コード例 #1
0
ファイル: refdata-xml.cpp プロジェクト: rmcgibbo/gromacs
//! \cond internal
void cleanupReferenceData()
{
    xmlCleanupParser();
}
コード例 #2
0
ファイル: testRegexp.c プロジェクト: ArielleBassanelli/gempak
int main(int argc, char **argv) {
    xmlRegexpPtr comp = NULL;
#ifdef LIBXML_EXPR_ENABLED
    xmlExpNodePtr expr = NULL;
    int use_exp = 0;
    xmlExpCtxtPtr ctxt = NULL;
#endif
    const char *pattern = NULL;
    char *filename = NULL;
    int i;

    xmlInitMemory();

    if (argc <= 1) {
	usage(argv[0]);
	return(1);
    }
    for (i = 1; i < argc ; i++) {
	if (!strcmp(argv[i], "-"))
	    break;

	if (argv[i][0] != '-')
	    continue;
	if ((!strcmp(argv[i], "-debug")) || (!strcmp(argv[i], "--debug"))) {
	    debug++;
	} else if ((!strcmp(argv[i], "-repeat")) ||
	         (!strcmp(argv[i], "--repeat"))) {
	    repeat++;
#ifdef LIBXML_EXPR_ENABLED
	} else if ((!strcmp(argv[i], "-expr")) ||
	         (!strcmp(argv[i], "--expr"))) {
	    use_exp++;
#endif
	} else if ((!strcmp(argv[i], "-i")) || (!strcmp(argv[i], "-f")) ||
		   (!strcmp(argv[i], "--input")))
	    filename = argv[++i];
        else {
	    fprintf(stderr, "Unknown option %s\n", argv[i]);
	    usage(argv[0]);
	}
    }

#ifdef LIBXML_EXPR_ENABLED
    if (use_exp)
	ctxt = xmlExpNewCtxt(0, NULL);
#endif

    if (filename != NULL) {
#ifdef LIBXML_EXPR_ENABLED
        if (use_exp)
	    runFileTest(ctxt, filename);
	else
#endif
	    testRegexpFile(filename);
    } else {
#ifdef LIBXML_EXPR_ENABLED
        if (use_exp) {
	    for (i = 1; i < argc ; i++) {
		if ((argv[i][0] != '-') || (strcmp(argv[i], "-") == 0)) {
		    if (pattern == NULL) {
			pattern = argv[i];
			printf("Testing expr %s:\n", pattern);
			expr = xmlExpParse(ctxt, pattern);
			if (expr == NULL) {
			    printf("   failed to compile\n");
			    break;
			}
			if (debug) {
			    exprDebug(ctxt, expr);
			}
		    } else {
			testReduce(ctxt, expr, argv[i]);
		    }
		}
	    }
	    if (expr != NULL)
		xmlExpFree(ctxt, expr);
	} else
#endif
        {
	    for (i = 1; i < argc ; i++) {
		if ((argv[i][0] != '-') || (strcmp(argv[i], "-") == 0)) {
		    if (pattern == NULL) {
			pattern = argv[i];
			printf("Testing %s:\n", pattern);
			comp = xmlRegexpCompile((const xmlChar *) pattern);
			if (comp == NULL) {
			    printf("   failed to compile\n");
			    break;
			}
			if (debug)
			    xmlRegexpPrint(stdout, comp);
		    } else {
			testRegexp(comp, argv[i]);
		    }
		}
	    }
	    if (comp != NULL)
		xmlRegFreeRegexp(comp);
        }
    }
#ifdef LIBXML_EXPR_ENABLED
    if (ctxt != NULL) {
	printf("Ops: %d nodes, %d cons\n",
	       xmlExpCtxtNbNodes(ctxt), xmlExpCtxtNbCons(ctxt));
	xmlExpFreeCtxt(ctxt);
    }
#endif
    xmlCleanupParser();
    xmlMemoryDump();
    return(0);
}
コード例 #3
0
ファイル: client_util.c プロジェクト: nerses73/epics
void getXmlDoc(int sockfd, int read_status, int read_config) {

    if(DEBUG>1) printf("[ getXmlDoc ]: from socket %d (read_status %d read_config %d)\n",sockfd,read_status,read_config);

    // check that I'm not already polling it
    if(xml_poll_status==1) {
        if(DEBUG>1) printf("[ getXmlDoc ]: already polling so don't continue for this process (%d,%p)\n",xml_poll_status,xml_string);    
        return;
    }

    // occupy the poll flag
    xml_poll_status = 1;

    //clear old documents
    if(DEBUG>2) printf("[ getXmlDoc ]: free xml string %p\n",xml_string);
    free_xml_string();
    //if(xml_string!=NULL) {
    //  free(xml_string);
    //}
    if(DEBUG>2) printf("[ getXmlDoc ]: free xml string done %p\n",xml_string);
    if(doc!=NULL) {
       
       if(doc_prev!=NULL) {
          if(DEBUG>2) printf("[ getXmlDoc ]: free the prev xml doc\n");
          xmlFreeDoc(doc_prev);
          doc_prev=NULL;
       }
       if(DEBUG>2) printf("[ getXmlDoc ]: copy to prev xml doc\n");
       doc_prev = xmlCopyDoc(doc,1);
       
       if(DEBUG>2) printf("[ getXmlDoc ]: free current xml doc\n");       
       xmlFreeDoc(doc);
       xmlCleanupParser();
       doc=NULL;
       xml_root=NULL;
    }
    if(DEBUG>2) printf("[ getXmlDoc ]: free xml doc done\n");

    // check that the socket is open
    if(sockfd<=0) {
        if(DEBUG>2) printf("[ getXmlDoc ]: socket is not open.\n");
        //clear the flag
        xml_poll_status = 0;
        return;
    }


    // Do a status and config read to be sure to catch all info
    // Need to see exactly how the falgs are set in the return string 
    // from the server to see what to do here.

    if(read_status>0) {

        if(DEBUG>2) printf("[ getXmlDoc ]: ReadStatus\n");

        writeReadStatus(sockfd);

    }

    if(read_config>0) {

        if(DEBUG>2) printf("[ getXmlDoc ]: ReadConfig\n");

        writeReadConfig(sockfd);

    }

    if(DEBUG>2) printf("[ getXmlDoc ]: Before reading xml string (%p)\n",xml_string);

    pollXmlString(sockfd);

    if(DEBUG>2) printf("[ getXmlDoc ]: After reading xml string (%p)\n",xml_string);

    if(xml_string!=NULL) {
        if(strlen(xml_string)>0) {
           if(DEBUG>1) printf("[ getXmlDoc ]: create xml document from xml string(strlen %d)\n",strlen(xml_string));
            if(DEBUG>1) printf("[ getXmlDoc ]: xml string:\n%s\n",xml_string);
            doc = xmlReadMemory(xml_string,strlen(xml_string),"noname.xml",NULL,0);
            if(DEBUG>1) printf("[ getXmlDoc ]: xml doc done %p\n",doc);
            if(doc!=NULL) {
                xml_root = xmlDocGetRootElement(doc);
                if(xml_root!=NULL) {
                   if(DEBUG>2) {
                      printf("[ getXmlDoc ]: found xml_root name %s\n",(xml_root)->name);
                      printf("[ getXmlDoc ]: print xml to file\n");
                   }
                   int bytes_written = xmlSaveFormatFile("svtdaq.xml",doc,1);
                   if(DEBUG>2) {
                      printf("[ getXmlDoc ]: printed %d bytes of xml to file\n",bytes_written);
                   }
                }
            } else {
                printf("[ getXmlDoc ]: [ ERROR ]: problem building xml doc at %p from \n%s\n",doc,xml_string);
                exit(1);
            }
        } else {
            printf("[ getXmlDoc ]: [ ERROR ]: xml_string is there but has zero string length!\n");	
            exit(1);
        }
    } else {
        printf("[ getXmlDoc ]: [ WARNING ]:  xml_string is NULL after reading from socket!\n");	
    }

    //clear the flag
    xml_poll_status = 0;
    if(DEBUG>0) printf("[ getXmlDoc ]: cleared the flag and return (%d)\n",xml_poll_status);

}
コード例 #4
0
/**
 *  This is the main function for 'validate' option
 */
