static int locking_available(void) { struct active_request_slot *slot; struct slot_results results; struct strbuf in_buffer = STRBUF_INIT; struct buffer out_buffer = { STRBUF_INIT, 0 }; struct curl_slist *dav_headers = http_copy_default_headers(); struct xml_ctx ctx; int lock_flags = 0; char *escaped; escaped = xml_entities(repo->url); strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped); free(escaped); dav_headers = curl_slist_append(dav_headers, "Depth: 0"); dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml"); slot = get_active_slot(); slot->results = &results; curl_setup_http(slot->curl, repo->url, DAV_PROPFIND, &out_buffer, fwrite_buffer); curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers); curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer); if (start_active_slot(slot)) { run_active_slot(slot); if (results.curl_result == CURLE_OK) { XML_Parser parser = XML_ParserCreate(NULL); enum XML_Status result; ctx.name = xcalloc(10, 1); ctx.len = 0; ctx.cdata = NULL; ctx.userFunc = handle_lockprop_ctx; ctx.userData = &lock_flags; XML_SetUserData(parser, &ctx); XML_SetElementHandler(parser, xml_start_tag, xml_end_tag); result = XML_Parse(parser, in_buffer.buf, in_buffer.len, 1); free(ctx.name); if (result != XML_STATUS_OK) { fprintf(stderr, "XML error: %s\n", XML_ErrorString( XML_GetErrorCode(parser))); lock_flags = 0; } XML_ParserFree(parser); if (!lock_flags) error("no DAV locking support on %s", repo->url); } else { error("Cannot access URL %s, return code %d", repo->url, results.curl_result); lock_flags = 0; } } else { error("Unable to start PROPFIND request on %s", repo->url); } strbuf_release(&out_buffer.buf); strbuf_release(&in_buffer); curl_slist_free_all(dav_headers); return lock_flags; }
/** This function parses the beginning of the file to detect the fields */ void OGRJMLLayer::LoadSchema() { if (bHasReadSchema) return; bHasReadSchema = true; oParser = OGRCreateExpatXMLParser(); XML_SetElementHandler(oParser, ::startElementLoadSchemaCbk, ::endElementLoadSchemaCbk); XML_SetCharacterDataHandler(oParser, ::dataHandlerCbk); XML_SetUserData(oParser, this); VSIFSeekL( fp, 0, SEEK_SET ); char aBuf[BUFSIZ]; int nDone = 0; do { nDataHandlerCounter = 0; const unsigned int nLen = static_cast<unsigned int>( VSIFReadL( aBuf, 1, sizeof(aBuf), fp ) ); nDone = VSIFEofL(fp); if (XML_Parse(oParser, aBuf, nLen, nDone) == XML_STATUS_ERROR) { CPLError( CE_Failure, CPLE_AppDefined, "XML parsing of JML file failed : %s at line %d, " "column %d", XML_ErrorString(XML_GetErrorCode(oParser)), static_cast<int>(XML_GetCurrentLineNumber(oParser)), static_cast<int>(XML_GetCurrentColumnNumber(oParser)) ); bStopParsing = true; } nWithoutEventCounter ++; } while ( !nDone && !bStopParsing && !bSchemaFinished && nWithoutEventCounter < 10 ); XML_ParserFree(oParser); oParser = nullptr; if (nWithoutEventCounter == 10) { CPLError(CE_Failure, CPLE_AppDefined, "Too much data inside one element. File probably corrupted"); bStopParsing = true; } if( osCollectionElement.empty() || osFeatureElement.empty() || osGeometryElement.empty() ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing CollectionElement, FeatureElement or " "GeometryElement" ); bStopParsing = true; } if( !osSRSName.empty() ) { if( osSRSName.find("http://www.opengis.net/gml/srs/epsg.xml#") == 0 ) { OGRSpatialReference* poSRS = new OGRSpatialReference(); poSRS->importFromEPSG(atoi(osSRSName.substr( strlen("http://www.opengis.net/gml/srs/epsg.xml#")).c_str())); poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS); poSRS->Release(); } } nJCSGMLInputTemplateDepth = 0; nCollectionElementDepth = 0; nFeatureCollectionDepth = 0; nFeatureElementDepth = 0; nGeometryElementDepth = 0; nColumnDepth = 0; nNameDepth = 0; nTypeDepth = 0; nAttributeElementDepth = 0; ResetReading(); }
bool wxXmlDocument::Load(wxInputStream& stream, const wxString& encoding, int flags) { #if wxUSE_UNICODE (void)encoding; #else m_encoding = encoding; #endif const size_t BUFSIZE = 1024; char buf[BUFSIZE]; wxXmlParsingContext ctx; bool done; XML_Parser parser = XML_ParserCreate(NULL); ctx.root = ctx.node = NULL; ctx.encoding = wxT("UTF-8"); // default in absence of encoding="" ctx.conv = NULL; #if !wxUSE_UNICODE if ( encoding.CmpNoCase(wxT("UTF-8")) != 0 ) ctx.conv = new wxCSConv(encoding); #endif ctx.removeWhiteOnlyNodes = (flags & wxXMLDOC_KEEP_WHITESPACE_NODES) == 0; XML_SetUserData(parser, (void*)&ctx); XML_SetElementHandler(parser, StartElementHnd, EndElementHnd); XML_SetCharacterDataHandler(parser, TextHnd); XML_SetStartCdataSectionHandler(parser, StartCdataHnd); XML_SetCommentHandler(parser, CommentHnd); XML_SetDefaultHandler(parser, DefaultHnd); XML_SetUnknownEncodingHandler(parser, UnknownEncodingHnd, NULL); bool ok = true; do { size_t len = stream.Read(buf, BUFSIZE).LastRead(); done = (len < BUFSIZE); if (!XML_Parse(parser, buf, len, done)) { wxString error(XML_ErrorString(XML_GetErrorCode(parser)), *wxConvCurrent); wxLogError(_("XML parsing error: '%s' at line %d"), error.c_str(), XML_GetCurrentLineNumber(parser)); ok = false; break; } } while (!done); if (ok) { if (!ctx.version.empty()) SetVersion(ctx.version); if (!ctx.encoding.empty()) SetFileEncoding(ctx.encoding); SetRoot(ctx.root); } else { delete ctx.root; } XML_ParserFree(parser); #if !wxUSE_UNICODE if ( ctx.conv ) delete ctx.conv; #endif return ok; }
BOOLEAN ReadInlbeStats(STR fileName) { HWFILE hFile; UINT32 uiBytesRead; UINT32 uiFSize; CHAR8 * lpcBuffer; XML_Parser parser = XML_ParserCreate(NULL); lbeParseData pData; DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading LoadBearingEquipment.xml" ); // Open loadbearingequipment file hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE ); if ( !hFile ) return( FALSE ); uiFSize = FileGetSize(hFile); lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1); //Read in block if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) ) { MemFree(lpcBuffer); return( FALSE ); } lpcBuffer[uiFSize] = 0; //add a null terminator FileClose( hFile ); XML_SetElementHandler(parser, lbeStartElementHandle, lbeEndElementHandle); XML_SetCharacterDataHandler(parser, lbeCharacterDataHandle); memset(&pData,0,sizeof(pData)); //pData.curArray = LoadBearingEquipment; //pData.maxArraySize = MAXITEMS; XML_SetUserData(parser, &pData); LoadBearingEquipment.clear(); if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE)) { CHAR8 errorBuf[511]; sprintf(errorBuf, "XML Parser Error in LoadBearingEquipment.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); LiveMessage(errorBuf); MemFree(lpcBuffer); return FALSE; } MemFree(lpcBuffer); XML_ParserFree(parser); return( TRUE ); }
struct audio_route *audio_route_init(unsigned int card, const char *xml_path) { struct config_parse_state state; XML_Parser parser; FILE *file; int bytes_read; void *buf; int i; struct audio_route *ar; ar = calloc(1, sizeof(struct audio_route)); if (!ar) goto err_calloc; ar->mixer = mixer_open(card); if (!ar->mixer) { ALOGE("Unable to open the mixer, aborting."); goto err_mixer_open; } ar->mixer_path = NULL; ar->mixer_path_size = 0; ar->num_mixer_paths = 0; /* allocate space for and read current mixer settings */ if (alloc_mixer_state(ar) < 0) goto err_mixer_state; /* use the default XML path if none is provided */ if (xml_path == NULL) xml_path = MIXER_XML_PATH; file = fopen(xml_path, "r"); if (!file) { ALOGE("Failed to open %s", xml_path); goto err_fopen; } parser = XML_ParserCreate(NULL); if (!parser) { ALOGE("Failed to create XML parser"); goto err_parser_create; } memset(&state, 0, sizeof(state)); state.ar = ar; XML_SetUserData(parser, &state); XML_SetElementHandler(parser, start_tag, end_tag); for (;;) { buf = XML_GetBuffer(parser, BUF_SIZE); if (buf == NULL) goto err_parse; bytes_read = fread(buf, 1, BUF_SIZE, file); if (bytes_read < 0) goto err_parse; if (XML_ParseBuffer(parser, bytes_read, bytes_read == 0) == XML_STATUS_ERROR) { ALOGE("Error in mixer xml (%s)", MIXER_XML_PATH); goto err_parse; } if (bytes_read == 0) break; } /* apply the initial mixer values, and save them so we can reset the mixer to the original values */ audio_route_update_mixer(ar); save_mixer_state(ar); XML_ParserFree(parser); fclose(file); return ar; err_parse: XML_ParserFree(parser); err_parser_create: fclose(file); err_fopen: free_mixer_state(ar); err_mixer_state: mixer_close(ar->mixer); err_mixer_open: free(ar); ar = NULL; err_calloc: return NULL; }
int OGRSVGDataSource::Open( const char * pszFilename, int bUpdateIn) { if (bUpdateIn) { CPLError(CE_Failure, CPLE_NotSupported, "OGR/SVG driver does not support opening a file in update mode"); return FALSE; } #ifdef HAVE_EXPAT pszName = CPLStrdup( pszFilename ); /* -------------------------------------------------------------------- */ /* Determine what sort of object this is. */ /* -------------------------------------------------------------------- */ VSIStatBufL sStatBuf; if( VSIStatL( pszFilename, &sStatBuf ) != 0 ) return FALSE; if( VSI_ISDIR(sStatBuf.st_mode) ) return FALSE; CPLString osFilename(pszFilename); if (EQUAL(CPLGetExtension(pszFilename), "svgz") && strstr(pszFilename, "/vsigzip/") == NULL) { osFilename = CPLString("/vsigzip/") + pszFilename; pszFilename = osFilename.c_str(); } VSILFILE* fp = VSIFOpenL(pszFilename, "r"); if (fp == NULL) return FALSE; eValidity = SVG_VALIDITY_UNKNOWN; XML_Parser oParser = OGRCreateExpatXMLParser(); oCurrentParser = oParser; XML_SetUserData(oParser, this); XML_SetElementHandler(oParser, ::startElementValidateCbk, NULL); XML_SetCharacterDataHandler(oParser, ::dataHandlerValidateCbk); char aBuf[BUFSIZ]; int nDone; unsigned int nLen; int nCount = 0; /* Begin to parse the file and look for the <svg> element */ /* It *MUST* be the first element of an XML file */ /* So once we have read the first element, we know if we can */ /* handle the file or not with that driver */ do { nDataHandlerCounter = 0; nLen = (unsigned int) VSIFReadL( aBuf, 1, sizeof(aBuf), fp ); nDone = VSIFEofL(fp); if (XML_Parse(oParser, aBuf, nLen, nDone) == XML_STATUS_ERROR) { if (nLen <= BUFSIZ-1) aBuf[nLen] = 0; else aBuf[BUFSIZ-1] = 0; if (strstr(aBuf, "<?xml") && strstr(aBuf, "<svg")) { CPLError(CE_Failure, CPLE_AppDefined, "XML parsing of SVG file failed : %s at line %d, column %d", XML_ErrorString(XML_GetErrorCode(oParser)), (int)XML_GetCurrentLineNumber(oParser), (int)XML_GetCurrentColumnNumber(oParser)); } eValidity = SVG_VALIDITY_INVALID; break; } if (eValidity == SVG_VALIDITY_INVALID) { break; } else if (eValidity == SVG_VALIDITY_VALID) { break; } else { /* After reading 50 * BUFSIZE bytes, and not finding whether the file */ /* is SVG or not, we give up and fail silently */ nCount ++; if (nCount == 50) break; } } while (!nDone && nLen > 0 ); XML_ParserFree(oParser); VSIFCloseL(fp); if (eValidity == SVG_VALIDITY_VALID) { if (bIsCloudmade) { nLayers = 3; papoLayers =(OGRSVGLayer **) CPLRealloc(papoLayers, nLayers * sizeof(OGRSVGLayer*)); papoLayers[0] = new OGRSVGLayer( pszFilename, "points", SVG_POINTS, this ); papoLayers[1] = new OGRSVGLayer( pszFilename, "lines", SVG_LINES, this ); papoLayers[2] = new OGRSVGLayer( pszFilename, "polygons", SVG_POLYGONS, this ); } else { CPLDebug("SVG", "%s seems to be a SVG file, but not a Cloudmade vector one.", pszFilename); } } return (nLayers > 0); #else char aBuf[256]; VSILFILE* fp = VSIFOpenL(pszFilename, "r"); if (fp) { unsigned int nLen = (unsigned int)VSIFReadL( aBuf, 1, 255, fp ); aBuf[nLen] = 0; if (strstr(aBuf, "<?xml") && strstr(aBuf, "<svg") && strstr(aBuf, "http://cloudmade.com/")) { CPLError(CE_Failure, CPLE_NotSupported, "OGR/SVG driver has not been built with read support. " "Expat library required"); } VSIFCloseL(fp); } return FALSE; #endif }
static void ngx_http_dav_ext_propfind_handler(ngx_http_request_t *r) { ngx_chain_t *c; ngx_buf_t *b; XML_Parser parser; ngx_uint_t status; ngx_http_dav_ext_ctx_t *ctx; ctx = ngx_http_get_module_ctx(r, ngx_http_dav_ext_module); if (ctx == NULL) { ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_dav_ext_ctx_t)); ngx_http_set_ctx(r, ctx, ngx_http_dav_ext_module); } c = r->request_body->bufs; status = NGX_OK; parser = XML_ParserCreate(NULL); XML_SetUserData(parser, ctx); XML_SetElementHandler(parser, ngx_http_dav_ext_start_xml_elt, ngx_http_dav_ext_end_xml_elt); for(; c != NULL && c->buf != NULL && !c->buf->last_buf; c = c->next) { b = c ->buf; if (!XML_Parse(parser, (const char*)b->pos, b->last - b->pos, b->last_buf)) { ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0, "dav_ext propfind XML error"); status = NGX_ERROR; break; } } XML_ParserFree(parser); if (status == NGX_OK) { r->headers_out.status = 207; ngx_str_set(&r->headers_out.status_line, "207 Multi-Status"); ngx_http_send_header(r); ngx_http_finalize_request(r, ngx_http_dav_ext_send_propfind(r)); } else { r->headers_out.status = NGX_HTTP_INTERNAL_SERVER_ERROR; r->header_only = 1; r->headers_out.content_length_n = 0; ngx_http_finalize_request(r, ngx_http_send_header(r)); } }
void node_expat::on_end_tag(const char* pszName) { --__walker_depth; _data = __data.str(); this->finished(); XML_SetUserData(_parser->get_parser(), _old_user_data); }
int RD_UnassignSchedCode( const char hostname[], const char username[], const char passwd[], const unsigned cartnum, const char code[]) { char post[1500]; char url[1500]; CURL *curl=NULL; XML_Parser parser; struct xml_data xml_data; long response_code; int i; int code_valid = 1; char errbuf[CURL_ERROR_SIZE]; CURLcode res; /* Check Code */ for (i = 0 ; i < strlen(code) ; i++) { if ((code[i]==32) || (i > 9)) { code_valid=0; break; } } if (!code_valid) { fprintf(stderr," Scheduler Code : %s Is Invalid! \n",code); return -1; } /* * Setup the CURL call */ memset(&xml_data,0,sizeof(xml_data)); parser=XML_ParserCreate(NULL); XML_SetUserData(parser,&xml_data); XML_SetElementHandler(parser,__UnAssignSchedCodeElementStart, __UnAssignSchedCodeElementEnd); XML_SetCharacterDataHandler(parser,__UnAssignSchedCodeElementData); snprintf(url,1500,"http://%s/rd-bin/rdxport.cgi",hostname); snprintf(post,1500,"COMMAND=26&LOGIN_NAME=%s&PASSWORD=%s&CART_NUMBER=%u&CODE=%s", username,passwd,cartnum,code); if((curl=curl_easy_init())==NULL) { return -1; } curl_easy_setopt(curl,CURLOPT_WRITEDATA,parser); curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,__UnAssignSchedCodeCallback); curl_easy_setopt(curl,CURLOPT_URL,url); curl_easy_setopt(curl,CURLOPT_POST,1); curl_easy_setopt(curl,CURLOPT_POSTFIELDS,post); curl_easy_setopt(curl,CURLOPT_NOPROGRESS,1); curl_easy_setopt(curl,CURLOPT_ERRORBUFFER,errbuf); // curl_easy_setopt(curl,CURLOPT_VERBOSE,1); res = curl_easy_perform(curl); if(res != CURLE_OK) { size_t len = strlen(errbuf); fprintf(stderr, "\nlibcurl error: (%d)", res); if (len) fprintf(stderr, "%s%s", errbuf, ((errbuf[len-1] != '\n') ? "\n" : "")); else fprintf(stderr, "%s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); return -1; } /* The response OK - so figure out if we got what we wanted.. */ curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&response_code); curl_easy_cleanup(curl); if (response_code > 199 && response_code < 300) { return 0; } else { fprintf(stderr," Call Returned Error: %s\n",xml_data.strbuf); return (int)response_code; } }
CONF_LIST *create_conf_list() { char buff[BUFSIZ], path[BUFSIZ]; FILE *fp = NULL; CONF_LIST *list; XML_Parser p; expat_userdata userdata; int xml_error = XML_ERROR_NONE; if (get_config_dradio_menu_path(path, sizeof(path)) == -1) return NULL; if (write_config_inputconf() == -1) return NULL; if ((iconv_cd = iconv_open("ISO-8859-1", "UTF-8")) == (iconv_t) -1) { perror("iconv_open"); return NULL; } p = XML_ParserCreate(NULL); if (!p) { fprintf(stderr, "Couldn't allocate memory for parser\n"); return NULL; } list = conf_list_init(); userdata.list = list; userdata.parser = p; XML_SetUserData(p, &userdata); XML_SetElementHandler(p, start_element_handler, end_element_handler); fp = fopen(path, "r"); if (fp == NULL) { perror("fopen"); return NULL; } for (;;) { int done; int len; len = (int)fread(buff, sizeof(char), sizeof(buff), fp); if (ferror(fp)) { perror("fread"); return NULL; } done = feof(fp); if (XML_Parse(p, buff, len, done) == XML_STATUS_ERROR) { xml_error = XML_GetErrorCode(p); switch (xml_error) { case XML_ERROR_ABORTED: ; /* This is a XML_StopParser event, error message has already written */ break; default: fprintf(stderr, "Parse error in '%s' at line %lu column %lu: %s\n", path, XML_GetCurrentLineNumber(p), XML_GetCurrentColumnNumber(p), XML_ErrorString(xml_error)); break; } break; } if (done) break; } XML_ParserFree(p); fclose(fp); iconv_close(iconv_cd); if (xml_error != XML_ERROR_NONE) { conf_list_free(list); return NULL; } return list; }
void runexpatNSuD(enum isource from, void * list, XML_StartElementHandler startElement, XML_EndElementHandler endElement, XML_Char *ns_sep_p, void *uData) { const char *buf; XML_Parser parser; static int depth; struct runinfo *rip = calloc(1,sizeof(struct runinfo)); if (curr_rip) { runinfo_stack = list_create(LIST_LIFO); list_add(runinfo_stack,curr_rip); } curr_rip = rip; if (ns_sep_p) parser = XML_ParserCreateNS("utf-8",*ns_sep_p); else parser = XML_ParserCreate("utf-8"); if (!parser) { fprintf(stderr,"runexpat: NULL return from XML_ParserCreate()\n"); return; } depth = 0; runexpat_init(rip); rip->from = from; rip->list = list; rip->charData_buflen = 1024; rip->charData_buf = malloc(sizeof(XML_Char) * rip->charData_buflen); rip->charData_bufused = 0; if (uData) XML_SetUserData(parser, uData); else XML_SetUserData(parser, &depth); XML_SetElementHandler(parser, startElement, endElement); XML_SetProcessingInstructionHandler(parser, piHandler); XML_SetCharacterDataHandler(parser, charHandler); if (!XML_Parse(parser,"<rp-wrap>",9,0)) fail(parser, rip); set_input(rip); for (;;) { if (NULL == (buf = get_input(rip))) break; if (rip->input_len && !XML_Parse(parser, buf, rip->input_len, 0)) { fprintf(stderr,"===\n%s\n===\n",buf); fail(parser, rip); } } if (!XML_Parse(parser,"</rp-wrap>",10,1)) fail(parser, rip); XML_ParserFree(parser); runexpat_term(rip); free(rip->fname); free(rip); if (runinfo_stack) { curr_rip = list_pop(runinfo_stack); curr_fname = curr_rip->fname; if (!list_len(runinfo_stack)) { free(runinfo_stack); runinfo_stack = NULL; } } else curr_rip = NULL; }
static int skin_load_file(SkinScreen* skin, char *file) { FILE* skin_xml; char buffer[BUFFER_SIZE]; int done; XML_Parser parser = XML_ParserCreate(NULL); if (parser) { SkinParser parserconfig; parserconfig.skin = skin; parserconfig.layout = NULL; XML_SetUserData( parser, (void*)&parserconfig ); XML_SetElementHandler(parser, parser_start_hndl, parser_end_hndl); skin_xml = fopen(file, "r"); //printf("skin_config_c: skin_load_file = '%s'\n", file); if (!skin_xml) { fprintf(stderr, "Error opening skin file '%s'\n", file); XML_ParserFree(parser); return -1; } // Extract the path of the given XML file to be used as a default path char *p = strrchr(file, '/'); if (p) { int index = p - file + 1; p = qemu_mallocz(index + 1); strncpy(p, file, index); // last character already zeroed at malloc } else { p = qemu_mallocz(3); p[0] = '.'; p[1] = '/'; // last character already zeroed at malloc } parserconfig.filepath = p; XML_SetUserData(parser, (void*)&parserconfig); XML_SetElementHandler(parser, parser_start_hndl, parser_end_hndl); do { if (fgets(buffer, sizeof(buffer), skin_xml) == NULL) done = 1; else { done = feof(skin_xml); if (!XML_Parse(parser, buffer, strlen(buffer), done)) { fprintf(stderr, "Parse error at line %d: %s\n", (int)XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); // Continue anyway } } } while (!done); if (done && !feof(skin_xml)) { fprintf(stderr, "Parse error, unexpected EOF\n"); // Continue anyway } XML_ParserFree(parser); qemu_free(parserconfig.filepath); // Create a buffer to store the information fclose(skin_xml); return skin_activate_layout(skin, skin->rotation); } return -1; }
void KML::checkValidity() { std::size_t nDone = 0; std::size_t nLen = 0; char aBuf[BUFSIZ] = { 0 }; if(poTrunk_ != NULL) { delete poTrunk_; poTrunk_ = NULL; } if(poCurrent_ != NULL) { delete poCurrent_; poCurrent_ = NULL; } if(pKMLFile_ == NULL) { this->sError_ = "No file given"; return; } XML_Parser oParser = OGRCreateExpatXMLParser(); XML_SetUserData(oParser, this); XML_SetElementHandler(oParser, startElementValidate, NULL); XML_SetCharacterDataHandler(oParser, dataHandlerValidate); int nCount = 0; oCurrentParser = oParser; /* Parses the file until we find the first element */ do { nDataHandlerCounter = 0; nLen = (int)VSIFReadL( aBuf, 1, sizeof(aBuf), pKMLFile_ ); nDone = VSIFEofL(pKMLFile_); if (XML_Parse(oParser, aBuf, nLen, nDone) == XML_STATUS_ERROR) { if (nLen <= BUFSIZ-1) aBuf[nLen] = 0; else aBuf[BUFSIZ-1] = 0; if( strstr(aBuf, "<?xml") && ( strstr(aBuf, "<kml") || (strstr(aBuf, "<Document") && strstr(aBuf, "/kml/2.")) ) ) { CPLError(CE_Failure, CPLE_AppDefined, "XML parsing of KML file failed : %s at line %d, column %d", XML_ErrorString(XML_GetErrorCode(oParser)), (int)XML_GetCurrentLineNumber(oParser), (int)XML_GetCurrentColumnNumber(oParser)); } validity = KML_VALIDITY_INVALID; XML_ParserFree(oParser); VSIRewindL(pKMLFile_); return; } nCount ++; /* After reading 50 * BUFSIZE bytes, and not finding whether the file */ /* is KML or not, we give up and fail silently */ } while (!nDone && nLen > 0 && validity == KML_VALIDITY_UNKNOWN && nCount < 50); XML_ParserFree(oParser); VSIRewindL(pKMLFile_); poCurrent_ = NULL; }
bool Csocketcan::open(const char *pUsername, const char *pPassword, const char *pHost, short port, const char *pPrefix, const char *pConfig) { bool rv = true; std::string wxstr = std::string(pConfig); m_username = std::string(pUsername); m_password = std::string(pPassword); m_host = std::string(pHost); m_port = port; m_prefix = std::string(pPrefix); // Parse the configuration string. It should // have the following form path std::deque<std::string> tokens; vscp_split( tokens, std::string(pConfig), ";" ); // Check for socketcan interface in configuration string if (!tokens.empty()) { // Interface m_interface = tokens.front(); tokens.pop_front(); } // First log on to the host and get configuration // variables if (VSCP_ERROR_SUCCESS != m_srv.doCmdOpen(m_host, m_port, m_username, m_password)) { syslog(LOG_ERR, "%s", (const char *)"Unable to connect to " "VSCP TCP/IP interface. Terminating!"); return false; } // Find the channel id uint32_t ChannelID; m_srv.doCmdGetChannelID(&ChannelID); // m_srv.doCmdGetGUID( m_ifguid ); // The server should hold configuration data for each sensor // we want to monitor. // // We look for // // _interface - The socketcan interface to use. Typically this // is “can0, can0, can1... // // _filter - Standard VSCP filter in string form. // 1,0x0000,0x0006, // ff:ff:ff:ff:ff:ff:ff:01:00:00:00:00:00:00:00:00 // as priority,class,type,GUID // Used to filter what events that is received from // the socketcan interface. If not give all events // are received. // _mask - Standard VSCP mask in string form. // 1,0x0000,0x0006, // ff:ff:ff:ff:ff:ff:ff:01:00:00:00:00:00:00:00:00 // as priority,class,type,GUID // Used to filter what events that is received from // the socketcan interface. If not give all events // are received. // // <setup interface="vcan0" // filter="" // mask="" /> // std::string str; std::string strName = m_prefix + std::string("_interface"); m_srv.getRemoteVariableValue(strName, m_interface); strName = m_prefix + std::string("_filter"); if (m_srv.getRemoteVariableValue(strName, str)) { vscp_readFilterFromString(&m_vscpfilter, str); } strName = m_prefix + std::string("_mask"); if (m_srv.getRemoteVariableValue(strName, str)) { vscp_readMaskFromString(&m_vscpfilter, str); } m_srv.doClrInputQueue(); // XML setup std::string strSetupXML; strName = m_prefix + std::string("_setup"); if (VSCP_ERROR_SUCCESS == m_srv.getRemoteVariableValue(strName, strSetupXML, true)) { XML_Parser xmlParser = XML_ParserCreate("UTF-8"); XML_SetUserData(xmlParser, this); XML_SetElementHandler(xmlParser, startSetupParser, endSetupParser); int bytes_read; void *buff = XML_GetBuffer(xmlParser, XML_BUFF_SIZE); strncpy((char *)buff, strSetupXML.c_str(), strSetupXML.length()); bytes_read = strSetupXML.length(); if (!XML_ParseBuffer(xmlParser, bytes_read, bytes_read == 0)) { syslog(LOG_ERR, "Failed parse XML setup."); } XML_ParserFree(xmlParser); } // start the workerthread if ( pthread_create( &m_threadWork, NULL, workerThread, this ) ) { syslog( LOG_CRIT, "Unable to start worker thread." ); return false; } // Close the channel m_srv.doCmdClose(); return rv; }
ExpatWrapper::ExpatWrapper() { parser = XML_ParserCreate((XML_Char *) "UTF-8"); XML_SetUserData(parser, (void *) this); XML_SetElementHandler(parser, startElementCallback, endElementCallback); XML_SetCharacterDataHandler(parser, characterDataCallback); }
BOOLEAN ReadInActionItems(STR fileName, BOOLEAN localizedVersion) { HWFILE hFile; UINT32 uiBytesRead; UINT32 uiFSize; CHAR8 * lpcBuffer; XML_Parser parser = XML_ParserCreate(NULL); actionItemsParseData pData; DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading ActionItems.xml" ); ActionItems_TextOnly = localizedVersion; // Open file hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE ); if ( !hFile ) return( localizedVersion ); uiFSize = FileGetSize(hFile); lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1); //Read in block if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) ) { MemFree(lpcBuffer); return( FALSE ); } lpcBuffer[uiFSize] = 0; //add a null terminator FileClose( hFile ); XML_SetElementHandler(parser, actionItemsStartElementHandle, actionItemsEndElementHandle); XML_SetCharacterDataHandler(parser, actionItemsCharacterDataHandle); memset(&pData,0,sizeof(pData)); XML_SetUserData(parser, &pData); if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE)) { CHAR8 errorBuf[511]; sprintf(errorBuf, "XML Parser Error in ActionItems.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); LiveMessage(errorBuf); MemFree(lpcBuffer); return FALSE; } MemFree(lpcBuffer); XML_ParserFree(parser); return( TRUE ); }
/* The handler. Create a new parser and/or filter context where appropriate * and parse the chunks of data received from the brigade */ static int xmlEntHandler( ap_filter_t *f, apr_bucket_brigade *brigade ) { xmlEntContext* ctx = f->ctx; apr_bucket* currentBucket = NULL; apr_pool_t* pool = f->r->pool; const char* data; apr_size_t len; /* load the per-dir/location config */ xmlEntConfig* config = ap_get_module_config( f->r->per_dir_config, &xmlent_module ); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, f->r, "XMLENT Config:\nContent Type = %s, " "Strip PI = %s, Strip Comments = %s, Doctype = %s", config->contentType, (config->stripPI) ? "yes" : "no", (config->stripComments) ? "yes" : "no", config->doctype); /* set the content type based on the config */ ap_set_content_type(f->r, config->contentType); /* create the XML parser */ int firstrun = 0; if( parser == NULL ) { firstrun = 1; parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, f); XML_SetElementHandler(parser, startElement, endElement); XML_SetCharacterDataHandler(parser, charHandler); if(!config->stripDoctype) XML_SetStartDoctypeDeclHandler( parser, doctypeHandler ); if(!config->stripPI) XML_SetProcessingInstructionHandler(parser, handlePI); if(!config->stripComments) XML_SetCommentHandler(parser, handleComment); } /* create the filter context */ if( ctx == NULL ) { f->ctx = ctx = apr_pcalloc( pool, sizeof(*ctx)); ctx->brigade = apr_brigade_create( pool, f->c->bucket_alloc ); ctx->parser = parser; } if(firstrun) { /* we haven't started writing the data to the stream yet */ /* go ahead and write the doctype out if we have one defined */ if(config->doctype) { ap_log_rerror( APLOG_MARK, APLOG_DEBUG, 0, f->r, "XMLENT DOCTYPE => %s", config->doctype); _fwrite(f, "%s\n", config->doctype); } } /* cycle through the buckets in the brigade */ while (!APR_BRIGADE_EMPTY(brigade)) { /* grab the next bucket */ currentBucket = APR_BRIGADE_FIRST(brigade); /* clean up when we're done */ if (APR_BUCKET_IS_EOS(currentBucket) || APR_BUCKET_IS_FLUSH(currentBucket)) { APR_BUCKET_REMOVE(currentBucket); APR_BRIGADE_INSERT_TAIL(ctx->brigade, currentBucket); ap_pass_brigade(f->next, ctx->brigade); XML_ParserFree(parser); parser = NULL; return APR_SUCCESS; } /* read the incoming data */ int s = apr_bucket_read(currentBucket, &data, &len, APR_NONBLOCK_READ); if( s != APR_SUCCESS ) { ap_log_rerror( APLOG_MARK, APLOG_ERR, 0, f->r, "XMLENT error reading data from filter with status %d", s); return s; } if (len > 0) { ap_log_rerror( APLOG_MARK, APLOG_DEBUG, 0, f->r, "XMLENT read %d bytes", (int)len); /* push data into the XML push parser */ if ( XML_Parse(ctx->parser, data, len, 0) == XML_STATUS_ERROR ) { char tmp[len+1]; memcpy(tmp, data, len); tmp[len] = '\0'; /* log and die on XML errors */ ap_log_rerror( APLOG_MARK, APLOG_ERR, 0, f->r, "XMLENT XML Parse Error: %s at line %d: parsing %s: data %s", XML_ErrorString(XML_GetErrorCode(ctx->parser)), (int) XML_GetCurrentLineNumber(ctx->parser), f->r->filename, tmp); XML_ParserFree(parser); parser = NULL; return HTTP_INTERNAL_SERVER_ERROR; } } /* so a subrequest doesn't re-read this bucket */ apr_bucket_delete(currentBucket); } apr_brigade_destroy(brigade); return APR_SUCCESS; }
int messdocs(const char *toc_filename, const char *dest_dir, const char *help_project_filename, const char *help_contents_filename, const char *help_filename) { char buf[4096]; struct messdocs_state state; int len; int done; FILE *in; FILE *chm_hhp; int i; char *s; XML_Memory_Handling_Suite memcallbacks; memset(&state, 0, sizeof(state)); state.m_pool = pool_alloc_lib(NULL); /* open the DOC */ in = fopen(toc_filename, "r"); if (!in) { fprintf(stderr, "Cannot open TOC file '%s'\n", toc_filename); goto error; } /* figure out the TOC directory */ state.m_toc_dir = pool_strdup_lib(state.m_pool, toc_filename); if (!state.m_toc_dir) goto outofmemory; for (i = strlen(state.m_toc_dir) - 1; (i > 0) && !osd_is_path_separator(state.m_toc_dir[i]); i--) state.m_toc_dir[i] = '\0'; /* clean the target directory */ rmdir_recursive(dest_dir); osd_mkdir(dest_dir); /* create the help contents file */ s = (char*)pool_malloc_lib(state.m_pool, strlen(dest_dir) + 1 + strlen(help_project_filename) + 1); if (!s) goto outofmemory; strcpy(s, dest_dir); strcat(s, PATH_SEPARATOR); strcat(s, help_contents_filename); state.m_chm_toc = fopen(s, "w"); state.m_dest_dir = dest_dir; if (!state.m_chm_toc) { fprintf(stderr, "Cannot open file %s\n", s); goto error; } fprintf(state.m_chm_toc, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\"\n"); fprintf(state.m_chm_toc, "<HTML>\n"); fprintf(state.m_chm_toc, "<HEAD>\n"); fprintf(state.m_chm_toc, "</HEAD>\n"); fprintf(state.m_chm_toc, "<BODY>\n"); fprintf(state.m_chm_toc, "<OBJECT type=\"text/site properties\">\n"); fprintf(state.m_chm_toc, "\t<param name=\"Window Styles\" value=\"0x800625\">\n"); fprintf(state.m_chm_toc, "\t<param name=\"ImageType\" value=\"Folder\">\n"); fprintf(state.m_chm_toc, "\t<param name=\"Font\" value=\"Arial,8,0\">\n"); fprintf(state.m_chm_toc, "</OBJECT>\n"); fprintf(state.m_chm_toc, "<UL>\n"); /* create the XML parser */ memcallbacks.malloc_fcn = expat_malloc; memcallbacks.realloc_fcn = expat_realloc; memcallbacks.free_fcn = expat_free; state.m_parser = XML_ParserCreate_MM(NULL, &memcallbacks, NULL); if (!state.m_parser) goto outofmemory; XML_SetUserData(state.m_parser, &state); XML_SetElementHandler(state.m_parser, start_handler, end_handler); XML_SetCharacterDataHandler(state.m_parser, data_handler); do { len = (int) fread(buf, 1, sizeof(buf), in); done = feof(in); if (XML_Parse(state.m_parser, buf, len, done) == XML_STATUS_ERROR) { process_error(&state, NULL, NULL); break; } } while(!done); fprintf(state.m_chm_toc, "</UL>\n"); fprintf(state.m_chm_toc, "</BODY></HTML>"); fclose(state.m_chm_toc); /* create the help project file */ s = (char*)pool_malloc_lib(state.m_pool, strlen(dest_dir) + 1 + strlen(help_project_filename) + 1); if (!s) goto outofmemory; strcpy(s, dest_dir); strcat(s, PATH_SEPARATOR); strcat(s, help_project_filename); chm_hhp = fopen(s, "w"); if (!chm_hhp) { fprintf(stderr, "Cannot open file %s\n", s); goto error; } fprintf(chm_hhp, "[OPTIONS]\n"); fprintf(chm_hhp, "Compiled file=%s\n", help_filename); fprintf(chm_hhp, "Contents file=%s\n", help_contents_filename); fprintf(chm_hhp, "Default topic=%s\n", state.m_default_topic); fprintf(chm_hhp, "Language=0x409 English (United States)\n"); fprintf(chm_hhp, "Title=%s\n", state.m_title); fprintf(chm_hhp, "\n"); fclose(chm_hhp); /* finish up */ XML_ParserFree(state.m_parser); fclose(in); pool_free_lib(state.m_pool); return state.m_error ? -1 : 0; outofmemory: fprintf(stderr, "Out of memory"); error: if (state.m_chm_toc) fclose(state.m_chm_toc); if (in) fclose(in); return -1; }
/****f* xml_element/xml_elem_parse_buf * NAME * xml_elem_parse_buf * SYNOPSIS * xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error) * FUNCTION * parse a buffer containing XML into an xml_element in-memory tree * INPUTS * in_buf - buffer containing XML document * len - length of buffer * options - input options. optional * error - error result data. optional. check if result is null. * RESULT * void * NOTES * The returned data must be free'd by caller * SEE ALSO * xml_elem_serialize_to_string () * xml_elem_free () * SOURCE */ xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error) { xml_element* xReturn = NULL; char buf[100] = ""; static STRUCT_XML_ELEM_INPUT_OPTIONS default_opts = {encoding_utf_8}; if(!options) { options = &default_opts; } if(in_buf) { XML_Parser parser; xml_elem_data mydata = {0, 0, 0, 0}; parser = XML_ParserCreate(NULL); mydata.root = xml_elem_new(); mydata.current = mydata.root; mydata.input_options = options; mydata.needs_enc_conversion = options->encoding && strcmp(options->encoding, encoding_utf_8); XML_SetElementHandler(parser, (XML_StartElementHandler)_xmlrpc_startElement, (XML_EndElementHandler)_xmlrpc_endElement); XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)_xmlrpc_charHandler); /* pass the xml_elem_data struct along */ XML_SetUserData(parser, (void*)&mydata); if(!len) { len = strlen(in_buf); } /* parse the XML */ if(XML_Parse(parser, in_buf, len, 1) == 0) { enum XML_Error err_code = XML_GetErrorCode(parser); int line_num = XML_GetCurrentLineNumber(parser); int col_num = XML_GetCurrentColumnNumber(parser); long byte_idx = XML_GetCurrentByteIndex(parser); int byte_total = XML_GetCurrentByteCount(parser); const XML_LChar * error_str = XML_ErrorString(err_code); if(byte_idx >= 0) { snprintf(buf, sizeof(buf), "\n\tdata beginning %ld before byte index: %s\n", byte_idx > 10 ? 10 : byte_idx, in_buf + (byte_idx > 10 ? byte_idx - 10 : byte_idx)); } fprintf(stderr, "expat reports error code %i\n" "\tdescription: %s\n" "\tline: %i\n" "\tcolumn: %i\n" "\tbyte index: %ld\n" "\ttotal bytes: %i\n%s ", err_code, error_str, line_num, col_num, byte_idx, byte_total, buf); /* error condition */ if(error) { error->parser_code = (long)err_code; error->line = line_num; error->column = col_num; error->byte_index = byte_idx; error->parser_error = error_str; } } else { xReturn = (xml_element*)Q_Head(&mydata.root->children); //xReturn->parent = NULL; } XML_ParserFree(parser); xml_elem_free_non_recurse(mydata.root); } return xReturn; }
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent, const QString& userName, const QString& password , const QString& authcfg ) { mUri = uri; mWkbType = wkbType; XML_Parser p = XML_ParserCreateNS( nullptr, NS_SEPARATOR ); XML_SetUserData( p, this ); XML_SetElementHandler( p, QgsGml::start, QgsGml::end ); XML_SetCharacterDataHandler( p, QgsGml::chars ); //start with empty extent mExtent.setMinimal(); QNetworkRequest request( mUri ); if ( !authcfg.isEmpty() ) { if ( !QgsAuthManager::instance()->updateNetworkRequest( request, authcfg ) ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request update failed for authcfg %1" ).arg( authcfg ), tr( "Network" ), QgsMessageLog::CRITICAL ); return 1; } } else if ( !userName.isNull() || !password.isNull() ) { request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( userName, password ).toAscii().toBase64() ); } QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog* progressDialog = nullptr; QWidget* mainWindow = nullptr; QWidgetList topLevelWidgets = qApp->topLevelWidgets(); for ( QWidgetList::const_iterator it = topLevelWidgets.constBegin(); it != topLevelWidgets.constEnd(); ++it ) { if (( *it )->objectName() == "QgisApp" ) { mainWindow = *it; break; } } if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) ); connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) ); connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( !readData.isEmpty() ) { if ( XML_Parse( p, readData.constData(), readData.size(), atEnd ) == 0 ) { XML_Error errorCode = XML_GetErrorCode( p ); QString errorString = tr( "Error: %1 on line %2, column %3" ) .arg( XML_ErrorString( errorCode ) ) .arg( XML_GetCurrentLineNumber( p ) ) .arg( XML_GetCurrentColumnNumber( p ) ); QgsMessageLog::logMessage( errorString, tr( "WFS" ) ); } } QCoreApplication::processEvents(); } QNetworkReply::NetworkError replyError = reply->error(); QString replyErrorString = reply->errorString(); delete reply; delete progressDialog; if ( replyError ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request failed with error: %1" ).arg( replyErrorString ), tr( "Network" ), QgsMessageLog::CRITICAL ); return 1; } if ( *mWkbType != QGis::WKBNoGeometry ) { if ( mExtent.isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } XML_ParserFree( p ); if ( extent ) *extent = mExtent; return 0; }
int DOM_DocumentLS_load(DOM_Document *doc, const DOM_String *uri) { FILE *fd; XML_Parser p; struct stack *stk; size_t n; // was ssize_t (DBL) void *buf; int ret, done; DOM_Exception=DOM_NO_ERR; //line added by DBL if (doc == NULL || uri == NULL) { DOM_Exception = DOM_NULL_POINTER_ERR; return 0; } fd = fopen(uri, "r"); if (fd == NULL) { DOM_Exception = DOM_SYSTEM_ERR; return 0; } p = XML_ParserCreate(NULL); if (p == NULL) { DOM_Exception = DOM_XML_PARSER_ERR; fclose(fd); return 0; } stk = stack_new(INT_MAX); if (stk == NULL || stack_push(stk, doc) == 0) { DOM_Exception = DOM_SYSTEM_ERR; XML_ParserFree(p); fclose(fd); stack_del(stk, NULL); return 0; } XML_SetElementHandler(p, start_fn, end_fn); XML_SetCharacterDataHandler(p, chardata_fn); XML_SetCommentHandler(p, comment_fn); XML_SetProcessingInstructionHandler(p , processing_fn); XML_SetUserData(p, stk); ret = 1; for ( ;; ) { if ((buf = XML_GetBuffer(p, BUF_SIZ)) == NULL) { DOM_Exception = DOM_NO_MEMORY_ERR; ret = 0; break; } if ((n = fread(buf, 1, BUF_SIZ, fd)) == 0 && ferror(fd)) { DOM_Exception = DOM_SYSTEM_ERR; ret = 0; break; } if (XML_ParseBuffer(p, (int) n, (done = feof(fd))) == 0 || DOM_Exception) { if (DOM_Exception == 0) { DOM_Exception = DOM_XML_PARSER_ERR; } ret = 0; break; } if (done) { break; } } stack_del(stk, NULL); XML_ParserFree(p); fclose(fd); return ret; }
am_config_t *am_parse_config_xml(unsigned long instance_id, const char *xml, size_t xml_sz, char log_enable) { static const char *thisfunc = "am_parse_config_xml():"; am_config_t *r = NULL; char *begin, *stream = NULL; size_t data_sz; pcre *x = NULL; const char *error = NULL; int erroroffset; am_xml_parser_ctx_t xctx = {.setting_value = 0, .conf = NULL, .rgx = NULL, .parser = NULL, .log_enable = log_enable, .data_sz = 0, .data = NULL, .status = AM_SUCCESS}; if (xml == NULL || xml_sz == 0) { AM_LOG_ERROR(instance_id, "%s memory allocation error", thisfunc); return NULL; } /* match [key]=value returned within <value>[key]=value_of_a_key</value> element */ x = pcre_compile("(?<=\\[)(.+?)(?=\\])\\]\\s*\\=\\s*(.+)", 0, &error, &erroroffset, NULL); if (x == NULL) { AM_LOG_ERROR(instance_id, "%s pcre error %s", thisfunc, error == NULL ? "" : error); } r = calloc(1, sizeof (am_config_t)); if (r == NULL) { AM_LOG_ERROR(instance_id, "%s memory allocation error", thisfunc); pcre_free(x); return NULL; } r->instance_id = instance_id; begin = strstr(xml, "![CDATA["); if (begin != NULL) { char *end = strstr(begin + 8, "]]>"); if (end != NULL) { stream = begin + 8; data_sz = end - (begin + 8); } } else { /* no CDATA */ stream = (char *) xml; data_sz = xml_sz; } if (stream != NULL && data_sz > 0) { XML_Parser parser = XML_ParserCreate("UTF-8"); xctx.parser = &parser; xctx.conf = r; xctx.rgx = x; XML_SetUserData(parser, &xctx); XML_SetElementHandler(parser, start_element, end_element); XML_SetCharacterDataHandler(parser, character_data); XML_SetEntityDeclHandler(parser, entity_declaration); if (XML_Parse(parser, stream, (int) data_sz, XML_TRUE) == XML_STATUS_ERROR) { const char *message = XML_ErrorString(XML_GetErrorCode(parser)); XML_Size line = XML_GetCurrentLineNumber(parser); XML_Size col = XML_GetCurrentColumnNumber(parser); AM_LOG_ERROR(instance_id, "%s xml parser error (%lu:%lu) %s", thisfunc, (unsigned long) line, (unsigned long) col, message); am_config_free(&r); r = NULL; } else { r->ts = time(NULL); } XML_ParserFree(parser); } if (xctx.status != AM_SUCCESS) { AM_LOG_ERROR(instance_id, "%s %s", thisfunc, am_strerror(xctx.status)); } pcre_free(x); decrypt_agent_passwords(r); update_agent_configuration_ttl(r); return r; }
/* * Initialize an IterParser object * * The Python arguments are: * * *fd*: A Python file object or a callable object * *buffersize*: The size of the read buffer */ static int IterParser_init(IterParser *self, PyObject *args, PyObject *kwds) { PyObject* fd = NULL; PyObject* read = NULL; ssize_t buffersize = 1 << 14; static char *kwlist[] = {"fd", "buffersize", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:IterParser.__init__", kwlist, &fd, &buffersize)) { return -1; } /* Keep the buffersize within a reasonable range */ self->buffersize = CLAMP(buffersize, (ssize_t)(1 << 10), (ssize_t)(1 << 24)); #ifdef __clang__ /* Clang can't handle the file descriptors Python gives us, so in that case, we just call the object's read method. */ read = PyObject_GetAttrString(fd, "read"); if (read != NULL) { fd = read; } #else self->file = PyObject_AsFileDescriptor(fd); if (self->file != -1) { /* This is a real C file handle or descriptor. We therefore need to allocate our own read buffer, and get the real C object. */ self->buffer = malloc((size_t)self->buffersize); if (self->buffer == NULL) { PyErr_SetString(PyExc_MemoryError, "Out of memory"); goto fail; } self->fd = fd; Py_INCREF(self->fd); lseek(self->file, 0, SEEK_SET); } else #endif if (PyCallable_Check(fd)) { /* fd is a Python callable */ self->fd = fd; Py_INCREF(self->fd); self->read = fd; Py_INCREF(self->read); } else { PyErr_SetString( PyExc_TypeError, "Arg 1 to iterparser must be a file object or callable object"); goto fail; } PyErr_Clear(); self->queue_read_idx = 0; self->queue_write_idx = 0; self->done = 0; self->text = malloc((size_t)buffersize * sizeof(XML_Char)); self->text_alloc = buffersize; if (self->text == NULL) { PyErr_SetString(PyExc_MemoryError, "Out of memory"); goto fail; } text_clear(self); #if PY_VERSION_HEX < 0x02060500 /* Due to Python issue #7249 */ self->read_args = PyTuple_Pack(1, PyInt_FromSsize_t(buffersize)); #else self->read_args = PyTuple_Pack(1, PyLong_FromSsize_t(buffersize)); #endif if (self->read_args == NULL) { goto fail; } self->dict_singleton = PyDict_New(); if (self->dict_singleton == NULL) { goto fail; } self->td_singleton = PyUnicode_FromString("TD"); if (self->td_singleton == NULL) { goto fail; } self->queue_size = buffersize / 2; self->queue = malloc(sizeof(PyObject*) * (size_t)self->queue_size); if (self->queue == NULL) { PyErr_SetString(PyExc_MemoryError, "Out of memory"); goto fail; } /* Set up an expat parser with our callbacks */ self->parser = XML_ParserCreate(NULL); if (self->parser == NULL) { PyErr_SetString(PyExc_MemoryError, "Out of memory"); goto fail; } XML_SetUserData(self->parser, self); XML_SetElementHandler( self->parser, (XML_StartElementHandler)startElement, (XML_EndElementHandler)endElement); XML_SetCharacterDataHandler( self->parser, (XML_CharacterDataHandler)characterData); XML_SetXmlDeclHandler( self->parser, (XML_XmlDeclHandler)xmlDecl); Py_XDECREF(read); return 0; fail: Py_XDECREF(read); Py_XDECREF(self->fd); Py_XDECREF(self->read); free(self->text); Py_XDECREF(self->dict_singleton); Py_XDECREF(self->td_singleton); Py_XDECREF(self->read_args); free(self->queue); return -1; }
int RD_ListCarts(struct rd_cart *carts[], const char hostname[], const char username[], const char passwd[], const char group_name[], const char filter[], const char type[], unsigned *numrecs) { char post[1500]; char url[1500]; CURL *curl=NULL; XML_Parser parser; struct xml_data xml_data; long response_code; char errbuf[CURL_ERROR_SIZE]; CURLcode res; /* Set number of recs so if fail already set */ *numrecs = 0; /* * Setup the CURL call */ memset(&xml_data,0,sizeof(xml_data)); parser=XML_ParserCreate(NULL); XML_SetUserData(parser,&xml_data); XML_SetElementHandler(parser,__ListCartsElementStart, __ListCartsElementEnd); XML_SetCharacterDataHandler(parser,__ListCartsElementData); snprintf(url,1500,"http://%s/rd-bin/rdxport.cgi",hostname); snprintf(post,1500,"COMMAND=6&LOGIN_NAME=%s&PASSWORD=%s&GROUP_NAME=%s&FILTER=%s&TYPE=%s", username,passwd,group_name,filter,type); if((curl=curl_easy_init())==NULL) { return -1; } curl_easy_setopt(curl,CURLOPT_WRITEDATA,parser); curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,__ListCartsCallback); curl_easy_setopt(curl,CURLOPT_URL,url); curl_easy_setopt(curl,CURLOPT_POST,1); curl_easy_setopt(curl,CURLOPT_POSTFIELDS,post); curl_easy_setopt(curl,CURLOPT_NOPROGRESS,1); curl_easy_setopt(curl,CURLOPT_ERRORBUFFER,errbuf); // curl_easy_setopt(curl,CURLOPT_VERBOSE,1); res = curl_easy_perform(curl); if(res != CURLE_OK) { size_t len = strlen(errbuf); fprintf(stderr, "\nlibcurl error: (%d)", res); if (len) fprintf(stderr, "%s%s", errbuf, ((errbuf[len-1] != '\n') ? "\n" : "")); else fprintf(stderr, "%s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); return -1; } /* The response OK - so figure out if we got what we wanted.. */ curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&response_code); curl_easy_cleanup(curl); if (response_code > 199 && response_code < 300) { *carts=xml_data.carts; *numrecs = xml_data.carts_quan; return 0; } else { fprintf(stderr," Call Returned Error: %s\n",xml_data.strbuf); return (int)response_code; } }
/** This function parses the whole file to build the schema */ void OGRSVGLayer::LoadSchema() { CPLAssert(poFeatureDefn == NULL); for(int i=0;i<poDS->GetLayerCount();i++) { OGRSVGLayer* poLayer = (OGRSVGLayer*)poDS->GetLayer(i); poLayer->poFeatureDefn = new OGRFeatureDefn( poLayer->osLayerName ); poLayer->poFeatureDefn->Reference(); poLayer->poFeatureDefn->SetGeomType(poLayer->GetGeomType()); poLayer->poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poLayer->poSRS); } oSchemaParser = OGRCreateExpatXMLParser(); XML_SetElementHandler(oSchemaParser, ::startElementLoadSchemaCbk, ::endElementLoadSchemaCbk); XML_SetCharacterDataHandler(oSchemaParser, ::dataHandlerLoadSchemaCbk); XML_SetUserData(oSchemaParser, this); if (fpSVG == NULL) return; VSIFSeekL( fpSVG, 0, SEEK_SET ); inInterestingElement = FALSE; depthLevel = 0; nWithoutEventCounter = 0; bStopParsing = FALSE; char aBuf[BUFSIZ]; int nDone; do { nDataHandlerCounter = 0; unsigned int nLen = (unsigned int)VSIFReadL( aBuf, 1, sizeof(aBuf), fpSVG ); nDone = VSIFEofL(fpSVG); if (XML_Parse(oSchemaParser, aBuf, nLen, nDone) == XML_STATUS_ERROR) { CPLError(CE_Failure, CPLE_AppDefined, "XML parsing of SVG file failed : %s at line %d, column %d", XML_ErrorString(XML_GetErrorCode(oSchemaParser)), (int)XML_GetCurrentLineNumber(oSchemaParser), (int)XML_GetCurrentColumnNumber(oSchemaParser)); bStopParsing = TRUE; break; } nWithoutEventCounter ++; } while (!nDone && !bStopParsing && nWithoutEventCounter < 1000); if (nWithoutEventCounter == 1000) { CPLError(CE_Failure, CPLE_AppDefined, "Too much data inside one element. File probably corrupted"); bStopParsing = TRUE; } XML_ParserFree(oSchemaParser); oSchemaParser = NULL; VSIFSeekL( fpSVG, 0, SEEK_SET ); }
/* * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it * should _only_ heed the information from that file, instead of trying to * determine the refs from the remote file system (badly: it does not even * know about packed-refs). */ static void remote_ls(const char *path, int flags, void (*userFunc)(struct remote_ls_ctx *ls), void *userData) { char *url = xstrfmt("%s%s", repo->url, path); struct active_request_slot *slot; struct slot_results results; struct strbuf in_buffer = STRBUF_INIT; struct buffer out_buffer = { STRBUF_INIT, 0 }; struct curl_slist *dav_headers = http_copy_default_headers(); struct xml_ctx ctx; struct remote_ls_ctx ls; ls.flags = flags; ls.path = xstrdup(path); ls.dentry_name = NULL; ls.dentry_flags = 0; ls.userData = userData; ls.userFunc = userFunc; strbuf_addstr(&out_buffer.buf, PROPFIND_ALL_REQUEST); dav_headers = curl_slist_append(dav_headers, "Depth: 1"); dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml"); slot = get_active_slot(); slot->results = &results; curl_setup_http(slot->curl, url, DAV_PROPFIND, &out_buffer, fwrite_buffer); curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers); curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer); if (start_active_slot(slot)) { run_active_slot(slot); if (results.curl_result == CURLE_OK) { XML_Parser parser = XML_ParserCreate(NULL); enum XML_Status result; ctx.name = xcalloc(10, 1); ctx.len = 0; ctx.cdata = NULL; ctx.userFunc = handle_remote_ls_ctx; ctx.userData = &ls; XML_SetUserData(parser, &ctx); XML_SetElementHandler(parser, xml_start_tag, xml_end_tag); XML_SetCharacterDataHandler(parser, xml_cdata); result = XML_Parse(parser, in_buffer.buf, in_buffer.len, 1); free(ctx.name); if (result != XML_STATUS_OK) { fprintf(stderr, "XML error: %s\n", XML_ErrorString( XML_GetErrorCode(parser))); } XML_ParserFree(parser); } } else { fprintf(stderr, "Unable to start PROPFIND request\n"); } free(ls.path); free(url); strbuf_release(&out_buffer.buf); strbuf_release(&in_buffer); curl_slist_free_all(dav_headers); }
int load_config() { XML_Parser p; FILE *fp; char *buffer; char *config_file, *home; int nb; /* Try the following configuration-files: * ~/.mimic.xml * /etc/mimic.xml */ fp = NULL; config_file = NULL; home = getenv("HOME"); if( home ){ if( (config_file = malloc(strlen(home) + 15)) == NULL){ perror("malloc()"); return -1; } sprintf(config_file, "%s/.mimic.xml", home); fp = fopen(config_file, "r"); } /* Try with /etc/mimic.xml */ if( !fp ){ if( config_file ) free(config_file); if( (config_file = strdup("/etc/mimic.xml")) == NULL ){ perror("strdup()"); return -1; } fp = fopen(config_file, "r"); } /* Print error, and exit */ if( !fp ){ free(config_file); printf("No usable configuration file found! (Please create ~/.mimic.xml)\n"); return -1; } p = XML_ParserCreate(NULL); if( ! p ) { fprintf(stderr, "XML_ParserCreate failed (not enough memory?)\n"); free(config_file); fclose(fp); return -1; } if( (buffer = XML_GetBuffer(p, BUFSIZE)) == NULL ){ perror("XML_GetBuffer()"); free(config_file); fclose(fp); return -1; } XML_SetElementHandler(p, start, end); XML_SetCharacterDataHandler(p, ch_data_handler); XML_SetUserData(p, &settings); while( !feof(fp) ){ nb = fread(buffer, 1, BUFSIZE, fp); if( ferror(fp) ){ perror("fread()"); return -1; } if( nb == 0 ) break; if( XML_ParseBuffer(p, nb, feof(fp)) == XML_STATUS_ERROR ){ fprintf(stderr, "XML parsing error at line %lu:\n%s\n", XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p))); fclose(fp); return -1; } } XML_ParserFree(p); fclose(fp); free(config_file); return 0; }
static struct remote_lock *lock_remote(const char *path, long timeout) { struct active_request_slot *slot; struct slot_results results; struct buffer out_buffer = { STRBUF_INIT, 0 }; struct strbuf in_buffer = STRBUF_INIT; char *url; char *ep; char timeout_header[25]; struct remote_lock *lock = NULL; struct curl_slist *dav_headers = http_copy_default_headers(); struct xml_ctx ctx; char *escaped; url = xstrfmt("%s%s", repo->url, path); /* Make sure leading directories exist for the remote ref */ ep = strchr(url + strlen(repo->url) + 1, '/'); while (ep) { char saved_character = ep[1]; ep[1] = '\0'; slot = get_active_slot(); slot->results = &results; curl_setup_http_get(slot->curl, url, DAV_MKCOL); if (start_active_slot(slot)) { run_active_slot(slot); if (results.curl_result != CURLE_OK && results.http_code != 405) { fprintf(stderr, "Unable to create branch path %s\n", url); free(url); return NULL; } } else { fprintf(stderr, "Unable to start MKCOL request\n"); free(url); return NULL; } ep[1] = saved_character; ep = strchr(ep + 1, '/'); } escaped = xml_entities(ident_default_email()); strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped); free(escaped); xsnprintf(timeout_header, sizeof(timeout_header), "Timeout: Second-%ld", timeout); dav_headers = curl_slist_append(dav_headers, timeout_header); dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml"); slot = get_active_slot(); slot->results = &results; curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer); curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers); curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer); lock = xcalloc(1, sizeof(*lock)); lock->timeout = -1; if (start_active_slot(slot)) { run_active_slot(slot); if (results.curl_result == CURLE_OK) { XML_Parser parser = XML_ParserCreate(NULL); enum XML_Status result; ctx.name = xcalloc(10, 1); ctx.len = 0; ctx.cdata = NULL; ctx.userFunc = handle_new_lock_ctx; ctx.userData = lock; XML_SetUserData(parser, &ctx); XML_SetElementHandler(parser, xml_start_tag, xml_end_tag); XML_SetCharacterDataHandler(parser, xml_cdata); result = XML_Parse(parser, in_buffer.buf, in_buffer.len, 1); free(ctx.name); if (result != XML_STATUS_OK) { fprintf(stderr, "XML error: %s\n", XML_ErrorString( XML_GetErrorCode(parser))); lock->timeout = -1; } XML_ParserFree(parser); } } else { fprintf(stderr, "Unable to start LOCK request\n"); } curl_slist_free_all(dav_headers); strbuf_release(&out_buffer.buf); strbuf_release(&in_buffer); if (lock->token == NULL || lock->timeout <= 0) { free(lock->token); free(lock->owner); free(url); FREE_AND_NULL(lock); } else { lock->url = url; lock->start_time = time(NULL); lock->next = repo->locks; repo->locks = lock; } return lock; }
CP_C_API cp_plugin_info_t * cp_load_plugin_descriptor(cp_context_t *context, const char *path, cp_status_t *error) { char *file = NULL; cp_status_t status = CP_OK; FILE *fh = NULL; XML_Parser parser = NULL; ploader_context_t *plcontext = NULL; cp_plugin_info_t *plugin = NULL; CHECK_NOT_NULL(context); CHECK_NOT_NULL(path); cpi_lock_context(context); cpi_check_invocation(context, CPI_CF_ANY, __func__); do { int path_len; // Construct the file name for the plug-in descriptor path_len = strlen(path); if (path_len == 0) { status = CP_ERR_IO; break; } if (path[path_len - 1] == CP_FNAMESEP_CHAR) { path_len--; } file = malloc((path_len + strlen(CP_PLUGIN_DESCRIPTOR) + 2) * sizeof(char)); if (file == NULL) { status = CP_ERR_RESOURCE; break; } strcpy(file, path); file[path_len] = CP_FNAMESEP_CHAR; strcpy(file + path_len + 1, CP_PLUGIN_DESCRIPTOR); // Open the file if ((fh = fopen(file, "rb")) == NULL) { status = CP_ERR_IO; break; } // Initialize the XML parsing parser = XML_ParserCreate(NULL); if (parser == NULL) { status = CP_ERR_RESOURCE; break; } XML_SetElementHandler(parser, start_element_handler, end_element_handler); // Initialize the parsing context if ((plcontext = malloc(sizeof(ploader_context_t))) == NULL) { status = CP_ERR_RESOURCE; break; } memset(plcontext, 0, sizeof(ploader_context_t)); if ((plcontext->plugin = malloc(sizeof(cp_plugin_info_t))) == NULL) { status = CP_ERR_RESOURCE; break; } plcontext->context = context; plcontext->configuration = NULL; plcontext->value = NULL; plcontext->parser = parser; plcontext->file = file; plcontext->state = PARSER_BEGIN; memset(plcontext->plugin, 0, sizeof(cp_plugin_info_t)); plcontext->plugin->name = NULL; plcontext->plugin->identifier = NULL; plcontext->plugin->version = NULL; plcontext->plugin->provider_name = NULL; plcontext->plugin->abi_bw_compatibility = NULL; plcontext->plugin->api_bw_compatibility = NULL; plcontext->plugin->plugin_path = NULL; plcontext->plugin->req_cpluff_version = NULL; plcontext->plugin->imports = NULL; plcontext->plugin->runtime_lib_name = NULL; plcontext->plugin->runtime_funcs_symbol = NULL; plcontext->plugin->ext_points = NULL; plcontext->plugin->extensions = NULL; plcontext->plugin->url = NULL; plcontext->plugin->resourcetype = NULL; XML_SetUserData(parser, plcontext); // Parse the plug-in descriptor while (1) { int bytes_read; void *xml_buffer; int i; // Get buffer from Expat if ((xml_buffer = XML_GetBuffer(parser, CP_XML_PARSER_BUFFER_SIZE)) == NULL) { status = CP_ERR_RESOURCE; break; } // Read data into buffer bytes_read = fread(xml_buffer, 1, CP_XML_PARSER_BUFFER_SIZE, fh); if (ferror(fh)) { status = CP_ERR_IO; break; } // Parse the data if (!(i = XML_ParseBuffer(parser, bytes_read, bytes_read == 0)) && context != NULL) { cpi_lock_context(context); cpi_errorf(context, N_("XML parsing error in %s, line %d, column %d (%s)."), file, XML_GetErrorLineNumber(parser), XML_GetErrorColumnNumber(parser) + 1, XML_ErrorString(XML_GetErrorCode(parser))); cpi_unlock_context(context); } if (!i || plcontext->state == PARSER_ERROR) { status = CP_ERR_MALFORMED; break; } if (bytes_read == 0) { break; } } if (status == CP_OK) { if (plcontext->state != PARSER_END || plcontext->error_count > 0) { status = CP_ERR_MALFORMED; } if (plcontext->resource_error_count > 0) { status = CP_ERR_RESOURCE; } } if (status != CP_OK) { break; } // Initialize the plug-in path *(file + path_len) = '\0'; plcontext->plugin->plugin_path = file; file = NULL; // Increase plug-in usage count if ((status = cpi_register_info(context, plcontext->plugin, (void (*)(cp_context_t *, void *)) dealloc_plugin_info)) != CP_OK) { break; } } while (0); // Report possible errors if (status != CP_OK) { switch (status) { case CP_ERR_MALFORMED: cpi_errorf(context, N_("Plug-in descriptor in %s is invalid."), path); break; case CP_ERR_IO: cpi_errorf(context, N_("An I/O error occurred while loading a plug-in descriptor from %s."), path); break; case CP_ERR_RESOURCE: cpi_errorf(context, N_("Insufficient system resources to load a plug-in descriptor from %s."), path); break; default: cpi_errorf(context, N_("Failed to load a plug-in descriptor from %s."), path); break; } } cpi_unlock_context(context); // Release persistently allocated data on failure if (status != CP_OK) { if (file != NULL) { free(file); file = NULL; } if (plcontext != NULL && plcontext->plugin != NULL) { cpi_free_plugin(plcontext->plugin); plcontext->plugin = NULL; } } // Otherwise copy the plug-in pointer else { plugin = plcontext->plugin; } // Release data allocated for parsing if (parser != NULL) { XML_ParserFree(parser); } if (fh != NULL) { fclose(fh); } if (plcontext != NULL) { if (plcontext->value != NULL) { free(plcontext->value); } free(plcontext); plcontext = NULL; } // Return error code if (error != NULL) { *error = status; } return plugin; }