int
valMain(int argc, char **argv)
{
    int start;
    static valOptions ops;
    static ErrorInfo errorInfo;
    int invalidFound = 0;
    int options = XML_PARSE_DTDLOAD | XML_PARSE_DTDATTR;

    if (argc <= 2) valUsage(argc, argv, EXIT_BAD_ARGS);
    valInitOptions(&ops);
    start = valParseOptions(&ops, argc, argv);
    if (ops.nonet) options |= XML_PARSE_NONET;

    errorInfo.verbose = ops.err;
    xmlSetStructuredErrorFunc(&errorInfo, reportError);
    xmlLineNumbersDefault(1);

    if (ops.dtd)
    {
        /* xmlReader doesn't work with external dtd, have to use SAX
         * interface */
        int i;

        for (i=start; i<argc; i++)
        {
            xmlDocPtr doc;
            int ret;

            ret = 0;
            doc = NULL;

            errorInfo.filename = argv[i];
            doc = xmlReadFile(argv[i], NULL, options);
            if (doc)
            {
                /* TODO: precompile DTD once */                
                ret = valAgainstDtd(&ops, ops.dtd, doc, argv[i]);
                xmlFreeDoc(doc);
            }
            else
            {
                ret = 1; /* Malformed XML or could not open file */
                if ((ops.listGood < 0) && !ops.show_val_res)
                {
                    fprintf(stdout, "%s\n", argv[i]);
                }
            }
            if (ret) invalidFound = 1;     

            if (ops.show_val_res)
            {
                if (ret == 0)
                    fprintf(stdout, "%s - valid\n", argv[i]);
                else
                    fprintf(stdout, "%s - invalid\n", argv[i]);
            }
        }
    }
    else if (ops.schema || ops.relaxng || ops.embed || ops.wellFormed)
    {
        int i;
        xmlTextReaderPtr reader = NULL;

#ifdef LIBXML_SCHEMAS_ENABLED
        xmlSchemaPtr schema = NULL;
        xmlSchemaParserCtxtPtr schemaParserCtxt = NULL;
        xmlSchemaValidCtxtPtr schemaCtxt = NULL;

        xmlRelaxNGPtr relaxng = NULL;
        xmlRelaxNGParserCtxtPtr relaxngParserCtxt = NULL;
        /* there is no xmlTextReaderRelaxNGValidateCtxt() !?  */

        /* TODO: Do not print debug stuff */
        if (ops.schema)
        {
            schemaParserCtxt = xmlSchemaNewParserCtxt(ops.schema);
            if (!schemaParserCtxt)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }
            errorInfo.filename = ops.schema;
            schema = xmlSchemaParse(schemaParserCtxt);
            if (!schema)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

            xmlSchemaFreeParserCtxt(schemaParserCtxt);
            schemaCtxt = xmlSchemaNewValidCtxt(schema);
            if (!schemaCtxt)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

        }
        else if (ops.relaxng)
        {
            relaxngParserCtxt = xmlRelaxNGNewParserCtxt(ops.relaxng);
            if (!relaxngParserCtxt)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

            errorInfo.filename = ops.relaxng;
            relaxng = xmlRelaxNGParse(relaxngParserCtxt);
            if (!relaxng)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

        }
#endif  /* LIBXML_SCHEMAS_ENABLED */

        for (i=start; i<argc; i++)
        {
            int ret = 0;
            if (ops.embed) options |= XML_PARSE_DTDVALID;

            if (!reader)
            {
                reader = xmlReaderForFile(argv[i], NULL, options);
            }
            else
            {
                ret = xmlReaderNewFile(reader, argv[i], NULL, options);
            }

            errorInfo.xmlReader = reader;
            errorInfo.filename = argv[i];

            if (reader && ret == 0)
            {
#ifdef LIBXML_SCHEMAS_ENABLED
                if (schemaCtxt)
                {
                    ret = xmlTextReaderSchemaValidateCtxt(reader,
                        schemaCtxt, 0);
                }
                else if (relaxng)
                {
                    ret = xmlTextReaderRelaxNGSetSchema(reader,
                        relaxng);
                }
#endif  /* LIBXML_SCHEMAS_ENABLED */

                if (ret == 0)
                {
                    do
                    {
                        ret = xmlTextReaderRead(reader);
                    } while (ret == 1);
                    if (ret != -1 && (schema || relaxng || ops.embed))
                        ret = !xmlTextReaderIsValid(reader);
                }
            }
            else
            {
                if (ops.err)
                    fprintf(stderr, "couldn't read file '%s'\n", errorInfo.filename);
                ret = 1; /* could not open file */
            }
            if (ret) invalidFound = 1;

            if (!ops.show_val_res)
            {
                if ((ops.listGood > 0) && (ret == 0))
                    fprintf(stdout, "%s\n", argv[i]);
                if ((ops.listGood < 0) && (ret != 0))
                    fprintf(stdout, "%s\n", argv[i]);
            }
            else
            {
                if (ret == 0)
                    fprintf(stdout, "%s - valid\n", argv[i]);
                else
                    fprintf(stdout, "%s - invalid\n", argv[i]);
            }
        }
        errorInfo.xmlReader = NULL;
        xmlFreeTextReader(reader);

#ifdef LIBXML_SCHEMAS_ENABLED
    schemaCleanup:
        xmlSchemaFreeValidCtxt(schemaCtxt);
        xmlRelaxNGFree(relaxng);
        xmlSchemaFree(schema);
        xmlRelaxNGCleanupTypes();
        xmlSchemaCleanupTypes();
#endif  /* LIBXML_SCHEMAS_ENABLED */
    }

    xmlCleanupParser();
    return invalidFound;
}
コード例 #5
0
ファイル: annot_test.c プロジェクト: ericprud/libxml-annot
int
test (const char* base) {
    xmlDocPtr docPtr = NULL;
    char filename[100];
    xmlSchemaPtr wxschemas = NULL;

    Handle2Path = xmlHashCreate(0);

    /* Read the schema. */
    {
        /* There is no visitibility into parserCtxt. */
	xmlSchemaParserCtxtPtr parserCtxt;

        /* parserCtxt->ctxtType is xmlSchemaTypePtr */

        snprintf(filename, 100, "%s.xsd", base);
        printf("\n\n\n----------------------------------------------------------------\n\n\n");
        printf("\n----> Reading schema %s...\n", filename);

	parserCtxt = xmlSchemaNewParserCtxt(filename);
	xmlSchemaSetParserErrors(parserCtxt,
		(xmlSchemaValidityErrorFunc) fprintf,
		(xmlSchemaValidityWarningFunc) fprintf,
		stdout);
	xmlSchemaSetParserAnnotation(parserCtxt, schema_annotation_callback, NULL);
	wxschemas = xmlSchemaParse(parserCtxt);
	if (wxschemas == NULL)
        {
            printf("***** schema parsing failed!\n");
	}
	xmlSchemaFreeParserCtxt(parserCtxt);
        printf("\n<---- Schema read!\n\n");
    }

    /* Read the XML. */
    {
        snprintf(filename, 100, "%s.xml", base);
        if ((docPtr = xmlReadFile(filename, NULL, 0)) == NULL)
        {
            printf("failed to parse \"%s\".\n", filename);
            return -1;
        }
    }

    if (!SKIP) {
        /* There is no visibility into schemaCtxt. */
	xmlSchemaValidCtxtPtr schemaCtxt;
	int ret;

        printf("\n----------------------------------------------------------------\n");
        printf("\n----> Validating document %s...\n", filename);

        /* This sets up the schemaCtxt, including a pointer to wxschemas. */
	schemaCtxt = xmlSchemaNewValidCtxt(wxschemas);
	xmlSchemaSetValidErrors(schemaCtxt,
		(xmlSchemaValidityErrorFunc) fprintf,
		(xmlSchemaValidityWarningFunc) fprintf,
		stdout);
	ret = xmlSchemaValidateDoc(schemaCtxt, docPtr);	/* read me! */
	if (ret == 0)
        {
	    /* printf("%s validates\n", filename); */
	}
        else if (ret > 0)
        {
	    printf("%s fails to validate\n", filename);
	}
        else
        {
	    printf("%s validation generated an internal error\n",
		   filename);
	}
	xmlSchemaFreeValidCtxt(schemaCtxt);
        printf("\n<---- Document validated!\n");

    }

    /* Generate a doc and validate it. */
    {
	xmlDocPtr newDoc = xmlNewDoc(BAD_CAST "1.0");
	{
	    xmlSchemaValidCtxtPtr schemaCtxt;
	    int ret;

	    schemaCtxt = xmlSchemaNewValidCtxt(wxschemas);
	    xmlSchemaSetValidErrors(schemaCtxt,
				    (xmlSchemaValidityErrorFunc) fprintf,
				    (xmlSchemaValidityWarningFunc) fprintf,
				    stdout);
	    xmlSchemaSetGeneratorCallback(schemaCtxt, BAD_CAST "people", NULL, &generation_callback, newDoc);
	    ret = xmlSchemaValidateDoc(schemaCtxt, newDoc);
	    if (ret == 0) {
/* 		xmlDocSetRootElement(newDoc, vctxt->node); */
		dump_doc(newDoc, NULL);
	    } else if (ret > 0)
		printf("%s fails to validate\n", filename);
	    else
		printf("%s validation generated an internal error\n",
		       filename);
	    xmlSchemaFreeValidCtxt(schemaCtxt);
	    printf("\n<---- Schema read!\n\n");
	}

	{
	    xmlSchemaValidCtxtPtr schemaCtxt;
	    int ret;

	    schemaCtxt = xmlSchemaNewValidCtxt(wxschemas);
	    xmlSchemaSetValidErrors(schemaCtxt,
				    (xmlSchemaValidityErrorFunc) fprintf,
				    (xmlSchemaValidityWarningFunc) fprintf,
				    stdout);
	    ret = xmlSchemaValidateDoc(schemaCtxt, newDoc);
	    if (ret == 0)
		;
	    else if (ret > 0)
		printf("%s fails to validate\n", filename);
	    else
		printf("%s validation generated an internal error\n",
		       filename);
	    xmlSchemaFreeValidCtxt(schemaCtxt);
	    printf("\n<---- Schema read!\n\n");
	}

	xmlFreeDoc(newDoc);
    }

#if 0
    /* why can't I just start with doc->children? */
    tree_trunk = xmlDocGetRootElement(docPtr);
#endif

#if 0
    tree_trunk = docPtr->children;

    printf("\n\n\n----------------------------------------------------------------\n\n\n");
    printf("\nWalking doc tree...\n");
    walk_doc_tree(tree_trunk, 0);
    printf("\n");
#endif
    printf("\n\n\n----------------------------------------------------------------\n\n\n");
    printf("\nWalking schema tree...\n");
    walk_schema_tree(wxschemas);
    printf("\n");

    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/
    /* This will tell me, for example, how to decode sequences. */
    printf("\n\n\n----------------------------------------------------------------\n\n\n");
    xmlSchemaDump(stdout, wxschemas);
    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/

    xmlFreeDoc(docPtr);

    xmlCleanupParser();

    xmlHashFree(Handle2Path, NULL);

    return 0;
}
コード例 #6
0
void DocbookGeneratorJob::run()
{
    UMLApp* app = UMLApp::app();
    UMLDoc* umlDoc = app->document();

    //write the XMI model in an in-memory char* string
    QString xmi;
    QTextStream xmiStream(&xmi, QIODevice::WriteOnly);

#if QT_VERSION >= 0x050000
    QTemporaryFile file; // we need this tmp file if we are writing to a remote file
#else
    KTemporaryFile file; // we need this tmp file if we are writing to a remote file
#endif
    file.setAutoRemove(false);

    // lets open the file for writing
    if (!file.open()) {
        uError() << "There was a problem saving file" << file.fileName();
        return;
    }

    umlDoc->saveToXMI(file); // save the xmi stuff to it

    xsltStylesheetPtr cur = NULL;
    xmlDocPtr doc, res;

    const char *params[16 + 1];
    int nbparams = 0;
    params[nbparams] = NULL;

#if QT_VERSION >= 0x050000
    QString xsltFile(QStandardPaths::locate(QStandardPaths::DataLocation, QLatin1String("xmi2docbook.xsl")));
#else
    QString xsltFile(KGlobal::dirs()->findResource("appdata", QLatin1String("xmi2docbook.xsl")));
#endif

    xmlSubstituteEntitiesDefault(1);
    xmlLoadExtDtdDefaultValue = 1;
    cur = xsltParseStylesheetFile((const xmlChar *)xsltFile.toLatin1().constData());
    doc = xmlParseFile((const char*)(file.fileName().toUtf8()));
    res = xsltApplyStylesheet(cur, doc, params);

#if QT_VERSION >= 0x050000
    QTemporaryFile tmpDocBook;
#else
    KTemporaryFile tmpDocBook;
#endif
    tmpDocBook.setAutoRemove(false);
    tmpDocBook.open();

    umlDoc->writeToStatusBar(i18n("Exporting to DocBook..."));
    xsltSaveResultToFd(tmpDocBook.handle(), res, cur);
    xsltFreeStylesheet(cur);
    xmlFreeDoc(res);
    xmlFreeDoc(doc);

    xsltCleanupGlobals();
    xmlCleanupParser();

    emit docbookGenerated(tmpDocBook.fileName());
}
コード例 #7
0
ファイル: app_config.cpp プロジェクト: Adimpression/TideSDK
AppConfig::AppConfig(std::string& xmlfile) :
	analyticsEnabled(true),
	updateMonitorEnabled(true)
{
	systemProperties = new PropertiesBinding();
	xmlParserCtxtPtr context = xmlNewParserCtxt();
	xmlDocPtr document = xmlCtxtReadFile(context, xmlfile.c_str(), NULL, 0);

	if (!document)
	{
		std::ostringstream error;
		if (context->lastError.code != XML_IO_LOAD_ERROR)
		{
			error << context->lastError.file << "[Line ";
			error << context->lastError.line << "] ";
		}
		error << context->lastError.message;
		GetLogger()->Error(error.str());

		xmlFreeParserCtxt(context);
		xmlCleanupParser();
		return;
	}

	xmlNodePtr root = xmlDocGetRootElement(document);
	xmlNodePtr node = root->children;
	while (node)
	{
		if (node->type != XML_ELEMENT_NODE)
		{
			node = node->next;
			continue;
		}

		// This should always be a UTF-8, so we can just cast
		// the node name here to a char*
		std::string nodeName(reinterpret_cast<char*>(
			const_cast<xmlChar*>(node->name)));

		if (nodeName == "name")
		{
			appName = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "id")
		{
			appID = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "description")
		{
			description = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "copyright")
		{
			copyright = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "url")
		{
			url = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "version")
		{
			version = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "publisher")
		{
			publisher = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "window")
		{
			this->windows.push_back(WindowConfig::FromXMLNode(node));
		}
		else if (nodeName == "analytics")
		{
			std::string nodeValue(ConfigUtils::GetNodeValue(node));
			analyticsEnabled = ConfigUtils::StringToBool(nodeValue);
		}
		else if (nodeName == "update-monitor")
		{
			std::string nodeValue(ConfigUtils::GetNodeValue(node));
			updateMonitorEnabled = ConfigUtils::StringToBool(nodeValue);
		}
		else if (nodeName == "icon")
		{
			icon = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "property")
		{
			ParsePropertyNode(node, systemProperties->GetConfig());
		}

		node = node->next;
	}

	xmlFreeDoc(document);
	xmlFreeParserCtxt(context);
	xmlCleanupParser();
}
コード例 #8
0
/**
 * Start engine.
 *
 */
void
engine_start(const char* cfgfile, int cmdline_verbosity, int daemonize,
    int info, int single_run)
{
    engine_type* engine = NULL;
    int use_syslog = 0;
    ods_status zl_changed = ODS_STATUS_UNCHANGED;
    ods_status status = ODS_STATUS_OK;
    int close_hsm = 0;

    ods_log_assert(cfgfile);
    ods_log_init(NULL, use_syslog, cmdline_verbosity);
    ods_log_verbose("[%s] starting signer", engine_str);

    /* initialize */
    xmlInitGlobals();
    xmlInitParser();
    xmlInitThreads();
    engine = engine_create();
    if (!engine) {
        ods_fatal_exit("[%s] create failed", engine_str);
        return;
    }
    engine->daemonize = daemonize;

    /* config */
    engine->config = engine_config(engine->allocator, cfgfile,
        cmdline_verbosity);
    status = engine_config_check(engine->config);
    if (status != ODS_STATUS_OK) {
        ods_log_error("[%s] cfgfile %s has errors", engine_str, cfgfile);
        goto earlyexit;
    }
    if (info) {
        engine_config_print(stdout, engine->config); /* for debugging */
        goto earlyexit;
    }
    /* check pidfile */
    if (!util_check_pidfile(engine->config->pid_filename)) {
        exit(1);
    }
    /* open log */
    ods_log_init(engine->config->log_filename, engine->config->use_syslog,
       engine->config->verbosity);
    /* setup */
    tzset(); /* for portability */
    status = engine_setup(engine);
    if (status != ODS_STATUS_OK) {
        ods_log_error("[%s] setup failed: %s", engine_str,
            ods_status2str(status));
        engine->need_to_exit = 1;
        if (status != ODS_STATUS_WRITE_PIDFILE_ERR) {
            /* command handler had not yet been started */
            engine->cmdhandler_done = 1;
        }
    } else {
        /* setup ok, mark hsm open */
        close_hsm = 1;
    }

    /* run */
    while (engine->need_to_exit == 0) {
        /* update zone list */
        lock_basic_lock(&engine->zonelist->zl_lock);
        zl_changed = zonelist_update(engine->zonelist,
            engine->config->zonelist_filename);
        engine->zonelist->just_removed = 0;
        engine->zonelist->just_added = 0;
        engine->zonelist->just_updated = 0;
        lock_basic_unlock(&engine->zonelist->zl_lock);
        /* start/reload */
        if (engine->need_to_reload) {
            ods_log_info("[%s] signer reloading", engine_str);
            engine->need_to_reload = 0;
        } else {
            ods_log_info("[%s] signer started", engine_str);
            zl_changed = engine_recover(engine);
        }
        if (zl_changed == ODS_STATUS_OK ||
            zl_changed == ODS_STATUS_UNCHANGED) {
            engine_update_zones(engine, zl_changed);
        }
        engine_run(engine, single_run);
    }

    /* shutdown */
    ods_log_info("[%s] signer shutdown", engine_str);
    if (close_hsm) {
        ods_log_verbose("[%s] close hsm", engine_str);
        hsm_close();
    }
    if (!engine->cmdhandler_done) {
        engine_stop_xfrhandler(engine);
        engine_stop_dnshandler(engine);
        engine_stop_cmdhandler(engine);
    }

earlyexit:
    if (engine && engine->config) {
        if (engine->config->pid_filename) {
            (void)unlink(engine->config->pid_filename);
        }
        if (engine->config->clisock_filename) {
            (void)unlink(engine->config->clisock_filename);
        }
    }
    tsig_handler_cleanup();
    engine_cleanup(engine);
    engine = NULL;
    ods_log_close();
    xmlCleanupParser();
    xmlCleanupGlobals();
    xmlCleanupThreads();
    return;
}
コード例 #9
0
ファイル: xpath.c プロジェクト: CraigBryan/PostgresqlFun
Datum
xpath_table(PG_FUNCTION_ARGS)
{
/* SPI (input tuple) support */
	SPITupleTable *tuptable;
	HeapTuple	spi_tuple;
	TupleDesc	spi_tupdesc;

/* Output tuple (tuplestore) support */
	Tuplestorestate *tupstore = NULL;
	TupleDesc	ret_tupdesc;
	HeapTuple	ret_tuple;

	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
	AttInMetadata *attinmeta;
	MemoryContext per_query_ctx;
	MemoryContext oldcontext;

/* Function parameters */
	char	   *pkeyfield = GET_STR(PG_GETARG_TEXT_P(0));
	char	   *xmlfield = GET_STR(PG_GETARG_TEXT_P(1));
	char	   *relname = GET_STR(PG_GETARG_TEXT_P(2));
	char	   *xpathset = GET_STR(PG_GETARG_TEXT_P(3));
	char	   *condition = GET_STR(PG_GETARG_TEXT_P(4));

	char	  **values;
	xmlChar   **xpaths;
	xmlChar    *pos;
	xmlChar    *pathsep = "|";

	int			numpaths;
	int			ret;
	int			proc;
	int			i;
	int			j;
	int			rownr;			/* For issuing multiple rows from one original
								 * document */
	int			had_values;		/* To determine end of nodeset results */

	StringInfo	querysql;

	/* We only have a valid tuple description in table function mode */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context that cannot accept a set")));
	if (rsinfo->expectedDesc == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("xpath_table must be called as a table function")));

	/*
	 * We want to materialise because it means that we don't have to carry
	 * libxml2 parser state between invocations of this function
	 */
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
			   errmsg("xpath_table requires Materialize mode, but it is not "
					  "allowed in this context")));

	/*
	 * The tuplestore must exist in a higher context than this function call
	 * (per_query_ctx is used)
	 */

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	/*
	 * Create the tuplestore - work_mem is the max in-memory size before a
	 * file is created on disk to hold it.
	 */
	tupstore = tuplestore_begin_heap(true, false, work_mem);

	MemoryContextSwitchTo(oldcontext);

	/* get the requested return tuple description */
	ret_tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);

	/*
	 * At the moment we assume that the returned attributes make sense for the
	 * XPath specififed (i.e. we trust the caller). It's not fatal if they get
	 * it wrong - the input function for the column type will raise an error
	 * if the path result can't be converted into the correct binary
	 * representation.
	 */

	attinmeta = TupleDescGetAttInMetadata(ret_tupdesc);

	/* Set return mode and allocate value space. */
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setDesc = ret_tupdesc;

	values = (char **) palloc(ret_tupdesc->natts * sizeof(char *));

	xpaths = (xmlChar **) palloc(ret_tupdesc->natts * sizeof(xmlChar *));

	/* Split XPaths. xpathset is a writable CString. */

	/* Note that we stop splitting once we've done all needed for tupdesc */

	numpaths = 0;
	pos = xpathset;
	do
	{
		xpaths[numpaths] = pos;
		pos = strstr(pos, pathsep);
		if (pos != NULL)
		{
			*pos = '\0';
			pos++;
		}
		numpaths++;
	} while ((pos != NULL) && (numpaths < (ret_tupdesc->natts - 1)));

	/* Now build query */

	querysql = makeStringInfo();

	/* Build initial sql statement */
	appendStringInfo(querysql, "SELECT %s, %s FROM %s WHERE %s",
					 pkeyfield,
					 xmlfield,
					 relname,
					 condition
		);


	if ((ret = SPI_connect()) < 0)
		elog(ERROR, "xpath_table: SPI_connect returned %d", ret);

	if ((ret = SPI_exec(querysql->data, 0)) != SPI_OK_SELECT)
		elog(ERROR, "xpath_table: SPI execution failed for query %s", querysql->data);

	proc = SPI_processed;
	/* elog(DEBUG1,"xpath_table: SPI returned %d rows",proc); */
	tuptable = SPI_tuptable;
	spi_tupdesc = tuptable->tupdesc;

/* Switch out of SPI context */
	MemoryContextSwitchTo(oldcontext);


/* Check that SPI returned correct result. If you put a comma into one of
 * the function parameters, this will catch it when the SPI query returns
 * e.g. 3 columns.
 */

	if (spi_tupdesc->natts != 2)
	{
		ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						errmsg("Expression returning multiple columns is not valid in parameter list"),
						errdetail("Expected two columns in SPI result, got %d", spi_tupdesc->natts)));
	}

/* Setup the parser. Beware that this must happen in the same context as the
 * cleanup - which means that any error from here on must do cleanup to
 * ensure that the entity table doesn't get freed by being out of context.
 */
	pgxml_parser_init();

	/* For each row i.e. document returned from SPI */
	for (i = 0; i < proc; i++)
	{
		char	   *pkey;
		char	   *xmldoc;

		xmlDocPtr	doctree;
		xmlXPathContextPtr ctxt;
		xmlXPathObjectPtr res;
		xmlChar    *resstr;


		xmlXPathCompExprPtr comppath;

		/* Extract the row data as C Strings */

		spi_tuple = tuptable->vals[i];
		pkey = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
		xmldoc = SPI_getvalue(spi_tuple, spi_tupdesc, 2);


		/*
		 * Clear the values array, so that not-well-formed documents return
		 * NULL in all columns.
		 */

		/* Note that this also means that spare columns will be NULL. */
		for (j = 0; j < ret_tupdesc->natts; j++)
			values[j] = NULL;

		/* Insert primary key */
		values[0] = pkey;

		/* Parse the document */
		doctree = xmlParseMemory(xmldoc, strlen(xmldoc));

		if (doctree == NULL)
		{						/* not well-formed, so output all-NULL tuple */

			ret_tuple = BuildTupleFromCStrings(attinmeta, values);
			oldcontext = MemoryContextSwitchTo(per_query_ctx);
			tuplestore_puttuple(tupstore, ret_tuple);
			MemoryContextSwitchTo(oldcontext);
			heap_freetuple(ret_tuple);
		}
		else
		{
			/* New loop here - we have to deal with nodeset results */
			rownr = 0;

			do
			{
				/* Now evaluate the set of xpaths. */
				had_values = 0;
				for (j = 0; j < numpaths; j++)
				{

					ctxt = xmlXPathNewContext(doctree);
					ctxt->node = xmlDocGetRootElement(doctree);
					xmlSetGenericErrorFunc(ctxt, pgxml_errorHandler);

					/* compile the path */
					comppath = xmlXPathCompile(xpaths[j]);
					if (comppath == NULL)
					{
						xmlCleanupParser();
						xmlFreeDoc(doctree);

						elog_error(ERROR, "XPath Syntax Error", 1);

						PG_RETURN_NULL();		/* Keep compiler happy */
					}

					/* Now evaluate the path expression. */
					res = xmlXPathCompiledEval(comppath, ctxt);
					xmlXPathFreeCompExpr(comppath);

					if (res != NULL)
					{
						switch (res->type)
						{
							case XPATH_NODESET:
								/* We see if this nodeset has enough nodes */
								if ((res->nodesetval != NULL) && (rownr < res->nodesetval->nodeNr))
								{
									resstr =
										xmlXPathCastNodeToString(res->nodesetval->nodeTab[rownr]);
									had_values = 1;
								}
								else
									resstr = NULL;

								break;

							case XPATH_STRING:
								resstr = xmlStrdup(res->stringval);
								break;

							default:
								elog(NOTICE, "Unsupported XQuery result: %d", res->type);
								resstr = xmlStrdup("<unsupported/>");
						}


						/*
						 * Insert this into the appropriate column in the
						 * result tuple.
						 */
						values[j + 1] = resstr;
					}
					xmlXPathFreeContext(ctxt);
				}
				/* Now add the tuple to the output, if there is one. */
				if (had_values)
				{
					ret_tuple = BuildTupleFromCStrings(attinmeta, values);
					oldcontext = MemoryContextSwitchTo(per_query_ctx);
					tuplestore_puttuple(tupstore, ret_tuple);
					MemoryContextSwitchTo(oldcontext);
					heap_freetuple(ret_tuple);
				}

				rownr++;

			} while (had_values);

		}

		xmlFreeDoc(doctree);

		pfree(pkey);
		pfree(xmldoc);
	}

	xmlCleanupParser();
/* Needed to flag completeness in 7.3.1. 7.4 defines it as a no-op. */
	tuplestore_donestoring(tupstore);

	SPI_finish();

	rsinfo->setResult = tupstore;

	/*
	 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
	 * tuples are in our tuplestore and passed back through rsinfo->setResult.
	 * rsinfo->setDesc is set to the tuple description that we actually used
	 * to build our tuples with, so the caller can verify we did what it was
	 * expecting.
	 */
	return (Datum) 0;

}
コード例 #10
0
ファイル: xml.c プロジェクト: NalaGinrut/eucalyptus
//!
//! Cleanup the LIBXML library (Unused for now)
//!
static void cleanup(void)
{
    xsltCleanupGlobals();
    xmlCleanupParser();                // calls xmlCleanupGlobals()
}
コード例 #11
0
/**
 * Set up engine.
 *
 */
static ods_status
engine_setup(engine_type* engine)
{
    ods_status status = ODS_STATUS_OK;
    struct sigaction action;
    int result = 0;
    int sockets[2] = {0,0};

    ods_log_debug("[%s] setup signer engine", engine_str);
    if (!engine || !engine->config) {
        return ODS_STATUS_ASSERT_ERR;
    }
    /* set edns */
    edns_init(&engine->edns, EDNS_MAX_MESSAGE_LEN);

    /* create command handler (before chowning socket file) */
    engine->cmdhandler = cmdhandler_create(engine->allocator,
        engine->config->clisock_filename);
    if (!engine->cmdhandler) {
        return ODS_STATUS_CMDHANDLER_ERR;
    }
    engine->dnshandler = dnshandler_create(engine->allocator,
        engine->config->interfaces);
    engine->xfrhandler = xfrhandler_create(engine->allocator);
    if (!engine->xfrhandler) {
        return ODS_STATUS_XFRHANDLER_ERR;
    }
    if (engine->dnshandler) {
        if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets) == -1) {
            return ODS_STATUS_XFRHANDLER_ERR;
        }
        engine->xfrhandler->dnshandler.fd = sockets[0];
        engine->dnshandler->xfrhandler.fd = sockets[1];
        status = dnshandler_listen(engine->dnshandler);
        if (status != ODS_STATUS_OK) {
            ods_log_error("[%s] setup: unable to listen to sockets (%s)",
                engine_str, ods_status2str(status));
        }
    }
    /* privdrop */
    engine->uid = privuid(engine->config->username);
    engine->gid = privgid(engine->config->group);
    /* TODO: does piddir exists? */
    /* remove the chown stuff: piddir? */
    ods_chown(engine->config->pid_filename, engine->uid, engine->gid, 1);
    ods_chown(engine->config->clisock_filename, engine->uid, engine->gid, 0);
    ods_chown(engine->config->working_dir, engine->uid, engine->gid, 0);
    if (engine->config->log_filename && !engine->config->use_syslog) {
        ods_chown(engine->config->log_filename, engine->uid, engine->gid, 0);
    }
    if (engine->config->working_dir &&
        chdir(engine->config->working_dir) != 0) {
        ods_log_error("[%s] setup: unable to chdir to %s (%s)", engine_str,
            engine->config->working_dir, strerror(errno));
        return ODS_STATUS_CHDIR_ERR;
    }
    if (engine_privdrop(engine) != ODS_STATUS_OK) {
        return ODS_STATUS_PRIVDROP_ERR;
    }
    /* daemonize */
    if (engine->daemonize) {
        switch ((engine->pid = fork())) {
            case -1: /* error */
                ods_log_error("[%s] setup: unable to fork daemon (%s)",
                    engine_str, strerror(errno));
                return ODS_STATUS_FORK_ERR;
            case 0: /* child */
                break;
            default: /* parent */
                engine_cleanup(engine);
                engine = NULL;
                xmlCleanupParser();
                xmlCleanupGlobals();
                xmlCleanupThreads();
                exit(0);
        }
        if (setsid() == -1) {
            ods_log_error("[%s] setup: unable to setsid daemon (%s)",
                engine_str, strerror(errno));
            return ODS_STATUS_SETSID_ERR;
        }
    }
    engine->pid = getpid();
    ods_log_verbose("[%s] running as pid %lu", engine_str,
        (unsigned long) engine->pid);
    /* catch signals */
    signal_set_engine(engine);
    action.sa_handler = signal_handler;
    sigfillset(&action.sa_mask);
    action.sa_flags = 0;
    sigaction(SIGTERM, &action, NULL);
    sigaction(SIGHUP, &action, NULL);
    sigaction(SIGINT, &action, NULL);
    sigaction(SIGILL, &action, NULL);
    sigaction(SIGUSR1, &action, NULL);
    sigaction(SIGALRM, &action, NULL);
    sigaction(SIGCHLD, &action, NULL);
    action.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &action, NULL);
    /* set up hsm */ /* LEAK */
    result = lhsm_open(engine->config->cfg_filename);
    if (result != HSM_OK) {
        return ODS_STATUS_HSM_ERR;
    }
    /* create workers/drudgers */
    engine_create_workers(engine);
    engine_create_drudgers(engine);
    /* start cmd/dns/xfr handlers */
    engine_start_cmdhandler(engine);
    engine_start_dnshandler(engine);
    engine_start_xfrhandler(engine);
    tsig_handler_init(engine->allocator);
    /* write pidfile */
    if (util_write_pidfile(engine->config->pid_filename, engine->pid) == -1) {
        hsm_close();
        return ODS_STATUS_WRITE_PIDFILE_ERR;
    }
    /* setup done */
    return ODS_STATUS_OK;
}
コード例 #12
0
bool CPhotoSpriteLoader::DownloadPhotos(void) {
	if (!_HTTP->Get("http://fotki.yandex.ru/export/slideshow-best50.xml", _XMLFileName)) {
		syslog(LOG_ERR, "Cannot load slideshow-best50.xml");
		return false;
	};

	xmlDoc * XMLDoc = NULL;
	xmlNode * Elem = NULL;

	LIBXML_TEST_VERSION

	XMLDoc = xmlReadFile(_XMLFileName, NULL, 0);
	if (XMLDoc == NULL)
		return false;

	Elem = xmlDocGetRootElement(XMLDoc);

	Elem = Elem->children;
	do {
		if (strcmp((char*)Elem->name, "image") == 0) {
			 xmlAttr * Attr = Elem->properties;
			 while (Attr && strcmp((char*)Attr->name, "url") != 0)
				 Attr = Attr->next;

			 if (Attr) {
				 char * XMLURL = (char*)Attr->children->content;
				 size_t szXMLURL = strlen(XMLURL);
				 char * URL = new char[szXMLURL + 2];
				 strcpy(URL, XMLURL);
				 URL[szXMLURL - 1] = 0;
				 strcat(URL, "XL");
				 char * FileName = strrchr(URL, '/');
				 char * FullFileName = new char[strlen(_DownloadFolder) + strlen(FileName) + 1];
				 strcpy(FullFileName, _DownloadFolder);
				 strcat(FullFileName, FileName);
				 for (int i=0; i<3; i++)
					 if (_HTTP->Get(URL, FullFileName))
						 break;

				 delete[] URL;
				 delete[] FullFileName;
			 };
		};
		Elem = Elem->next;
	} while (Elem);

	xmlFreeDoc(XMLDoc);
	xmlCleanupParser();

	remove(_XMLFileName);

	//Удаляем старые файлы
	DIR * dir = opendir(_PhotoFolder);
	struct dirent * dent;
	struct stat buf;
	size_t szPhotoFolder = strlen(_PhotoFolder);
	if (dir != NULL) {
		while ((dent = readdir(dir)) != NULL) {
			size_t szFileName = szPhotoFolder + strlen(dent->d_name) + 2;
			char * FileName = new char[szFileName];
			sprintf(FileName, "%s/%s", _PhotoFolder, dent->d_name);
			stat(FileName, &buf);
			if (S_ISREG(buf.st_mode))
				remove(FileName);
			delete[] FileName;
		};
		closedir(dir);
	};

	//Перемещаем скаченные файлы
	dir = opendir(_DownloadFolder);
	size_t szDownloadFolder = strlen(_DownloadFolder);
	if (dir != NULL) {
		while ((dent = readdir(dir)) != NULL) {
			char * OldFileName = new char[szDownloadFolder + strlen(dent->d_name) + 2];
			char * NewFileName = new char[szPhotoFolder + strlen(dent->d_name) + 2];

			sprintf(OldFileName, "%s/%s", _DownloadFolder, dent->d_name);
			sprintf(NewFileName, "%s/%s", _PhotoFolder, dent->d_name);
			stat(OldFileName, &buf);

			if (S_ISREG(buf.st_mode))
				rename(OldFileName, NewFileName);

			delete[] OldFileName;
			delete[] NewFileName;
		};
		closedir(dir);
	};

	return true;
}
コード例 #13
0
ファイル: xmlutil.cpp プロジェクト: bjornjohansson/ircbot
	~XmlParserCleaner()
	{
		xmlCleanupParser();
	}
コード例 #14
0
ファイル: frmReport.cpp プロジェクト: KrisShannon/pgadmin3
wxString frmReport::XslProcessReport(const wxString &xml, const wxString &xsl)
{
	xmlChar *output = 0;
	xmlDocPtr ssDoc = 0, xmlDoc = 0, resDoc = 0;
	xsltStylesheetPtr ssPtr = 0;
	int length;

	wxBeginBusyCursor();

	// Apply the stylesheet
	xmlSubstituteEntitiesDefault (1); // Substitute entities
	xmlLoadExtDtdDefaultValue = 1; // Load external entities

	// Parse the stylesheet
	ssDoc = xmlParseDoc(XML_FROM_WXSTRING(xsl));
	if (!ssDoc)
	{
		wxEndBusyCursor();
		wxLogError(_("Failed to parse the XML stylesheet!"));
		goto cleanup;
	}

	ssPtr = xsltParseStylesheetDoc(ssDoc);
	if (!ssPtr)
	{
		wxEndBusyCursor();
		wxLogError(_("Failed to parse the XSL stylesheet!"));
		goto cleanup;
	}

	// Parse the data
	xmlDoc = xmlParseDoc(XML_FROM_WXSTRING(xml));
	if (!xmlDoc)
	{
		wxEndBusyCursor();
		wxLogError(_("Failed to parse the XML document!"));
		goto cleanup;
	}

	// Apply the stylesheet
	resDoc = xsltApplyStylesheet(ssPtr, xmlDoc, NULL);
	if (!resDoc)
	{
		wxEndBusyCursor();
		wxLogError(_("Failed to apply the XSL stylesheet to the XML document!"));
		goto cleanup;
	}

	// Get the result
	xsltSaveResultToString (&output, &length, resDoc, ssPtr);
	if (!resDoc)
	{
		wxEndBusyCursor();
		wxLogError(_("Failed to read the processed document!"));
		goto cleanup;
	}

cleanup:

	// Cleanup
	if (resDoc)
		xmlFreeDoc(resDoc);

	if (xmlDoc)
		xmlFreeDoc(xmlDoc);

	if (ssPtr)
		xsltFreeStylesheet(ssPtr);

	// This crashes - dunno why :-(
	// if (ssDoc)
	//  xmlFreeDoc(ssDoc);

	xsltCleanupGlobals();
	xmlCleanupParser();

	wxEndBusyCursor();

	if (output)
		return WXSTRING_FROM_XML(output);
	else
		return wxEmptyString;
}
コード例 #15
0
ファイル: parser.cpp プロジェクト: kastian/newsbeuter
void parser::global_cleanup() {
	xmlCleanupParser();
	curl_global_cleanup();
}
コード例 #16
0
ファイル: PoleXmlSec.c プロジェクト: MaxMorais/pole
static PyObject *
PoleXmlSec_sign(PyObject *self, PyObject *args)
{
    const char *xml, *key, *certificate, *id_attr_name, *id_node_name;
    PyObject* result;

    if (!PyArg_ParseTuple(args, "sssss", &xml, &key, &certificate, &id_attr_name, &id_node_name))
        return NULL;

    result = Py_BuildValue("s", xml);

    /* Init libxml and libxslt libraries */
    xmlInitParser();
    LIBXML_TEST_VERSION
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1;
#endif /* XMLSEC_NO_XSLT */

    /* Init xmlsec library */
    if(xmlSecInit() < 0) {
        fprintf(stderr, "XmlSecError: xmlsec initialization failed.\n");
        return result;
    }

    /* Check loaded library version */
    if(xmlSecCheckVersion() != 1) {
        fprintf(stderr, "XmlSecError: loaded xmlsec library version is not compatible.\n");
        return result;
    }

    /* Load default crypto engine if we are supporting dynamic
     * loading for xmlsec-crypto libraries. Use the crypto library
     * name ("openssl", "nss", etc.) to load corresponding
     * xmlsec-crypto library.
     */
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
        fprintf(stderr, "XmlSecError: unable to load default xmlsec-crypto library. Make sure\n"
                        "that you have it installed and check shared libraries path\n"
                        "(LD_LIBRARY_PATH) envornment variable.\n");
        return result;
    }
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */

    /* Init crypto library */
    if(xmlSecCryptoAppInit(NULL) < 0) {
        fprintf(stderr, "XmlSecError: crypto initialization failed.\n");
        return result;
    }

    /* Init xmlsec-crypto library */
    if(xmlSecCryptoInit() < 0) {
        fprintf(stderr, "XmlSecError: xmlsec-crypto initialization failed.\n");
        return result;
    }

    result = sign_xml(xml, key, certificate, id_attr_name, id_node_name);

    /* Shutdown xmlsec-crypto library */
    xmlSecCryptoShutdown();

    /* Shutdown xmlsec library */
    xmlSecShutdown();

    /* Shutdown crypto library */
    /* Se executar essa linha dá erro na conexão HTTPS */
    // xmlSecCryptoAppShutdown();

    /* Shutdown libxslt/libxml/libxmlsec1 */
#ifndef XMLSEC_NO_XSLT
    xsltCleanupGlobals();
#endif /* XMLSEC_NO_XSLT */
    xmlCleanupParser();

    return result;
}
コード例 #17
0
ファイル: xmlwriter.c プロジェクト: dunghand/msrds
/* ========================================================================= */
void ghmm_xmlfile_write(ghmm_xmlfile* f, const char *file) {
#define CUR_PROC "ghmm_xmlfile_write"
  int rc, i;
  xmlTextWriterPtr writer;
  xmlDocPtr doc;

  /*
   * this initialize the library and check potential ABI mismatches
   * between the version it was compiled for and the actual shared
   * library used.
   */
  LIBXML_TEST_VERSION

    xmlSubstituteEntitiesDefault(1);

  /* Create a new XmlWriter for DOM, with no compression. */
  writer = xmlNewTextWriterDoc(&doc, 0);
  if (writer == NULL) {
    GHMM_LOG(LERROR, "can not create the xml writer");
    goto STOP;
  }

  /* indenting writer to circumvent no space between SYSTEM and PUBLIC identifier */
  xmlTextWriterSetIndent(writer, 1);

  /* Start the document with the xml default for the version,
   * encoding ISO 8859-1 and the default for the standalone
   * declaration. */
  rc = xmlTextWriterStartDocument(writer, NULL, MY_ENCODING, NULL);
  if (rc < 0) {
    GHMM_LOG(LERROR, "Error at xmlTextWriterStartDocument\n");
    goto STOP;
  }

  /* Set the Document type declaration at the beginning of the document */
  rc = xmlTextWriterWriteDTD(writer, BAD_CAST "mixture",
                             BAD_CAST "-//ghmm.org//DOCUMENT ghmm V"DTD_VERSION"//EN",
                             BAD_CAST "http://ghmm.sourceforge.net/xml/"DTD_VERSION"/ghmm.dtd",
                             NULL);
  if (rc < 0) {
    GHMM_LOG(LERROR, "failed to write the DocType"); goto STOP;}

  /* start real contents */
  if (0 > xmlTextWriterStartElement(writer, BAD_CAST "mixture")) {
    GHMM_LOG(LERROR, "Error at xmlTextWriterStartElement (mixture)");
    goto STOP;;
  }

  if (xmlTextWriterWriteAttribute(writer, BAD_CAST "version", BAD_CAST DTD_VERSION) < 0) {
    GHMM_LOG(LERROR, "failed to write version 1.0"); goto STOP;}

  if (0 > xmlTextWriterWriteFormatAttribute(writer, BAD_CAST "noComponents", "%d", f->noModels)) {
    GHMM_LOG(LERROR, "failed to write the number of components"); goto STOP;}

  /* write all models */
  for (i=0; i<f->noModels; i++)
    writeHMM(writer, f, i);

  /* end mixture */
  if (0 > xmlTextWriterEndDocument(writer)) {
    GHMM_LOG(LERROR, "Error at xmlTextWriterEndDocument (mixture)");
    goto STOP;
  }

  xmlFreeTextWriter(writer);

  xmlSaveFormatFileEnc(file, doc, MY_ENCODING, 1);

STOP:
  xmlFreeDoc(doc);

  /*
   * Cleanup function for the XML library.
   */
  xmlCleanupParser();
  /*
   * this is to debug memory for regression tests
   */
  xmlMemoryDump();
#undef CUR_PROC
}
コード例 #18
0
ファイル: PoleXmlSec.c プロジェクト: MaxMorais/pole
static PyObject *
PoleXmlSec_verify(PyObject *self, PyObject *args)
{
    const char *xml, *id_attr_name, *id_node_name, *certifiers;
    int verified = 0;
    PyObject* result;
    xmlSecKeysMngrPtr mngr;
    const char **f, *files[1000000];
    char *c, *certs;

    if (!PyArg_ParseTuple(args, "ssss", &xml, &id_attr_name, &id_node_name, &certifiers))
        return NULL;

    result = Py_BuildValue("b", verified);

    /* Init libxml and libxslt libraries */
    xmlInitParser();
    LIBXML_TEST_VERSION
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1;
#endif /* XMLSEC_NO_XSLT */

    /* Init xmlsec library */
    if(xmlSecInit() < 0) {
        fprintf(stderr, "XmlSecError: xmlsec initialization failed.\n");
        return result;
    }

    /* Check loaded library version */
    if(xmlSecCheckVersion() != 1) {
        fprintf(stderr, "XmlSecError: loaded xmlsec library version is not compatible.\n");
        return result;
    }

    /* Load default crypto engine if we are supporting dynamic
     * loading for xmlsec-crypto libraries. Use the crypto library
     * name ("openssl", "nss", etc.) to load corresponding
     * xmlsec-crypto library.
     */
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
        fprintf(stderr, "XmlSecError: unable to load default xmlsec-crypto library. Make sure\n"
                        "that you have it installed and check shared libraries path\n"
                        "(LD_LIBRARY_PATH) envornment variable.\n");
        return result;
    }
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */

    /* Init crypto library */
    if(xmlSecCryptoAppInit(NULL) < 0) {
        fprintf(stderr, "XmlSecError: crypto initialization failed.\n");
        return result;
    }

    /* Init xmlsec-crypto library */
    if(xmlSecCryptoInit() < 0) {
        fprintf(stderr, "XmlSecError: xmlsec-crypto initialization failed.\n");
        return result;
    }

    /* Create a list of trusted certificates files/directories */
    certs = strdup(certifiers);
    for (c = certs, f = files, *(f++) = c; *c; c++)
        if (*c == ';') {
            *c = '\0';
            *(f++) = c + 1;
        }
    *f = NULL;

    /* create keys manager and load trusted certificates */
    mngr = load_trusted_certs(files);
    free(certs);
    if(mngr == NULL) {
        return result;
    }
    verified = verify_xml(mngr, xml, id_attr_name, id_node_name);
    xmlSecKeysMngrDestroy(mngr);
    result = Py_BuildValue("b", verified == 1);

    /* Shutdown xmlsec-crypto library */
    xmlSecCryptoShutdown();

    /* Shutdown xmlsec library */
    xmlSecShutdown();

    /* Shutdown crypto library */
    /* Se executar essa linha dá erro na conexão HTTPS */
    xmlSecCryptoAppShutdown();

    /* Shutdown libxslt/libxml/libxmlsec1 */
#ifndef XMLSEC_NO_XSLT
    xsltCleanupGlobals();
#endif /* XMLSEC_NO_XSLT */
    xmlCleanupParser();

    return result;
}
コード例 #19
0
ファイル: Engine.cpp プロジェクト: rafalcieslak/vmodsynth
void dump_patch(std::string filename) 
//Dumps XML-data to a file
{
    xmlDocPtr doc = NULL;       /* document pointer */
    xmlNodePtr root_node = NULL, node = NULL, node1 = NULL;/* node pointers */
    xmlDtdPtr dtd = NULL;       /* DTD pointer */

    xmlNodePtr some_section     = NULL;
    xmlNodePtr some_entry       = NULL;
    xmlNodePtr module_entry     = NULL;
    xmlNodePtr module_section   = NULL;
    xmlIndentTreeOutput = 1;
  
    char buff[256];

    doc = xmlNewDoc(BAD_CAST "1.0");
    root_node = xmlNewNode(NULL, BAD_CAST "patch");
    xmlDocSetRootElement(doc, root_node);
    xmlNewProp(root_node, BAD_CAST "vmodsynth_version", BAD_CAST "1.1");

    char origLocale[1024];
    strcpy(origLocale, std::setlocale(LC_ALL, "")); //Store locale before changing
    std::setlocale(LC_ALL, "C"); // We use '.' as decimal-point separator

    some_section = xmlNewChild(root_node, NULL, BAD_CAST "modules", BAD_CAST "");

    int m_pos=0, n=0;
    //Iterate over modules
    for(auto m = modules.begin(); m != modules.end(); m++)
    { 
        module_entry = xmlNewChild(some_section, NULL, BAD_CAST "module",BAD_CAST "");
        xmlNewProp(module_entry, BAD_CAST "name", BAD_CAST((*m)->name.c_str()));
        //Module name is not used, but output for human readability of the file. 
        xmlNewProp(module_entry, BAD_CAST "type_id", BAD_CAST(std::to_string((*m)->type_id).c_str()));

        n=0;
        //knob-settings per module
        for(auto i = (*m)->knobs.begin(); i != (*m)->knobs.end(); i++)
        { 
            double value = (*i)->get_value();
            some_entry = xmlNewChild(module_entry, NULL, BAD_CAST "knob",BAD_CAST "");
            xmlNewProp(some_entry, BAD_CAST "n", BAD_CAST(std::to_string(n).c_str()));
            xmlNewProp(some_entry, BAD_CAST "value", BAD_CAST(std::to_string(value).c_str()));
            n++; //Increment knob counter
        } //End knobs
 
        n=0;
        //swtich-settings per module
        for(auto i = (*m)->switches.begin(); i != (*m)->switches.end(); i++)
        { 
            double value = (*i)->get_value();
            some_entry = xmlNewChild(module_entry, NULL, BAD_CAST "switch",BAD_CAST "");
            xmlNewProp(some_entry, BAD_CAST "n", BAD_CAST(std::to_string(n).c_str()));
            xmlNewProp(some_entry, BAD_CAST "value", BAD_CAST(std::to_string(value).c_str()));
            n++; //Increment knob counter
        }
 

   } //End modules
 
    some_section = xmlNewChild(root_node, NULL, BAD_CAST "wires", BAD_CAST "");

    for(auto i = wires.begin(); i != wires.end(); i++)
    { 
        some_entry = xmlNewChild(some_section, NULL, BAD_CAST "wire",BAD_CAST "");

        n = get_mod_pos((*i)->from->parent);
        int o_n = (*i)->from->parent->get_outlet_index((*i)->from); //Logical order of outlet within module (eg. 0,1,2,...)

        xmlNewProp(some_entry, BAD_CAST "src", BAD_CAST(std::to_string(n).c_str()));
        xmlNewProp(some_entry, BAD_CAST "sj", BAD_CAST(std::to_string(o_n).c_str()));

        n = get_mod_pos((*i)->to->parent);
        int i_n = (*i)->to->parent->get_inlet_index((*i)->to); //Logical order of inlet within module (eg. 0,1,2,...)
        xmlNewProp(some_entry, BAD_CAST "dst", BAD_CAST(std::to_string(n).c_str()));
        xmlNewProp(some_entry, BAD_CAST "dj", BAD_CAST(std::to_string(i_n).c_str()));
    }

    xmlSaveFormatFileEnc(filename.c_str(), doc, "UTF-8", 1);
    xmlFreeDoc(doc);
    xmlCleanupParser();

    std::setlocale(LC_ALL, origLocale); //Restore locale to the original state
}
コード例 #20
0
ファイル: msdesc.c プロジェクト: rbundschuh/MonoSeq
/* load a description from a file */
PMSDESCRIPTION LoadSiteDescription(const char *Filename)
{
  int error;                     /* non-zero if error occurred          */
  int foundPattern;              /* non-zero if pattern found           */
  int foundScoring;              /* non-zero if scoring parameters found*/
  int foundQuality;              /* non-zero if quality filter found    */
  PMSDESCRIPTION pDescription;   /* site description to be loaded       */
  xmlDocPtr pXMLDocument;        /* the XML document in the file        */
  xmlNode *pNode;                /* current node in XML document        */

  /* parse XML file */
  xmlInitParser();
  pXMLDocument=xmlParseFile(Filename);
  if (!pXMLDocument) {
    fprintf(stderr,"Could not parse site description file!\n");
    return(NULL);
  }

  /* get memory for site description */
  pDescription=(PMSDESCRIPTION)malloc(sizeof(MSDESCRIPTION));
  if (!pDescription) {
    fprintf(stderr,"Could not allocate memory for site description!\n");
    xmlFreeDoc(pXMLDocument);
    xmlCleanupParser();
    return(NULL);
  }
  pDescription->Length=0;
  pDescription->Sequence=NULL;
  pDescription->RepeatBasePosition=-1;
  pDescription->Minimal5Flank=5;
  pDescription->Minimal3Flank=5;
  pDescription->MaximalMismatch=10;
  pDescription->MaxMismatch5Req=1;
  pDescription->MaxMismatch3Req=1;
  pDescription->CutoffForNs=20;
  pDescription->MaximumNs=30;

  error=0;
  do { /* region of controlled exit */

    for(pNode=xmlDocGetRootElement(pXMLDocument);pNode;pNode=pNode->next)
      if (pNode->type==XML_ELEMENT_NODE &&
	  !strcmp((const char*)pNode->name,"SiteDescription"))
	break;
    if (!pNode) {
      fprintf(stderr,"Could not find <SiteDescription> in description file!\n");
      error=1;
      break;
    }
    foundPattern=0;
    foundScoring=0;
    foundQuality=0;
    for(pNode=pNode->children;pNode;pNode=pNode->next) {
      if (pNode->type != XML_ELEMENT_NODE) continue;
      if (!strcmp((const char*)pNode->name,"Pattern")) {
	if (foundPattern) {
	  fprintf(stderr,"Site description contains two patterns!\n");
	  error=1;
	  break;
	}
	foundPattern=1;
	error=ParsePatterns(pDescription,pNode);
      }
      if (!strcmp((const char*)pNode->name,"ScoringRules")) {
	if (foundScoring) {
	  fprintf(stderr,"Site description contains two scoring parameter "
		  "sets!\n");
	  error=1;
	  break;
	}
	foundScoring=1;
	error=ParseScoring(pDescription,pNode);
      }
      if (!strcmp((const char*)pNode->name,"QualityFilter")) {
	if (foundQuality) {
	  fprintf(stderr,"Site description contains two quality filter "
		  "parameter sets!\n");
	  error=1;
	  break;
	}
	foundQuality=1;
	error=ParseQuality(pDescription,pNode);
      }
      if (error) break;
    }

    if (!foundPattern) {
      fprintf(stderr,"Site description does not contain a pattern!\n");
      error=1;
      break;
    }

    if (pDescription->RepeatBasePosition<pDescription->Minimal5Flank) {
      fprintf(stderr,"5' flank is shorter than requested minimal 5' flank "
	      "length!\n");
      error=1;
      break;
    }
    
    if (pDescription->Length-pDescription->RepeatBasePosition-1
	<pDescription->Minimal3Flank) {
      fprintf(stderr,"3' flank is shorter than requested minimal 3' flank "
	      "length!\n");
      error=1;
      break;
    }

  } while(0); /* end of region of controlled exit */
  
  xmlFreeDoc(pXMLDocument);
  xmlCleanupParser();

  if (error) DestroySiteDescription(&pDescription);
  
  return(pDescription);
}
コード例 #21
0
ファイル: xmpp2simple.c プロジェクト: Drooids/openser-xmlrpc
void pres_Xmpp2Sip(char *msg, int type, void *param)
{
	xmlDocPtr doc= NULL;
	xmlNodePtr pres_node= NULL;
	char* pres_type= NULL;

	doc= xmlParseMemory(msg, strlen(msg));
	if(doc == NULL)
	{
		LM_ERR("while parsing xml memory\n");
		return;
	}

	pres_node= XMLDocGetNodeByName(doc, "presence", NULL);
	if(pres_node == NULL)
	{
		LM_ERR("while getting node\n");
		goto error;
	}
	pres_type= XMLNodeGetAttrContentByName(pres_node, "type" );
	
	if(pres_type== NULL )
	{
		LM_DBG("type attribut not present\n");
		build_publish(pres_node, -1);
		if(presence_subscribe(pres_node, 3600, XMPP_SUBSCRIBE)< 0)
		{
				LM_ERR("when sending subscribe for presence");
				xmlFree(pres_type);
				goto error;
		}


		/* send subscribe after publish because in xmpp subscribe message
		 * comes only when a new contact is inserted in buddy list */
	}
	else
	if(strcmp(pres_type, "unavailable")== 0)
	{
		build_publish(pres_node, 0);
		if(presence_subscribe(pres_node, 3600, XMPP_SUBSCRIBE)< 0)
				/* else subscribe for one hour*/
		{
				LM_ERR("when unsubscribing for presence");
				xmlFree(pres_type);
				goto error;
		}

	}		
	else
	if((strcmp(pres_type, "subscribe")==0)|| 
		( strcmp(pres_type, "unsubscribe")== 0)||
		 (strcmp(pres_type, "probe")== 0))
	{
		if(strcmp(pres_type, "subscribe")==0 || 
				strcmp(pres_type, "probe")== 0)
		{	
		    LM_DBG("send Subscribe message (no time limit)\n");
			if(presence_subscribe(pres_node, -1,
						XMPP_INITIAL_SUBS)< 0)
			{
				LM_ERR("when sending subscribe for presence");
				xmlFree(pres_type);
				goto error;
			}
		}	
		if(strcmp(pres_type, "unsubscribe")== 0)
		{
			if(presence_subscribe(pres_node, 0, 
						XMPP_INITIAL_SUBS)< 0)
			{
				LM_ERR("when unsubscribing for presence");
				xmlFree(pres_type);
				goto error;
			}
		}
	}
	xmlFree(pres_type);

	//	else 
	//		send_reply_message(pres_node);

	xmlFreeDoc(doc);
	xmlCleanupParser();
	xmlMemoryDump();
	return ;

error:

	if(doc)
		xmlFreeDoc(doc);
	xmlCleanupParser();
	xmlMemoryDump();

	return ;

}	
コード例 #22
0
ファイル: svg2png.cpp プロジェクト: Blaxxun/mapnik
int main (int argc,char** argv)
{
    namespace po = boost::program_options;

    bool verbose = false;
    bool auto_open = false;
    int return_value = 0;
    std::vector<std::string> svg_files;
    mapnik::logger logger;
    logger.set_severity(mapnik::logger::error);

    try
    {
        po::options_description desc("svg2png utility");
        desc.add_options()
            ("help,h", "produce usage message")
            ("version,V","print version string")
            ("verbose,v","verbose output")
            ("open","automatically open the file after rendering (os x only)")
            ("svg",po::value<std::vector<std::string> >(),"svg file to read")
            ;

        po::positional_options_description p;
        p.add("svg",-1);
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
        po::notify(vm);

        if (vm.count("version"))
        {
            std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl;
            return 1;
        }

        if (vm.count("help"))
        {
            std::clog << desc << std::endl;
            return 1;
        }

        if (vm.count("verbose"))
        {
            verbose = true;
        }

        if (vm.count("open"))
        {
            auto_open = true;
        }

        if (vm.count("svg"))
        {
            svg_files=vm["svg"].as< std::vector<std::string> >();
        }
        else
        {
            std::clog << "please provide an svg file!" << std::endl;
            return -1;
        }

        std::vector<std::string>::const_iterator itr = svg_files.begin();
        if (itr == svg_files.end())
        {
            std::clog << "no svg files to render" << std::endl;
            return 0;
        }

        xmlInitParser();

        while (itr != svg_files.end())
        {
            std::string svg_name (*itr++);
            if (verbose)
            {
                std::clog << "found: " << svg_name << "\n";
            }

            boost::optional<mapnik::marker_ptr> marker_ptr =
                mapnik::marker_cache::instance().find(svg_name, false);
            if (!marker_ptr)
            {
                std::clog << "svg2png error: could not open: '" << svg_name << "'\n";
                return_value = -1;
                continue;
            }
            mapnik::marker marker = **marker_ptr;
            if (!marker.is_vector())
            {
                std::clog << "svg2png error: '" << svg_name << "' is not a valid vector!\n";
                return_value = -1;
                continue;
            }

            typedef agg::pixfmt_rgba32_pre pixfmt;
            typedef agg::renderer_base<pixfmt> renderer_base;
            typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid;
            agg::rasterizer_scanline_aa<> ras_ptr;
            agg::scanline_u8 sl;

            double opacity = 1;
            int w = marker.width();
            int h = marker.height();
            if (verbose)
            {
                std::clog << "found width of '" << w << "' and height of '" << h << "'\n";
            }
            // 10 pixel buffer to avoid edge clipping of 100% svg's
            mapnik::image_32 im(w+10,h+10);
            agg::rendering_buffer buf(im.raw_data(), im.width(), im.height(), im.width() * 4);
            pixfmt pixf(buf);
            renderer_base renb(pixf);

            mapnik::box2d<double> const& bbox = (*marker.get_vector_data())->bounding_box();
            mapnik::coord<double,2> c = bbox.center();
            // center the svg marker on '0,0'
            agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y);
            // render the marker at the center of the marker box
            mtx.translate(0.5 * im.width(), 0.5 * im.height());

            mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage((*marker.get_vector_data())->source());
            mapnik::svg::svg_path_adapter svg_path(stl_storage);
            mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter,
                agg::pod_bvector<mapnik::svg::path_attributes>,
                renderer_solid,
                agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path,
                                                           (*marker.get_vector_data())->attributes());

            svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox);

            boost::algorithm::ireplace_last(svg_name,".svg",".png");
            im.demultiply();
            mapnik::save_to_file<mapnik::image_data_32>(im.data(),svg_name,"png");
            if (auto_open)
            {
                std::ostringstream s;
#ifdef DARWIN
                s << "open " << svg_name;
#else
                s << "xdg-open " << svg_name;
#endif
                int ret = system(s.str().c_str());
                if (ret != 0)
                    return_value = ret;
            }
            std::clog << "rendered to: " << svg_name << "\n";
        }
    }
    catch (...)
    {
        std::clog << "Exception of unknown type!" << std::endl;
        xmlCleanupParser();
        return -1;
    }

    // only call this once, on exit
    // to make sure valgrind output is clean
    // http://xmlsoft.org/xmlmem.html
    xmlCleanupParser();
    return return_value;
}
コード例 #23
0
ファイル: ul_publish.c プロジェクト: Distrotech/opensips
str* build_pidf(ucontact_t* c)
{
	xmlDocPtr  doc = NULL;
	xmlNodePtr root_node = NULL;
	xmlNodePtr tuple_node = NULL;
	xmlNodePtr status_node = NULL;
	xmlNodePtr basic_node = NULL;
	str *body= NULL;
	str pres_uri= {NULL, 0};
	char buf[BUF_LEN];
	char* at= NULL;

	if(c->expires< (int)time(NULL))
	{
		LM_DBG("found expired \n\n");
		return NULL;
	}

	pres_uri.s = buf;
	if(pres_prefix.s)
	{
		memcpy(pres_uri.s, pres_prefix.s, pres_prefix.len);
		pres_uri.len+= pres_prefix.len;
		memcpy(pres_uri.s+ pres_uri.len, ":", 1);
		pres_uri.len+= 1;
	}
	if(pres_uri.len + c->aor->len+ 1 > BUF_LEN)
	{
		LM_ERR("buffer size overflown\n");
		return NULL;
	}

	memcpy(pres_uri.s+ pres_uri.len, c->aor->s, c->aor->len);
	pres_uri.len+= c->aor->len;

	at = memchr(c->aor->s, '@', c->aor->len);
	if(!at)
	{
		if(pres_uri.len + 2 + default_domain.len > BUF_LEN)
		{
			LM_ERR("buffer size overflown\n");
			return NULL;
		}

		pres_uri.s[pres_uri.len++]= '@';
		memcpy(pres_uri.s+ pres_uri.len, default_domain.s, default_domain.len);
		pres_uri.len+= default_domain.len;
	}
	pres_uri.s[pres_uri.len]= '\0';

	/* create the Publish body  */
	doc = xmlNewDoc(BAD_CAST "1.0");
	if(doc==0)
		return NULL;

    root_node = xmlNewNode(NULL, BAD_CAST "presence");
	if(root_node==0)
		goto error;

	xmlDocSetRootElement(doc, root_node);

    xmlNewProp(root_node, BAD_CAST "xmlns",
			BAD_CAST "urn:ietf:params:xml:ns:pidf");
	xmlNewProp(root_node, BAD_CAST "xmlns:dm",
			BAD_CAST "urn:ietf:params:xml:ns:pidf:data-model");
	xmlNewProp(root_node, BAD_CAST  "xmlns:rpid",
			BAD_CAST "urn:ietf:params:xml:ns:pidf:rpid" );
	xmlNewProp(root_node, BAD_CAST "xmlns:c",
			BAD_CAST "urn:ietf:params:xml:ns:pidf:cipid");
	xmlNewProp(root_node, BAD_CAST "entity", BAD_CAST pres_uri.s);

	tuple_node =xmlNewChild(root_node, NULL, BAD_CAST "tuple", NULL) ;
	if( tuple_node ==NULL)
	{
		LM_ERR("while adding child\n");
		goto error;
	}

	status_node = xmlNewChild(tuple_node, NULL, BAD_CAST "status", NULL) ;
	if( status_node ==NULL)
	{
		LM_ERR("while adding child\n");
		goto error;
	}

	basic_node = xmlNewChild(status_node, NULL, BAD_CAST "basic",
		BAD_CAST "open") ;

	if( basic_node ==NULL)
	{
		LM_ERR("while adding child\n");
		goto error;
	}

	body = (str*)pkg_malloc(sizeof(str));
	if(body == NULL)
	{
		LM_ERR("while allocating memory\n");
		return NULL;
	}
	memset(body, 0, sizeof(str));

	xmlDocDumpMemory(doc,(unsigned char**)(void*)&body->s,&body->len);

	LM_DBG("new_body:\n%.*s\n",body->len, body->s);

    /*free the document */
	xmlFreeDoc(doc);
    xmlCleanupParser();

	return body;

error:
	if(body)
	{
		if(body->s)
			xmlFree(body->s);
		pkg_free(body);
	}
	if(doc)
		xmlFreeDoc(doc);
	return NULL;
}
コード例 #24
0
ファイル: tcp_input.c プロジェクト: VisBlank/ipfixcol
/**
 * \brief Input plugin initializtion function
 *
 * \param[in]  params  XML with input parameters
 * \param[out] config  Sets source and destination IP, destination port.
 * \return 0 on success, nonzero else.
 */
int input_init(char *params, void **config)
{
	/* necessary structures */
	struct addrinfo *addrinfo = NULL, hints;
	struct plugin_conf *conf = NULL;
	char *port = NULL, *address = NULL;
	int ai_family = AF_INET6; /* IPv6 is default */
	char dst_addr[INET6_ADDRSTRLEN];
	int ret, ipv6_only = 0, retval = 0, yes = 1; /* yes is for setsockopt */
	/* 1 when using default port - don't free memory */
	int def_port = 0;
#ifdef TLS_SUPPORT
	SSL_CTX *ctx = NULL;       /* SSL context structure */
	SSL **ssl_list = NULL;     /* list of SSL connection structures */
	xmlNode *cur_node_parent;
#endif

	/* parse params */
	xmlDoc *doc = NULL;
	xmlNode *root_element = NULL;
	xmlNode *cur_node = NULL;

	/* allocate plugin_conf structure */
	conf = calloc(1, sizeof(struct plugin_conf));
	if (conf == NULL) {
		MSG_ERROR(msg_module, "Cannot allocate memory for config structure: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	if (!enlarge_sock_addresses(conf)) {
		MSG_ERROR(msg_module, "Cannot initialize array for socket address");
		retval = 1;
		goto out;
	}

	/* empty the master set */
	FD_ZERO(&conf->master);

	/* parse xml string */
	doc = xmlParseDoc(BAD_CAST params);
	if (doc == NULL) {
		MSG_ERROR(msg_module, "Cannot parse configuration file");
		retval = 1;
		goto out;
	}
	/* get the root element node */
	root_element = xmlDocGetRootElement(doc);
	if (root_element == NULL) {
		MSG_ERROR(msg_module, "Cannot get document root element");
		retval = 1;
		goto out;
	}

	/* check that we have the right config xml, BAD_CAST is (xmlChar *) cast defined by libxml */
	if (!xmlStrEqual(root_element->name, BAD_CAST "tcpCollector")) {
		MSG_ERROR(msg_module, "Expecting tcpCollector root element; got %s", root_element->name);
		retval = 1;
		goto out;
	}

	/* go over all elements */
	for (cur_node = root_element->children; cur_node; cur_node = cur_node->next) {
#ifdef TLS_SUPPORT
		/* check whether we want to enable transport layer security */
		if (xmlStrEqual(cur_node->name, BAD_CAST "transportLayerSecurity")) {
			MSG_INFO(msg_module, "TLS enabled");
			conf->tls = 1;   /* TLS enabled */
			cur_node_parent = cur_node;	

			/* TLS configuration options */
			for (cur_node = cur_node->xmlChildrenNode; cur_node; cur_node = cur_node->next) {
			if (cur_node->type == XML_ELEMENT_NODE
						&& cur_node->children != NULL
						&& cur_node->children->content != NULL) {
					int tmp_val_len = strlen((char *) cur_node->children->content) + 1;
					char *tmp_val = malloc(sizeof(char) * tmp_val_len);
					if (!tmp_val) {
						MSG_ERROR(msg_module, "Cannot allocate memory: %s", strerror(errno));
						retval = 1;
						goto out;
					}
					strncpy_safe(tmp_val, (char *)cur_node->children->content, tmp_val_len);
					
					if (xmlStrEqual(cur_node->name, BAD_CAST "localCAfile")) {
						/* location of the CA certificate */
						conf->ca_cert_file = tmp_val;
					} else if (xmlStrEqual(cur_node->name, BAD_CAST "localServerCert")) {
						/* server's certificate */
						conf->server_cert_file = tmp_val;
					} else if (xmlStrEqual(cur_node->name, BAD_CAST "localServerCertKey")) {
						/* server's private key */
						conf->server_pkey_file = tmp_val;
					} else {
						/* unknown option */
						MSG_WARNING(msg_module, "Unknown configuration option: %s", cur_node->name);
						free(tmp_val);
					}
				}
			}

			cur_node = cur_node_parent;

			continue;
		}
#else   /* user wants TLS, but collector was compiled without it */
		if (xmlStrEqual(cur_node->name, BAD_CAST "transportLayerSecurity")) {
			/* user wants to enable TLS, but collector was compiled without it */
			MSG_WARNING(msg_module, "Collector was compiled without TLS support");
			continue;
		}
#endif
		if (cur_node->type == XML_ELEMENT_NODE && cur_node->children != NULL) {
			/* copy value to memory - don't forget the terminating zero */
			int tmp_val_len = strlen((char *) cur_node->children->content) + 1;
			char *tmp_val = malloc(sizeof(char) * tmp_val_len);
			/* this is not a preferred cast, but we really want to use plain chars here */
			if (tmp_val == NULL) {
				MSG_ERROR(msg_module, "Cannot allocate memory: %s", strerror(errno));
				retval = 1;
				goto out;
			}
			strncpy_safe(tmp_val, (char *)cur_node->children->content, tmp_val_len);

			if (xmlStrEqual(cur_node->name, BAD_CAST "localPort") && port == NULL) { /* set local port */
				port = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "localIPAddress") && address == NULL) { /* set local address */
				address = tmp_val;
			/* save following configuration to input_info */
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifeTime")) {
				conf->info.template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifeTime")) {
				conf->info.options_template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifePacket")) {
				conf->info.template_life_packet = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifePacket")) {
				conf->info.options_template_life_packet = tmp_val;
			} else { /* unknown parameter, ignore */
				/* Free the tmp_val for unknown elements */
				free(tmp_val);
			}
		}
	}

	/* set default port if none given */
	if (port == NULL) {
		port = DEFAULT_PORT;
		def_port = 1;
	}

#ifdef TLS_SUPPORT
	if (conf->tls) {
		/* use default options if not specified in configuration file */
		if (conf->ca_cert_file == NULL) {
			conf->ca_cert_file = strdup(DEFAULT_CA_FILE);
		}

		if (conf->server_cert_file == NULL) {
			conf->server_cert_file = strdup(DEFAULT_SERVER_CERT_FILE);
		}

		if (conf->server_pkey_file == NULL) {
			conf->server_pkey_file = strdup(DEFAULT_SERVER_PKEY_FILE);
		}
	}
#endif

	/* specify parameters of the connection */
	memset (&hints, 0, sizeof(struct addrinfo));
	hints.ai_socktype = SOCK_STREAM; /* TCP */
	hints.ai_family = ai_family; /* select IPv4 or IPv6*/
	hints.ai_flags = AI_V4MAPPED; /* we want to accept mapped addresses */
	if (address == NULL) {
		hints.ai_flags |= AI_PASSIVE; /* no address given, listen on all local addresses */
	}

	/* get server address */
	if ((ret = getaddrinfo(address, port, &hints, &addrinfo)) != 0) {
		MSG_ERROR(msg_module, "getaddrinfo failed: %s", gai_strerror(ret));
		retval = 1;
		goto out;
	}

	/* create socket */
	conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
	/* Retry with IPv4 when the implementation does not support the specified address family */
	if (conf->socket == -1 && errno == EAFNOSUPPORT && addrinfo->ai_family == AF_INET6) {
		addrinfo->ai_family = AF_INET;
		conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
	}
	if (conf->socket == -1) {
		/* End with error otherwise */
		MSG_ERROR(msg_module, "Cannot create socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* allow IPv4 connections on IPv6 */
	if ((addrinfo->ai_family == AF_INET6) &&
		(setsockopt(conf->socket, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)) == -1)) {
		MSG_WARNING(msg_module, "Cannot turn off socket option IPV6_V6ONLY; plugin may not accept IPv4 connections...");
	}

	/* allow to reuse the address immediately */
	if (setsockopt(conf->socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1)
	{
		MSG_WARNING(msg_module, "Cannot turn on socket reuse option; it may take a while before collector can be restarted");
	}

	/* bind socket to address */
	if (bind(conf->socket, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
		MSG_ERROR(msg_module, "Cannot bind socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* this is a listening socket */
	if (listen(conf->socket, BACKLOG) == -1) {
		MSG_ERROR(msg_module, "Cannot listen on socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

#ifdef TLS_SUPPORT
	if (conf->tls) {
		/* configure TLS */
	
		/* initialize library */
		SSL_load_error_strings();
		SSL_library_init();
	
		/* create CTX structure for TLS */
		ctx = SSL_CTX_new(TLSv1_server_method());
		if (!ctx) {
			MSG_ERROR(msg_module, "Cannot create CTX structure");
			ERR_print_errors_fp(stderr);
			retval = 1;
			goto out;
		}
	
		/* load server certificate into the CTX structure */
		ret = SSL_CTX_use_certificate_file(ctx, conf->server_cert_file, SSL_FILETYPE_PEM);
		if (ret != 1) {
			MSG_ERROR(msg_module, "Unable to load server's certificate from %s", conf->server_cert_file);
			ERR_print_errors_fp(stderr);
			retval = 1;
			goto out;
		}
	
		/* load private keys into the CTX structure */
		SSL_CTX_use_PrivateKey_file(ctx, conf->server_pkey_file, SSL_FILETYPE_PEM);
		if (ret <= 0) {
			MSG_ERROR(msg_module, "Unable to load server's private key from %s", conf->server_pkey_file);
			ERR_print_errors_fp(stderr);
			retval = 1;
			goto out;
		}

		/* set peer certificate verification parameters */
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL);
		
		ssl_list = (SSL **) malloc(sizeof(SSL *) * DEFAULT_SIZE_SSL_LIST);
		if (ssl_list == NULL) {
			MSG_ERROR(msg_module, "Memory allocation failed (%s:%d)", __FILE__, __LINE__);
			retval = 1;
			goto out;
		}
		memset(ssl_list, 0, DEFAULT_SIZE_SSL_LIST * sizeof(SSL *));

		conf->ssl_list_size = DEFAULT_SIZE_SSL_LIST;
		conf->ctx = ctx;
		conf->ssl_list = ssl_list;
	}
#endif  /* TLS */

	/* fill in general information */
	conf->info.type = SOURCE_TYPE_TCP;
	conf->info.dst_port = atoi(port);
	if (addrinfo->ai_family == AF_INET) { /* IPv4 */
		conf->info.l3_proto = 4;

		/* copy dst IPv4 address */
		conf->info.dst_addr.ipv4.s_addr =
			((struct sockaddr_in*) addrinfo->ai_addr)->sin_addr.s_addr;

		inet_ntop(AF_INET, &conf->info.dst_addr.ipv4, dst_addr, INET6_ADDRSTRLEN);
	} else { /* IPv6 */
		conf->info.l3_proto = 6;

		/* copy dst IPv6 address */
		int i;
		for (i=0; i<4;i++) {
			conf->info.dst_addr.ipv6.s6_addr32[i] =
				((struct sockaddr_in6*) addrinfo->ai_addr)->sin6_addr.s6_addr32[i];
		}

		inet_ntop(AF_INET6, &conf->info.dst_addr.ipv6, dst_addr, INET6_ADDRSTRLEN);
	}

	/* allocate memory for templates */
	if (convert_init(TCP_PLUGIN, BUFF_LEN) != 0) {
		MSG_ERROR(msg_module, "malloc() for templates failed!");
		retval = 1;
		goto out;
	}

	/* print info */
	MSG_INFO(msg_module, "Input plugin listening on %s, port %s", dst_addr, port);

	/* start listening thread */
	if (pthread_create(&listen_thread, NULL, &input_listen, (void *) conf) != 0) {
		MSG_ERROR(msg_module, "Failed to create listening thread");
		retval = 1;
		goto out;
	}

	/* pass general information to the collector */
	*config = (void*) conf;

	/* normal exit, all OK */
	MSG_INFO(msg_module, "Plugin initialization completed successfully");

out:
	if (def_port == 0 && port != NULL) { /* free when memory was actually allocated*/
		free(port);
	}

	if (address != NULL) {
		free(address);
	}

	if (addrinfo != NULL) {
		freeaddrinfo(addrinfo);
	}

	/* free the xml document */
	if (doc != NULL) {
		xmlFreeDoc(doc);
	}

	/* free the global variables that may have been allocated by the xml parser */
	xmlCleanupParser();

	/* free input_info when error occured */
	if (retval != 0 && conf != NULL) {
		if (conf->info.template_life_time != NULL) {
			free (conf->info.template_life_time);
		}
		if (conf->info.options_template_life_time != NULL) {
			free (conf->info.options_template_life_time);
		}
		if (conf->info.template_life_packet != NULL) {
			free (conf->info.template_life_packet);
		}
		if (conf->info.options_template_life_packet != NULL) {
			free (conf->info.options_template_life_packet);
		}
		free(conf);

	}

#ifdef TLS_SUPPORT
	/* error occurs, clean up */
	if ((retval != 0) && (conf != NULL)) {
		if (ssl_list) {
			free(ssl_list);
		}

		if (ctx) {
			SSL_CTX_free(ctx);
		}
	}
#endif

	return retval;
}
コード例 #25
0
ファイル: udp_input.c プロジェクト: VisBlank/ipfixcol
/**
 * \brief Input plugin initializtion function
 *
 * \param[in]  params XML with input parameters
 * \param[out] config  Sets source and destination IP, destination port.
 * \return 0 on success, nonzero else.
 */
int input_init(char *params, void **config)
{
	/* necessary structures */
	struct addrinfo *addrinfo = NULL, hints;
	struct plugin_conf *conf = NULL;
	char *port = NULL, *address = NULL;
	int ai_family = AF_INET6; /* IPv6 is default */
	char dst_addr[INET6_ADDRSTRLEN];
	int ret, ipv6_only = 0, retval = 0;

	/* 1 when using default port - don't free memory */
	int default_port = 0;

	/* parse params */
	xmlDoc *doc = NULL;
	xmlNode *root_element = NULL;
	xmlNode *cur_node = NULL;

	/* allocate plugin_conf structure */
	conf = calloc(1, sizeof(struct plugin_conf));
	if (conf == NULL) {
		MSG_ERROR(msg_module, "Cannot allocate memory for config structure: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* parse xml string */
	doc = xmlParseDoc(BAD_CAST params);
	if (doc == NULL) {
		printf("%s", params);
		MSG_ERROR(msg_module, "Cannot parse configuration");
		retval = 1;
		goto out;
	}

	/* get the root element node */
	root_element = xmlDocGetRootElement(doc);
	if (root_element == NULL) {
		MSG_ERROR(msg_module, "Cannot get document root element");
		retval = 1;
		goto out;
	}

	/* check that we have the right config xml, BAD_CAST is (xmlChar *) cast defined by libxml */
	if (!xmlStrEqual(root_element->name, BAD_CAST "udpCollector")) {
		MSG_ERROR(msg_module, "Expecting udpCollector root element, got %s", root_element->name);
		retval = 1;
		goto out;
	}

	/* go over all elements */
	for (cur_node = root_element->children; cur_node; cur_node = cur_node->next) {
		if (cur_node->type == XML_ELEMENT_NODE
				&& cur_node->children != NULL
				&& cur_node->children->content != NULL) {
			/* copy value to memory - don't forget the terminating zero */
			int tmp_val_len = strlen((char *) cur_node->children->content) + 1;
			char *tmp_val = malloc(sizeof(char) * tmp_val_len);
			if (tmp_val == NULL) {
				MSG_ERROR(msg_module, "Cannot allocate memory: %s", strerror(errno));
				retval = 1;
				goto out;
			}

			/* this is not a preferred cast, but we really want to use plain chars here */
			strncpy_safe(tmp_val, (char *) cur_node->children->content, tmp_val_len);

			if (xmlStrEqual(cur_node->name, BAD_CAST "localPort")) { /* set local port */
				if (port) {
					free(port);
				}
				port = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "localIPAddress")) { /* set local address */
				if (address) {
					free(address);
				}
				address = tmp_val;

			/* save following configuration to input_info */
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifeTime")) {
				if (conf->info.template_life_time) {
					free(conf->info.template_life_time);
				}
				conf->info.template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifeTime")) {
				if (conf->info.options_template_life_time) {
					free(conf->info.options_template_life_time);
				}
				conf->info.options_template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifePacket")) {
				if (conf->info.template_life_packet) {
					free(conf->info.template_life_packet);
				}
				conf->info.template_life_packet = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifePacket")) {
				if (conf->info.options_template_life_packet) {
					free(conf->info.options_template_life_packet);
				}
				conf->info.options_template_life_packet = tmp_val;
			} else { /* unknown parameter, ignore */
				free(tmp_val);
			}
		}
	}

	/* set default port if none given */
	if (port == NULL) {
		port = DEFAULT_PORT;
		default_port = 1;
	}

	/* specify parameters of the connection */
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_socktype = SOCK_DGRAM; /* UDP */
	hints.ai_family = ai_family; /* both IPv4 and IPv6*/
	hints.ai_flags = AI_V4MAPPED; /* we want to accept mapped addresses */
	if (address == NULL) {
		hints.ai_flags |= AI_PASSIVE; /* no address given, listen on all local addresses */
	}

	/* get server address */
	if ((ret = getaddrinfo(address, port, &hints, &addrinfo)) != 0) {
		MSG_ERROR(msg_module, "getaddrinfo failed: %s", gai_strerror(ret));
		retval = 1;
		goto out;
	}

	/* create socket */
	conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);

	/* Retry with IPv4 when the implementation does not support the specified address family */
	if (conf->socket == -1 && errno == EAFNOSUPPORT && addrinfo->ai_family == AF_INET6) {
		addrinfo->ai_family = AF_INET;
		conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
	}
	if (conf->socket == -1) {
		MSG_ERROR(msg_module, "Cannot create socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* allow IPv4 connections on IPv6 */
	if ((addrinfo->ai_family == AF_INET6) &&
			(setsockopt(conf->socket, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)) == -1)) {
		MSG_WARNING(msg_module, "Cannot turn off socket option IPV6_V6ONLY; plugin may not accept IPv4 connections...");
	}

	/* bind socket to address */
	if (bind(conf->socket, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
		MSG_ERROR(msg_module, "Cannot bind socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* fill in general information */
	conf->info.type = SOURCE_TYPE_UDP;
	conf->info.dst_port = atoi(port);
	if (addrinfo->ai_family == AF_INET) { /* IPv4 */
		conf->info.l3_proto = 4;

		/* copy dst IPv4 address */
		conf->info.dst_addr.ipv4.s_addr =
			((struct sockaddr_in*) addrinfo->ai_addr)->sin_addr.s_addr;

		inet_ntop(AF_INET, &conf->info.dst_addr.ipv4, dst_addr, INET6_ADDRSTRLEN);
	} else { /* IPv6 */
		conf->info.l3_proto = 6;

		/* copy destination IPv6 address */
		int i;
		for (i = 0; i < 4; i++) {
			conf->info.dst_addr.ipv6.s6_addr32[i] =
				((struct sockaddr_in6*) addrinfo->ai_addr)->sin6_addr.s6_addr32[i];
		}

		inet_ntop(AF_INET6, &conf->info.dst_addr.ipv6, dst_addr, INET6_ADDRSTRLEN);
	}

	if (convert_init(UDP_PLUGIN, BUFF_LEN) != 0) {
		MSG_ERROR(msg_module, "Failed to initialize templates");
		retval = 1;
		goto out;
	}

	/* print info */
	MSG_INFO(msg_module, "Input plugin listening on %s, port %s", dst_addr, port);

	/* and pass it to the collector */
	*config = (void*) conf;

	/* normal exit, all OK */
	MSG_INFO(msg_module, "Plugin initialization completed successfully");

out:
	if (default_port == 0 && port != NULL) { /* free when memory was actually allocated */
		free(port);
	}

	if (address != NULL) {
		free(address);
	}

	if (addrinfo != NULL) {
		freeaddrinfo(addrinfo);
	}

	/* free the xml document */
	if (doc != NULL) {
		xmlFreeDoc(doc);
	}

	/* free the global variables that may have been allocated by the xml parser */
	xmlCleanupParser();

	/* free input_info when error occured */
	if (retval != 0 && conf != NULL) {
		if (conf->info.template_life_time != NULL) {
			free (conf->info.template_life_time);
		}
		if (conf->info.options_template_life_time != NULL) {
			free (conf->info.options_template_life_time);
		}
		if (conf->info.template_life_packet != NULL) {
			free (conf->info.template_life_packet);
		}
		if (conf->info.options_template_life_packet != NULL) {
			free (conf->info.options_template_life_packet);
		}
		free(conf);
	}

	return retval;
}
コード例 #26
0
ファイル: gnc-gsettings.c プロジェクト: jralls/gnucash
/* Tool to migrate existing user settings from GConf to GSettings
 *
 * This tool will first run some sanity checks to see if migration
 * is necessary/possible. The actual migration works directly from
 * the GConf .xml files. Using an xsl transform it will convert them
 * in a guile script to set most settings found.
 *
 * Notes:
 * - due to some limitations in the xslt code, all the gconf xml files are
 *   first copied into a temporary directory. After the migration has finished,
 *   that temporary directory and its contents are removed.
 * - not all settings can be migrated. All the important ones are though.
 *   The ones that are missing are mostly with respect to window position
 *   and size.
 * - column widths/visibilities, sorting orders,... are no longer stored
 *   in gsettings, so these will obviously not be migrated either.
 * - upon a successful run, a flag will be set to prevent the migration
 *   from running again. So in normal circumstances the migration will
 *   be executed only once.
 */
static void gnc_gsettings_migrate_from_gconf (void)
{
    gchar *pkgdatadir, *stylesheet, *input, *output, *command;
    gchar *gconf_root, *gconf_apps, *gconf_gnucash;
    gchar *base_dir, *iter;
    SCM migr_script;
    xsltStylesheetPtr stylesheetptr = NULL;
    xmlDocPtr inputxml, transformedxml;
    FILE *outfile;
    gboolean migration_ok = FALSE;

    ENTER ();

    base_dir = g_strdup (g_get_home_dir ());
    for (iter = base_dir; *iter != 0; iter++)
    {
        if ( *iter == '\\')
            *iter = '/';
    }

    /* Only attempt to migrate if there is something to migrate */
    gconf_root    = g_build_filename(base_dir, ".gconf", NULL);
    gconf_apps    = g_build_filename(gconf_root, "apps", NULL);
    gconf_gnucash = g_build_filename(gconf_apps, "gnucash", NULL);
    migration_ok = (g_file_test (gconf_root, G_FILE_TEST_IS_DIR) &&
                    g_file_test (gconf_apps, G_FILE_TEST_IS_DIR) &&
                    g_file_test (gconf_gnucash, G_FILE_TEST_IS_DIR));
    g_free (gconf_root);
    g_free (gconf_apps);
    g_free (gconf_gnucash);
    if (!migration_ok)
    {
        g_free (base_dir);
        gnc_gsettings_set_bool (GNC_PREFS_GROUP_GENERAL, GNC_PREF_MIGRATE_PREFS_DONE, TRUE);
        PINFO ("No pre-existing GConf gnucash section found.\n"
               "Most likely this system never ran GnuCash before.\n"
               "Assume migration is not needed.");
        LEAVE ();
        return;
    }

    pkgdatadir = gnc_path_get_pkgdatadir();
    stylesheet = g_build_filename(pkgdatadir, "make-prefs-migration-script.xsl", NULL);
    input      = g_build_filename(pkgdatadir, "migratable-prefs.xml", NULL);
    g_free (pkgdatadir);

    migration_ok = (g_file_test (stylesheet, G_FILE_TEST_IS_REGULAR) &&
                    g_file_test (input, G_FILE_TEST_IS_REGULAR));
    if (!migration_ok)
    {
        /* Critical files not found, abort migration */
        g_free (base_dir);
        g_free (stylesheet);
        g_free (input);
        PWARN ("Migration input file and stylesheet missing. Skip migration.");
        return;
    }

    command = g_strconcat ("(use-modules (migrate-prefs))(migration-prepare \"",
                           base_dir, "\")", NULL);
    DEBUG ("command = %s", command);
    migration_ok = scm_is_true (scm_c_eval_string (command));
    g_free (command);
    if (!migration_ok)
    {
        /* Preparation step failed */
        g_free (base_dir);
        g_free (stylesheet);
        g_free (input);
        PWARN ("Migration preparation step failed. Skip migration.");
        LEAVE ();
        return;
    }

    output  = g_build_filename(base_dir, ".gnc-migration-tmp", "migrate-prefs-user.scm", NULL);
    xmlSubstituteEntitiesDefault(1);
    xmlLoadExtDtdDefaultValue = 1;
    defaultEntityLoader = xmlGetExternalEntityLoader();
    xmlSetExternalEntityLoader(xsltprocExternalEntityLoader);
    stylesheetptr = xsltParseStylesheetFile((const xmlChar *)stylesheet);
    inputxml = xmlParseFile(input);
    transformedxml = xsltApplyStylesheet(stylesheetptr, inputxml, NULL);

    outfile = fopen(output, "w");
    xsltSaveResultToFile(outfile, transformedxml, stylesheetptr);
    fclose(outfile);

    xsltFreeStylesheet(stylesheetptr);
    xmlFreeDoc(inputxml);
    xmlFreeDoc(transformedxml);

    xsltCleanupGlobals();
    xmlCleanupParser();
    g_free (stylesheet);
    g_free (input);

    migr_script = scm_from_locale_string (output);
    scm_primitive_load (migr_script);
    g_free (output);

    migration_ok = scm_is_true (scm_c_eval_string ("(use-modules (migrate-prefs-user))(run-migration)"));
    if (!migration_ok)
    {
        /* Actual migration step failed */
        g_free (base_dir);
        PWARN ("Actual migration step failed. Skip migration.");
        LEAVE ();
        return;
    }

    /* If we got here, the preferences were migrated successfully
     * Mark this success in gsettings, so we won't run the migration again.
     */
    gnc_gsettings_set_bool (GNC_PREFS_GROUP_GENERAL, GNC_PREF_MIGRATE_PREFS_DONE, TRUE);

    /* All that is left now is to cleanup... */
    command = g_strconcat ("(use-modules (migrate-prefs))(migration-cleanup \"",
                           base_dir, "\")", NULL);
    DEBUG ("command = %s", command);
    migration_ok = scm_is_true (scm_c_eval_string (command));
    g_free (command);
    if (!migration_ok) /* Cleanup step failed, not critical */
        PWARN ("Cleanup step failed. You may need to delete %s/.gnc-migration-tmp manually.", base_dir);
    else
        PINFO ("Preferences migration completed successfully");

    LEAVE ("");
    g_free (base_dir);

}
コード例 #27
0
ファイル: xml.cpp プロジェクト: clone2727/xoreos
void deinitXML() {
	xmlCleanupParser();
}
コード例 #28
0
ファイル: osm2pgsql.c プロジェクト: paulbalomiri/osm2pgsql
int main(int argc, char *argv[])
{
    int append=0;
    int create=0;
    int slim=0;
    int sanitize=0;
    int long_usage_bool=0;
    int pass_prompt=0;
    int projection = PROJ_SPHERE_MERC;
    int expire_tiles_zoom = -1;
    int expire_tiles_zoom_min = -1;
    int enable_hstore = 0;
    int enable_multi = 0;
    const char *expire_tiles_filename = "dirty_tiles";
    const char *db = "gis";
    const char *username=NULL;
    const char *host=NULL;
    const char *password=NULL;
    const char *port = "5432";
    const char *tblsindex = "pg_default"; // default TABLESPACE for index
    const char *conninfo = NULL;
    const char *prefix = "planet_osm";
    const char *style = OSM2PGSQL_DATADIR "/default.style";
    const char *temparg;
    const char *output_backend = "pgsql";
    const char *input_reader = "auto";
    const char **hstore_columns = NULL;
    int n_hstore_columns = 0;
    int cache = 800;
    struct output_options options;
    PGconn *sql_conn;

    int (*streamFile)(char *, int, struct osmdata_t *);

    printf("osm2pgsql SVN version %s\n\n", VERSION);

    while (1) {
        int c, option_index = 0;
        static struct option long_options[] = {
            {"append",   0, 0, 'a'},
            {"bbox",     1, 0, 'b'},
            {"create",   0, 0, 'c'},
            {"database", 1, 0, 'd'},
            {"latlong",  0, 0, 'l'},
            {"verbose",  0, 0, 'v'},
            {"slim",     0, 0, 's'},
            {"prefix",   1, 0, 'p'},
            {"proj",     1, 0, 'E'},
            {"merc",     0, 0, 'm'},
            {"oldmerc",  0, 0, 'M'},
            {"utf8-sanitize", 0, 0, 'u'},
            {"cache",    1, 0, 'C'},
            {"username", 1, 0, 'U'},
            {"password", 0, 0, 'W'},
            {"host",     1, 0, 'H'},
            {"port",     1, 0, 'P'},
            {"tablespace-index", 1, 0, 'i'},
            {"help",     0, 0, 'h'},
            {"style",    1, 0, 'S'},
            {"expire-tiles", 1, 0, 'e'},
            {"expire-output", 1, 0, 'o'},
            {"output",   1, 0, 'O'},
            {"extra-attributes", 0, 0, 'x'},
            {"hstore", 0, 0, 'k'},
            {"hstore-column", 1, 0, 'z'},
            {"multi-geometry", 0, 0, 'G'},
            {"input-reader", 1, 0, 'r'},
            {"version", 0, 0, 'V'},
            {0, 0, 0, 0}
        };

        c = getopt_long (argc, argv, "ab:cd:hlmMp:suvU:WH:P:i:E:C:S:e:o:O:xkGz:r:V", long_options, &option_index);
        if (c == -1)
            break;

        switch (c) {
        case 'a':
            append=1;
            break;
        case 'b':
            osmdata.bbox=optarg;
            break;
        case 'c':
            create=1;
            break;
        case 'v':
            verbose=1;
            break;
        case 's':
            slim=1;
            break;
        case 'u':
            sanitize=1;
            break;
        case 'l':
            projection=PROJ_LATLONG;
            break;
        case 'm':
            projection=PROJ_SPHERE_MERC;
            break;
        case 'M':
            projection=PROJ_MERC;
            break;
        case 'E':
            projection=-atoi(optarg);
            break;
        case 'p':
            prefix=optarg;
            break;
        case 'd':
            db=optarg;
            break;
        case 'C':
            cache = atoi(optarg);
            break;
        case 'U':
            username=optarg;
            break;
        case 'W':
            pass_prompt=1;
            break;
        case 'H':
            host=optarg;
            break;
        case 'P':
            port=optarg;
            break;
        case 'S':
            style=optarg;
            break;
        case 'i':
            tblsindex=optarg;
            break;
        case 'e':
            expire_tiles_zoom_min = atoi(optarg);
            temparg = strchr(optarg, '-');
            if (temparg) expire_tiles_zoom = atoi(temparg + 1);
            if (expire_tiles_zoom < expire_tiles_zoom_min) expire_tiles_zoom = expire_tiles_zoom_min;
            break;
        case 'o':
            expire_tiles_filename=optarg;
            break;
        case 'O':
            output_backend = optarg;
            break;
        case 'x':
            osmdata.extra_attributes=1;
            break;
        case 'k':
            enable_hstore=1;
            break;
        case 'z':
            n_hstore_columns++;
            hstore_columns = (const char**)realloc(hstore_columns, sizeof(&n_hstore_columns) * n_hstore_columns);
            hstore_columns[n_hstore_columns-1] = optarg;
            break;
        case 'G':
            enable_multi=1;
            break;
        case 'r':
            input_reader = optarg;
            break;
        case 'h':
            long_usage_bool=1;
            break;
        case 'V':
            exit(EXIT_SUCCESS);
        case '?':
        default:
            short_usage(argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    if (long_usage_bool) {
        long_usage(argv[0]);
        exit(EXIT_SUCCESS);
    }

    if (argc == optind) {  // No non-switch arguments
        short_usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    if (append && create) {
        fprintf(stderr, "Error: --append and --create options can not be used at the same time!\n");
        exit(EXIT_FAILURE);
    }

    if( cache < 0 ) cache = 0;

    if (pass_prompt)
        password = simple_prompt("Password:"******"PGPASS");
    }


    conninfo = build_conninfo(db, username, password, host, port);
    sql_conn = PQconnectdb(conninfo);
    if (PQstatus(sql_conn) != CONNECTION_OK) {
        fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(sql_conn));
        exit(EXIT_FAILURE);
    }
    PQfinish(sql_conn);

    text_init();
    initList(&osmdata.tags);

    osmdata.count_node = osmdata.max_node = 0;
    osmdata.count_way  = osmdata.max_way  = 0;
    osmdata.count_rel  = osmdata.max_rel  = 0;

    LIBXML_TEST_VERSION

    project_init(projection);
    fprintf(stderr, "Using projection SRS %d (%s)\n",
            project_getprojinfo()->srs, project_getprojinfo()->descr );

    if (parse_bbox(&osmdata))
        return 1;

    options.conninfo = conninfo;
    options.prefix = prefix;
    options.append = append;
    options.slim = slim;
    options.projection = project_getprojinfo()->srs;
    options.scale = (projection==PROJ_LATLONG)?10000000:100;
    options.mid = slim ? &mid_pgsql : &mid_ram;
    options.cache = cache;
    options.style = style;
    options.tblsindex = tblsindex;
    options.expire_tiles_zoom = expire_tiles_zoom;
    options.expire_tiles_zoom_min = expire_tiles_zoom_min;
    options.expire_tiles_filename = expire_tiles_filename;
    options.enable_multi = enable_multi;
    options.enable_hstore = enable_hstore;
    options.hstore_columns = hstore_columns;
    options.n_hstore_columns = n_hstore_columns;

    if (strcmp("pgsql", output_backend) == 0) {
        osmdata.out = &out_pgsql;
    } else if (strcmp("gazetteer", output_backend) == 0) {
        osmdata.out = &out_gazetteer;
    } else if (strcmp("null", output_backend) == 0) {
        osmdata.out = &out_null;
    } else {
        fprintf(stderr, "Output backend `%s' not recognised. Should be one of [pgsql, gazetteer, null].\n", output_backend);
        exit(EXIT_FAILURE);
    }

    if (strcmp("auto", input_reader) != 0) {
        if (strcmp("libxml2", input_reader) == 0) {
            streamFile = &streamFileXML2;
        } else if (strcmp("primitive", input_reader) == 0) {
            streamFile = &streamFilePrimitive;
#ifdef BUILD_READER_PBF
        } else if (strcmp("pbf", input_reader) == 0) {
            streamFile = &streamFilePbf;
#endif
        } else {
            fprintf(stderr, "Input parser `%s' not recognised. Should be one of [libxml2, primitive"
#ifdef BUILD_READER_PBF
                    ", pbf"
#endif
                    "].\n", input_reader);
            exit(EXIT_FAILURE);
        }
    }

    osmdata.out->start(&options);

    realloc_nodes(&osmdata);
    realloc_members(&osmdata);

    if (sizeof(int*) == 4 && options.slim != 1) {
        fprintf(stderr, "\n!! You are running this on 32bit system, so at most\n");
        fprintf(stderr, "!! 3GB of RAM can be used. If you encounter unexpected\n");
        fprintf(stderr, "!! exceptions during import, you should try running in slim\n");
        fprintf(stderr, "!! mode using parameter -s.\n");
    }

    while (optind < argc) {
        /* if input_reader is not forced by -r switch try to auto-detect it
           by file extension */
        if (strcmp("auto", input_reader) == 0) {
#ifdef BUILD_READER_PBF
            if (strcasecmp(".pbf",argv[optind]+strlen(argv[optind])-4) == 0) {
                streamFile = &streamFilePbf;
            } else {
                streamFile = &streamFileXML2;
            }
#else
            streamFile = &streamFileXML2;
#endif
        }
        time_t start, end;

        fprintf(stderr, "\nReading in file: %s\n", argv[optind]);
        time(&start);
        if (streamFile(argv[optind], sanitize, &osmdata) != 0)
            exit_nicely();
        time(&end);
        fprintf(stderr, "  parse time: %ds\n", (int)(end - start));
        optind++;
    }

    xmlCleanupParser();
    xmlMemoryDump();

    if (osmdata.count_node || osmdata.count_way || osmdata.count_rel) {
        fprintf(stderr, "\n");
        fprintf(stderr, "Node stats: total(%d), max(%d)\n", osmdata.count_node, osmdata.max_node);
        fprintf(stderr, "Way stats: total(%d), max(%d)\n", osmdata.count_way, osmdata.max_way);
        fprintf(stderr, "Relation stats: total(%d), max(%d)\n", osmdata.count_rel, osmdata.max_rel);
    }
    osmdata.out->stop();

    free(osmdata.nds);
    free(osmdata.members);

    // free the column pointer buffer
    free(hstore_columns);

    project_exit();
    text_exit();
    fprintf(stderr, "\n");

    return 0;
}
コード例 #29
0
ファイル: main.c プロジェクト: h31/NetworksCourseBackup
void start_work(int newsockfd)
{

	int  n;
	xmlDoc         *doc = NULL;
	xmlNode        *root_element = NULL;
	const char     *TopicFilename = "topics.xml";
	const char     *UserFilename = "users.xml";
	char buffer[256];
	char id[6];
	char login[100];

	bzero(login,100);
	    login_func(newsockfd,login);
	    strcpy(usersthr.login[usersthr.count],login);
	    usersthr.count++;
	    bzero(buffer,256);
	    strcpy(buffer,"next\n");
	    n=write(newsockfd,buffer,7);

	    while(1)
	    {
	    	bzero(buffer,256);
	    	strcpy(buffer,"next\n");
			n=write(newsockfd,buffer,7);
	    	//printf("next\n");
			bzero(buffer,256);
			n = read( newsockfd,buffer,255 );
			//printf("Buffer :%s\n",buffer);
			if (n < 0)
			{
				perror("ERROR reading from socket");
				exit(1);
			}
			if(!strncmp(buffer,"topics",6))
			{
				print_topic(buffer,newsockfd);
				//n = write(newsockfd,buffer,255);
			}
			if(!strncmp(buffer,"online",6))
			{
				doc = xmlReadFile(UserFilename, NULL, 0);
				if (doc == NULL)
				{
					printf("error: could not parse file %s\n", UserFilename);
					n = write(newsockfd,"Error\n",6);
				}
				else
				{
				    root_element = xmlDocGetRootElement(doc);
				    search_online_user(root_element,newsockfd);
				    xmlFreeDoc(doc);
				}
				xmlCleanupParser();
			}
			if(!strncmp(buffer,"show",4))
			{
				bzero(id,6);
				for(n=5;n<10;n++)
					id[n-5]=buffer[n];
			    doc = xmlReadFile(TopicFilename, NULL, 0);
			    if (doc == NULL)
			    {
			        printf("error: could not parse file %s\n", TopicFilename);
			        n = write(newsockfd,"Error\n",6);
			    }
			    else
			    {
	                root_element = xmlDocGetRootElement(doc);
	                fnp_post_by_id(root_element,id,newsockfd);
	                xmlFreeDoc(doc);
	            }
		        xmlCleanupParser();

		        doc = xmlReadFile(UserFilename, NULL, 0);
		        if (doc == NULL)
		        {
		             printf("error: could not parse file %s\n", UserFilename);
		             n = write(newsockfd,"Error\n",6);
		        }
		        else
		        {
		             root_element = xmlDocGetRootElement(doc);
		             add_see_topic(root_element,login,id);
		             xmlSaveFile(UserFilename,doc);
		             xmlFreeDoc(doc);
		        }
		       	xmlCleanupParser();
			}
			if(!strncmp(buffer,"exit",4))
			{
				bzero(buffer,256);
				strncpy(buffer,"exit\n",6);
				n = write(newsockfd,buffer,255);
				doc = xmlReadFile(UserFilename, NULL, 0);
				if (doc == NULL)
				{
					printf("error: could not parse file %s\n", UserFilename);
					n = write(newsockfd,"Error\n",6);
				}
				else
				{
				    root_element = xmlDocGetRootElement(doc);
				    on_off_user(root_element,login,0);
				    xmlSaveFile(UserFilename,doc);
					xmlFreeDoc(doc);
				}
				xmlCleanupParser();
				return;
			}
			if(!strncmp(buffer,"add",3))
			{
				doc = xmlReadFile(TopicFilename, NULL, 0);
				if (doc == NULL)
				{
					printf("error: could not parse file %s\n", TopicFilename);
					n = write(newsockfd,"Error\n",6);
				}
				else
				{
				    root_element = xmlDocGetRootElement(doc);
				    add_new_topic(root_element,newsockfd,login);
				    xmlSaveFile(TopicFilename,doc);
					xmlFreeDoc(doc);
				}
				xmlCleanupParser();
			}
			else
			{
				n=write(newsockfd,"OK",2);
			}
			/* Write a response to the client */
			if (n < 0)
			{
				perror("ERROR writing to socket");
				exit(1);
			}
	    }
}
コード例 #30
0
ファイル: simple2xmpp.c プロジェクト: Danfx/opensips
int winfo2xmpp(str* to_uri, str* body, str* id)
{
	xmlAttrPtr attr= NULL;
	str xmpp_msg;
	char* watcher= NULL ;
	str from_uri = {0, 0};
	xmlDocPtr notify_doc= NULL;
	xmlDocPtr doc= NULL;
	xmlNodePtr pidf_root= NULL;
	xmlNodePtr root_node= NULL;
	xmlNodePtr node= NULL;
	xmlBufferPtr buffer= NULL;
	str watcher_str;

	LM_DBG("start...\n");
	notify_doc= xmlParseMemory(body->s, body->len);
	if(notify_doc== NULL)
	{
		LM_ERR("while parsing xml memory\n");
		return -1;
	}
	pidf_root= XMLDocGetNodeByName(notify_doc, "watcherinfo", NULL);
	if(pidf_root== NULL)
	{
		LM_ERR("while extracting 'presence' node\n");
		goto error;
	}

	node = XMLNodeGetNodeByName(pidf_root, "watcher", NULL);

	for (; node!=NULL; node = node->next)
	{
		if( xmlStrcasecmp(node->name,(unsigned char*)"watcher"))
			continue;

		watcher= (char*)xmlNodeGetContent(node->children);
		if(watcher== NULL)
		{
			LM_ERR("while extracting watcher node content\n");
			goto error;
		}
		watcher_str.s = watcher;
		watcher_str.len = strlen(watcher);

		from_uri.s = xmpp_uri_sip2xmpp(&watcher_str);
		if(from_uri.s == NULL)
		{
			LM_ERR("Failed to transform uri from sip to xmpp\n");
			goto error;
		}
		from_uri.len = strlen(from_uri.s);
		xmlFree(watcher);
		watcher= NULL;

		doc= xmlNewDoc( 0 );
		if(doc== NULL)
		{
			LM_ERR("when creating new xml doc\n");
			goto error;
		}
		root_node = xmlNewNode(NULL, BAD_CAST "presence");
		if(root_node== NULL)
		{
			LM_ERR("when adding new node\n");
			goto error;
		}
		xmlDocSetRootElement(doc, root_node);

		attr= xmlNewProp(root_node, BAD_CAST "to", BAD_CAST to_uri->s);
		if(attr== NULL)
		{
			LM_ERR("while adding attribute to_uri\n");
			goto error;
		}
		attr= xmlNewProp(root_node, BAD_CAST "from", BAD_CAST from_uri.s);
		if(attr== NULL)
		{
			LM_ERR("while adding attribute from_uri\n");
			goto error;
		}
		attr= xmlNewProp(root_node, BAD_CAST "type", BAD_CAST "subscribe");
		if(attr== NULL)
		{
			LM_ERR("while adding attribute type\n");
			goto error;
		}
		buffer= xmlBufferCreate();
		if(buffer== NULL)
		{
			LM_ERR("while adding creating new buffer\n");
			goto error;
		}

		xmpp_msg.len= xmlNodeDump(buffer, doc, root_node, 1,1);
		if(xmpp_msg.len== -1)
		{
			LM_ERR("while dumping node\n");
			goto error;
		}
		xmpp_msg.s= (char*)xmlBufferContent( buffer);
		if(xmpp_msg.s==  NULL)
		{
			LM_ERR("while extracting buffer content\n");
			goto error;
		}

		LM_DBG("xmpp_msg: %.*s\n",xmpp_msg.len, xmpp_msg.s);

		if( xmpp_subscribe(&from_uri, to_uri, &xmpp_msg, id)< 0)
		{
			LM_ERR("while sending xmpp_subscribe\n");
			goto error;
		}
		xmlBufferFree(buffer);
		buffer= NULL;
		xmlFreeDoc(doc);
		doc= NULL;
	}

	xmlFreeDoc(notify_doc);
	xmlCleanupParser();
	xmlMemoryDump();
	return 0;

error:

	if(doc)
		xmlFreeDoc(doc);
	if(notify_doc)
		xmlFreeDoc(notify_doc);
	if(watcher)
		xmlFree(watcher);
	if(buffer)
		xmlBufferFree(buffer);
	xmlCleanupParser();
	xmlMemoryDump();

	return -1;
}