Exemplo n.º 1
0
//create xml for mibs
int create_eag_xml(char *xmlpath)
{
	xmlDocPtr doc = NULL;			/* document pointer */	
	xmlNodePtr root_node = NULL;
	
	doc = xmlNewDoc(BAD_CAST "1.0");
	root_node = xmlNewNode(NULL, BAD_CAST "root" );
	xmlDocSetRootElement(doc, root_node);

	xmlSaveFormatFileEnc(xmlpath, doc, "UTF-8", 1);
	/*free the document */
	xmlFreeDoc(doc);
	xmlCleanupParser();
	xmlMemoryDump();	

	do {
		char command[56];
		sprintf(command, "sudo chmod a+rw %s", xmlpath);
		system(command);
	} while(0);
	
	return 0;	
}
Exemplo n.º 2
0
int
main(int argc, char **argv)
{
    xmlTextReaderPtr reader;
    if (argc != 2)
        return(1);

    LIBXML_TEST_VERSION

    reader = xmlReaderForFile(argv[1], NULL, 0);
    if (reader == NULL) {
        fprintf(stderr, "Unable to open %s\n", argv[1]);
        return (1);
    }

    if (fx_parse_xml(reader, &testSchema))
    	printf("Error parsing document\n");

    xmlCleanupParser();
    xmlMemoryDump();

    return(0);
}
Exemplo n.º 3
0
int main(int argc, char** argv)
{
	if(argc !=3 ){
		printf("wrong no of argv..\n");
		usage(argv[0]);
		return(-1);
	}
	xmlInitParser();
	LIBXML_TEST_VERSION

	xmlParse abc;

	if(parser(argv[1], BAD_CAST argv[2],abc)<0){
		printf("error...\n");
		return(-1);
	}

	abc.onpath();

	xmlCleanupParser();
	xmlMemoryDump();
	return 0;
}
Exemplo n.º 4
0
int main(int argc, char **argv) {
    if (argc != 2)
        return(1);

    /*
     * 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

    streamFile(argv[1]);

    /*
     * Cleanup function for the XML library.
     */
    xmlCleanupParser();
    /*
     * this is to debug memory for regression tests
     */
    xmlMemoryDump();
    return(0);
}
Exemplo n.º 5
0
bool read_pb_message_from_xml_memory(google::protobuf::Message *document, const char *buffer, int size)
{
	LIBXML_TEST_VERSION
	
	xmlSAXHandler sax;
	init_xmlSAXHandler(&sax);
	
	xmlext::Context context;
	context.stack.push_back(document);
	context.paths.push_back("");
	int result = xmlSAXUserParseMemory(&sax, &context, buffer, size);
	context.paths.pop_back();
	context.stack.pop_back();
	
	if ( result != 0 ) {
		printf("Failed to parse document.\n" );
		return false;
	}
	
	xmlCleanupParser();
	xmlMemoryDump();
	return true;
}
Exemplo n.º 6
0
// Parse the settings XML file.
int parseXmlSettings(const char *filename) {

	int retVal = 0;
	
	xmlSAXHandler saxHandler;

	memset(&saxHandler, 0, sizeof(saxHandler));
	saxHandler.initialized = XML_SAX2_MAGIC;
	saxHandler.startElement = settingsXmlStartElementCallback;	
	saxHandler.characters = settingsXmlValueElementCallback;
	saxHandler.endElement = settingsXmlEndElementCallback;
	
	if(xmlSAXUserParseFile(&saxHandler, NULL, filename) < 0) 		
		retVal = 1;
		
	// Cleanup function for the XML library.
	xmlCleanupParser();

    // This is to debug memory for regression tests
	xmlMemoryDump();
	
	return retVal;
}
int parse_alps_output(

  dynamic_string *alps_output,
  dynamic_string *status)

  {
  xmlDocPtr  doc;

  if ((doc = xmlReadMemory(alps_output->str, strlen(alps_output->str), "apbasil", NULL, 0)) == NULL)
    {
    char buf[MAXLINE * 4];
    xmlErrorPtr pErr = xmlGetLastError();
    snprintf(buf, sizeof(buf), "Failed to parse the output of alps - %s", pErr->message);
    log_err(-1, __func__, buf);
    return(ALPS_PARSING_ERROR);
    }

  process_element(status, xmlDocGetRootElement(doc));

  xmlFreeDoc(doc);
  xmlMemoryDump();

  return(PBSE_NONE);
  } /* END parse_alps_output() */
Exemplo n.º 8
0
str* agregate_xmls(str* pres_user, str* pres_domain, str** body_array, int n)
{
	int i, j= 0, append ;
	xmlNodePtr p_root= NULL, new_p_root= NULL ;
	xmlDocPtr* xml_array ;
	xmlNodePtr node = NULL;
	xmlNodePtr add_node = NULL ;
	str *body= NULL;
	char* id= NULL, *tuple_id = NULL;

	xml_array = (xmlDocPtr*)pkg_malloc( (n+2)*sizeof(xmlDocPtr));
	if(xml_array== NULL)
	{
	
		LM_ERR("while alocating memory");
		return NULL;
	}
	memset(xml_array, 0, (n+2)*sizeof(xmlDocPtr)) ;

	for(i=0; i<n; i++)
	{
		if(body_array[i] == NULL )
			continue;

		xml_array[j] = NULL;
		xml_array[j] = xmlParseMemory( body_array[i]->s, body_array[i]->len );
		
		if( xml_array[j]== NULL)
		{
			LM_ERR("while parsing xml body message\n");
			goto error;
		}
		j++;

	} 

	if(j== 0)  /* no body */
	{
		if(xml_array)
			pkg_free(xml_array);
		return NULL;
	}

	j--;
	p_root = xmlDocGetNodeByName( xml_array[j], "presence", NULL);
	if(p_root ==NULL)
	{
		LM_ERR("while geting the xml_tree root\n");
		goto error;
	}

	for(i= j-1; i>=0; i--)
	{
		new_p_root= xmlDocGetNodeByName( xml_array[i], "presence", NULL);
		if(new_p_root ==NULL)
		{
			LM_ERR("while geting the xml_tree root\n");
			goto error;
		}

		append= 1;
		node= xmlNodeGetChildByName(new_p_root, "tuple");
		if(node != NULL)
		{
			tuple_id= xmlNodeGetAttrContentByName(node, "id");
			if(tuple_id== NULL)
			{
				LM_ERR("while extracting tuple id\n");
				goto error;
			}
			for (node = p_root->children; node!=NULL; node = node->next)
			{		
				if( xmlStrcasecmp(node->name,(unsigned char*)"text")==0)
					continue;
			
				if( xmlStrcasecmp(node->name,(unsigned char*)"tuple")==0)
				{
					id = xmlNodeGetAttrContentByName(node, "id");
					if(id== NULL)
					{
						LM_ERR("while extracting tuple id\n");
						goto error;
					}
				
					if(xmlStrcasecmp((unsigned char*)tuple_id,
								(unsigned char*)id )== 0)
					{
						append = 0;
						xmlFree(id);
						break;
					}
					xmlFree(id);
				}
			}
			xmlFree(tuple_id);
			tuple_id= NULL;
		}

		if(append) 
		{	
			for(node= new_p_root->children; node; node= node->next)
			{	
				add_node= xmlCopyNode(node, 1);
				if(add_node== NULL)
				{
					LM_ERR("while copying node\n");
					goto error;
				}
				if(xmlAddChild(p_root, add_node)== NULL)
				{
					LM_ERR("while adding child\n");
					goto error;
				}
								
			}
		}
	}

	body = (str*)pkg_malloc(sizeof(str));
	if(body == NULL)
	{
		ERR_MEM(PKG_MEM_STR);
	}

	xmlDocDumpFormatMemory(xml_array[j],(xmlChar**)(void*)&body->s, 
			&body->len, 1);	

  	for(i=0; i<=j; i++)
	{
		if(xml_array[i]!=NULL)
			xmlFreeDoc( xml_array[i]);
	}
	if(xml_array!=NULL)
		pkg_free(xml_array);
    
	xmlCleanupParser();
    xmlMemoryDump();

	return body;

error:
	if(xml_array!=NULL)
	{
		for(i=0; i<=j; i++)
		{
			if(xml_array[i]!=NULL)
				xmlFreeDoc( xml_array[i]);
		}
		pkg_free(xml_array);
	}
	if(tuple_id)
		xmlFree(tuple_id);
	if(body)
		pkg_free(body);

	return NULL;
}
Exemplo n.º 9
0
str* get_final_notify_body( subs_t *subs, str* notify_body, xmlNodePtr rule_node)
{
	xmlNodePtr transf_node = NULL, node = NULL, dont_provide = NULL;
	xmlNodePtr doc_root = NULL, doc_node = NULL, provide_node = NULL;
	xmlNodePtr all_node = NULL;
	xmlDocPtr doc= NULL;
	char name[15];
	char service_uri_scheme[10];
	int i= 0, found = 0;
	str* new_body = NULL;
    char* class_cont = NULL, *occurence_ID= NULL, *service_uri= NULL;
	char* deviceID = NULL;
	char* content = NULL;
	char all_name[20];

	strcpy(all_name, "all-");

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

	memset(new_body, 0, sizeof(str));

	doc = xmlParseMemory(notify_body->s, notify_body->len);
	if(doc== NULL) 
	{
		LM_ERR("while parsing the xml body message\n");
		goto error;
	}
	doc_root = xmlDocGetNodeByName(doc,"presence", NULL);
	if(doc_root == NULL)
	{
		LM_ERR("while extracting the presence node\n");
		goto error;
	}

	transf_node = xmlNodeGetChildByName(rule_node, "transformations");
	if(transf_node == NULL)
	{
		LM_DBG("transformations node not found\n");
		goto done;
	}
	
	for(node = transf_node->children; node; node = node->next )
	{
		if(xmlStrcasecmp(node->name, (unsigned char*)"text")== 0)
			continue;

		LM_DBG("transf_node->name:%s\n",node->name);

		strcpy((char*)name ,(char*)(node->name + 8));
		strcpy(all_name+4, name);
		
		if(xmlStrcasecmp((unsigned char*)name,(unsigned char*)"services") == 0)
			strcpy(name, "tuple");
		if(strncmp((char*)name,"person", 6) == 0)
			name[6] = '\0';

		doc_node = xmlNodeGetNodeByName(doc_root, name, NULL);
		if(doc_node == NULL)
			continue;
		LM_DBG("searched doc_node->name:%s\n",name);
	
		content = (char*)xmlNodeGetContent(node);
		if(content)
		{
			LM_DBG("content = %s\n", content);
		
			if(xmlStrcasecmp((unsigned char*)content,
					(unsigned char*) "FALSE") == 0)
			{
				LM_DBG("found content false\n");
				while( doc_node )
				{
					xmlUnlinkNode(doc_node);	
					xmlFreeNode(doc_node);
					doc_node = xmlNodeGetChildByName(doc_root, name);
				}
				xmlFree(content);
				continue;
			}
		
			if(xmlStrcasecmp((unsigned char*)content,
					(unsigned char*) "TRUE") == 0)
			{
				LM_DBG("found content true\n");
				xmlFree(content);
				continue;
			}
			xmlFree(content);
		}

		while (doc_node )
		{
			if (xmlStrcasecmp(doc_node->name,(unsigned char*)"text")==0)
			{
				doc_node = doc_node->next;
				continue;
			}

			if (xmlStrcasecmp(doc_node->name,(unsigned char*)name)!=0)
			{
				break;
			}
			all_node = xmlNodeGetChildByName(node, all_name) ;
		
			if( all_node )
			{
				LM_DBG("must provide all\n");
				doc_node = doc_node->next;
				continue;
			}

			found = 0;
			class_cont = xmlNodeGetNodeContentByName(doc_node, "class", 
					NULL);
			if(class_cont == NULL)
				LM_DBG("no class tag found\n");
			else
				LM_DBG("found class = %s\n", class_cont);

			occurence_ID = xmlNodeGetAttrContentByName(doc_node, "id");
			if(occurence_ID == NULL)
				LM_DBG("no id found\n");
			else
				LM_DBG("found id = %s\n", occurence_ID);


			deviceID = xmlNodeGetNodeContentByName(doc_node, "deviceID",
					NULL);	
			if(deviceID== NULL)
				LM_DBG("no deviceID found\n");
			else
				LM_DBG("found deviceID = %s\n",	deviceID);


			service_uri = xmlNodeGetNodeContentByName(doc_node, "contact",
					NULL);	
			if(service_uri == NULL)
				LM_DBG("no service_uri found\n");
			else
				LM_DBG("found service_uri = %s\n", service_uri);
			i = 0;
			if(service_uri!= NULL)
			{
				while(service_uri[i]!= ':')
				{
					service_uri_scheme[i] = service_uri[i];
					i++;
				}
				service_uri_scheme[i] = '\0';
				LM_DBG("service_uri_scheme: %s\n", service_uri_scheme);
			}

			provide_node = node->children;
				
			while ( provide_node!= NULL )
			{
				if(xmlStrcasecmp(provide_node->name,(unsigned char*) "text")==0)
				{
					provide_node = 	provide_node->next;
					continue;
				}

				if(xmlStrcasecmp(provide_node->name,(unsigned char*)"class")== 0
						&& class_cont )
				{
					content = (char*)xmlNodeGetContent(provide_node);

					if(content&& xmlStrcasecmp((unsigned char*)content,
								(unsigned char*)class_cont) == 0)
					{
						found = 1;
						LM_DBG("found class= %s", class_cont);
						xmlFree(content);
						break;
					}
					if(content)
						xmlFree(content);
				}
				if(xmlStrcasecmp(provide_node->name,
							(unsigned char*) "deviceID")==0&&deviceID )
				{
					content = (char*)xmlNodeGetContent(provide_node);

					if(content && xmlStrcasecmp ((unsigned char*)content,
								(unsigned char*)deviceID) == 0)
					{
						found = 1;
						LM_DBG("found deviceID= %s", deviceID);
						xmlFree(content);
						break;
					}
					if(content)
						xmlFree(content);

				}
				if(xmlStrcasecmp(provide_node->name,
							(unsigned char*)"occurence-id")== 0&& occurence_ID)
				{
					content = (char*)xmlNodeGetContent(provide_node);
					if(content && xmlStrcasecmp ((unsigned char*)content,
								(unsigned char*)occurence_ID) == 0)
					{
						found = 1;
						LM_DBG("found occurenceID= %s\n", occurence_ID);
						xmlFree(content);
						break;
					}
					if(content)
						xmlFree(content);

				}
				if(xmlStrcasecmp(provide_node->name,
							(unsigned char*)"service-uri")== 0 && service_uri)
				{
					content = (char*)xmlNodeGetContent(provide_node);
					if(content&& xmlStrcasecmp ((unsigned char*)content,
								(unsigned char*)service_uri) == 0)
					{
						found = 1;
						LM_DBG("found service_uri= %s", service_uri);
						xmlFree(content);
						break;
					}
					if(content)
						xmlFree(content);

				}
			
				if(xmlStrcasecmp(provide_node->name,
						(unsigned char*)"service-uri-scheme")==0&& i)
				{
					content = (char*)xmlNodeGetContent(provide_node);
					LM_DBG("service_uri_scheme=%s\n",content);
					if(content && xmlStrcasecmp((unsigned char*)content,
								(unsigned char*)service_uri_scheme) == 0)
					{
						found = 1;
						LM_DBG("found service_uri_scheme= %s", service_uri_scheme);
						xmlFree(content);
						break;
					}	
					if(content)
						xmlFree(content);

				}

				provide_node = provide_node->next;
			}
			
			if(found == 0)
			{
				LM_DBG("delete node: %s\n", doc_node->name);
				dont_provide = doc_node;
				doc_node = doc_node->next;
				xmlUnlinkNode(dont_provide);	
				xmlFreeNode(dont_provide);
			}	
			else
				doc_node = doc_node->next;
	
		}
	}

done:
	xmlDocDumpFormatMemory(doc,(xmlChar**)(void*)&new_body->s,
			&new_body->len, 1);
	LM_DBG("body = \n%.*s\n", new_body->len,
			new_body->s);

    xmlFreeDoc(doc);

	xmlFree(class_cont);
	xmlFree(occurence_ID);
	xmlFree(deviceID);
	xmlFree(service_uri);
    xmlCleanupParser();
    xmlMemoryDump();

    return new_body;
error:
    if(doc)
		xmlFreeDoc(doc);
	if(new_body)
	{
		if(new_body->s)
			xmlFree(new_body->s);
		pkg_free(new_body);
	}
	if(class_cont)
		xmlFree(class_cont);
	if(occurence_ID)
		xmlFree(occurence_ID);
	if(deviceID)
		xmlFree(deviceID);
	if(service_uri)
		xmlFree(service_uri);

	return NULL;
}	
char *uwsgi_format_airbrake_backtrace(struct uwsgi_thread *ut) {

	struct uwsgi_airbrake_config *uacc = (struct uwsgi_airbrake_config *) ut->data;

	xmlChar *xmlbuff;
	int buffersize;
	xmlDocPtr doc = NULL;
	xmlNodePtr notice_node = NULL, node = NULL, line_node = NULL, errnode = NULL;
	char *msg = NULL;

	doc = xmlNewDoc(BAD_CAST "1.0");
	notice_node = xmlNewNode(NULL, BAD_CAST "notice");
	xmlNewProp(notice_node, BAD_CAST "version", BAD_CAST "2.3");
	xmlDocSetRootElement(doc, notice_node);

	xmlNewChild(notice_node, NULL, BAD_CAST "api-key", BAD_CAST uacc->apikey);

	node = xmlNewChild(notice_node, NULL, BAD_CAST "notifier", NULL);
	xmlNewChild(node, NULL, BAD_CAST "name", BAD_CAST "uWSGI");
	xmlNewChild(node, NULL, BAD_CAST "version", BAD_CAST UWSGI_VERSION);
	xmlNewChild(node, NULL, BAD_CAST "url", BAD_CAST "https://github.com/unbit/uwsgi");

	// request env
	node = xmlNewChild(notice_node, NULL, BAD_CAST "request", NULL);
	node = xmlNewChild(node, NULL, BAD_CAST "cgi-data", NULL);

	line_node = xmlNewChild(node, NULL, BAD_CAST "var", BAD_CAST UWSGI_VERSION);
	xmlNewProp(line_node, BAD_CAST "key", BAD_CAST "uwsgi_version");

	line_node = xmlNewChild(node, NULL, BAD_CAST "var", BAD_CAST __VERSION__);
	xmlNewProp(line_node, BAD_CAST "key", BAD_CAST "compiled_with_version");

	struct utsname uuts;
#ifdef __sun__
	if (uname(&uuts) < 0) {
#else
	if (uname(&uuts)) {
#endif
		uwsgi_error("uname()");
	}
	else {
		line_node = xmlNewChild(node, NULL, BAD_CAST "var", BAD_CAST uuts.sysname);
		xmlNewProp(line_node, BAD_CAST "key", BAD_CAST "os_sysname");

		char *os_version = uwsgi_concat3(uuts.release, "-", uuts.version);
		line_node = xmlNewChild(node, NULL, BAD_CAST "var", BAD_CAST os_version);
		xmlNewProp(line_node, BAD_CAST "key", BAD_CAST "os_version");
		free(os_version);

		line_node = xmlNewChild(node, NULL, BAD_CAST "var", BAD_CAST uuts.machine);
		xmlNewProp(line_node, BAD_CAST "key", BAD_CAST "machine");

		line_node = xmlNewChild(node, NULL, BAD_CAST "var", BAD_CAST uuts.nodename);
		xmlNewProp(line_node, BAD_CAST "key", BAD_CAST "nodename");

	}
	// end request env

	node = xmlNewChild(notice_node, NULL, BAD_CAST "server-environment", NULL);
	xmlNewChild(node, NULL, BAD_CAST "app-version", BAD_CAST UWSGI_VERSION);
	if (uacc->env) {
		xmlNewChild(node, NULL, BAD_CAST "environment-name", BAD_CAST uacc->env);
	}
	else {
		xmlNewChild(node, NULL, BAD_CAST "environment-name", BAD_CAST UWSGI_VERSION);
	}

	errnode = xmlNewChild(notice_node, NULL, BAD_CAST "error", NULL);
	xmlNewChild(errnode, NULL, BAD_CAST "class", BAD_CAST "RuntimeError");
	node = xmlNewChild(errnode, NULL, BAD_CAST "backtrace", NULL);

	char *ctx = NULL;
	char *text = uwsgi_str(ut->buf);
	char *p = strtok_r(text, "\n", &ctx);
	while (p) {
		// skip log messages
		if (!uwsgi_startswith(p, "***", 3))
			goto next;
		// backtrace line looks like this: uwsgi(simple_loop_run+0xc5) [0x451555]
		// we take binary/lib as filename
		// and extract method name from remaining string
		char *n = strchr(p, '(');
		if (n) {
			*n = 0;

			char *pls = strchr(n+1, '+');
			if (pls) {
				*pls = 0;
			}

			if (!strcmp("uwsgi_backtrace", n+1) || !strcmp("what_i_am_doing", n+1)) {
				goto next;
			}
			else if (!strcmp("uwsgi_fpe", n+1)) {
				msg = uwsgi_concat4("uWSGI FPE at ", n+1, " in ", p);
				goto next;
			}

			if (!msg) {
				if (strlen(n+1)) {
					msg = uwsgi_concat4("uWSGI segfault at ", n+1, " in ", p);
				}
				else {
					// method name might be missing
					msg = uwsgi_concat2("uWSGI segfault in ", p);
				}
			}

			// skip empty lines
			if (!p)
				goto next;

			line_node = xmlNewChild(node, NULL, BAD_CAST "line", NULL);

			if ((n+1)[0] == ')') {
				xmlNewProp(line_node, BAD_CAST "method", BAD_CAST "()");
			}
			else {
				xmlNewProp(line_node, BAD_CAST "method", BAD_CAST n+1);
			}

			xmlNewProp(line_node, BAD_CAST "file", BAD_CAST p);

			//xmlNewProp(line_node, BAD_CAST "number", BAD_CAST "0");
		}
next:
		p = strtok_r(NULL, "\n", &ctx);
	}

	xmlNewChild(errnode, NULL, BAD_CAST "message", BAD_CAST msg);

	xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);

	xmlFreeDoc(doc);
	xmlCleanupParser();
	xmlMemoryDump();
	free(msg);
	free(text);

	return (char *) xmlbuff;
}


static void uwsgi_airbrake_loop(struct uwsgi_thread *ut) {
	int interesting_fd;
	ut->buf = uwsgi_malloc(uwsgi.log_master_bufsize);

	CURL *curl = curl_easy_init();
	// ARGH !!!
	if (!curl) return;

	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, uwsgi.shared->options[UWSGI_OPTION_SOCKET_TIMEOUT]);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, uwsgi.shared->options[UWSGI_OPTION_SOCKET_TIMEOUT]);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
	curl_easy_setopt(curl, CURLOPT_READDATA, ut);
	curl_easy_setopt(curl, CURLOPT_POST, 1L);
	struct curl_slist *expect = NULL; expect = curl_slist_append(expect, "Expect:");
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, expect);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

	struct uwsgi_airbrake_config *uacc = (struct uwsgi_airbrake_config *) ut->data;
	char *opts = uwsgi_str(uacc->arg);

	// fill curl options
	char *ctx = NULL;
	char *p = strtok_r(opts, ";", &ctx);
	while(p) {
		uwsgi_airbrake_setopt(curl, uwsgi_str(p), uacc);
		p = strtok_r(NULL, ";", &ctx);
	}

	for(;;) {
		int ret = event_queue_wait(ut->queue, -1, &interesting_fd);
		if (ret < 0) return;
		if (ret == 0) continue;
		if (interesting_fd != ut->pipe[1]) continue;
		ssize_t rlen = read(ut->pipe[1], ut->buf, uwsgi.log_master_bufsize);
		if (rlen <= 0) continue;
		ut->pos = 0;
		ut->len = (size_t) rlen;
		ut->custom0 = 0;

		char *notice = uwsgi_format_airbrake_backtrace(ut);

		curl_slist_append(expect, "Accept: */*");
		curl_slist_append(expect, "Content-Type: text/xml; charset=utf-8");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, expect);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, notice);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(notice));

		curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t) ut->len);
		CURLcode res = curl_easy_perform(curl);
		if (res != CURLE_OK) {
			uwsgi_log_alarm("-curl] curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
		}
		free(notice);
	}
}
Exemplo n.º 11
0
int get_dialog_state(str body, int *dialog_state)
{
	xmlDocPtr doc;
	xmlNodePtr node;
	unsigned char* state = NULL;
	int i;

	doc = xmlParseMemory(body.s, body.len);
	if(doc== NULL)
	{
		LM_ERR("failed to parse xml document\n");
		return -1;
	}

	node = doc->children;
	node = xmlNodeGetChildByName(node, "dialog");

	if(node == NULL)
	{
		*dialog_state = DLG_DESTROYED;
		xmlFreeDoc(doc);
		return 0;
	}

	node = xmlNodeGetChildByName(node, "state");
	if(node == NULL)
	{
		LM_ERR("Malformed document - no state found\n");
		goto error;
	}
	state = xmlNodeGetContent(node);
	if(state == NULL)
	{
		LM_ERR("Malformed document - null state\n");
		goto error;
	}
	LM_DBG("state = %s\n", state);
	for(i = 0; i< DLG_STATES_NO; i++)
	{
		if(xmlStrcasecmp(state, BAD_CAST dialog_states[i])==0)
		{
			break;
		}
	}
	xmlFree(state);
	xmlFreeDoc(doc);
	xmlCleanupParser();
	xmlMemoryDump();

	if(i == DLG_STATES_NO)
	{
		LM_ERR("Wrong dialog state\n");
		return -1;
	}

	*dialog_state = i;

	return 0;
error:
	xmlFreeDoc(doc);
	return -1;
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
   int i;

   if (argc != 2) {
      usage(argv[0]);
      exit(1);
   }

   initList(&keys);
   initList(&tags);
   initList(&segs);

   LIBXML_TEST_VERSION

   printf("drop table %s ;\n", table_name_point);
   printf("create table %s ( osm_id int4",table_name_point);
   for (i=0; i < sizeof(exportTags) / sizeof(exportTags[0]); i++)
      printf(",\"%s\" %s", exportTags[i].name, exportTags[i].type);
   printf(" );\n");
   printf("select AddGeometryColumn('%s', 'way', 4326, 'POINT', 2 );\n", table_name_point);
   
   printf("drop table %s ;\n", table_name_line);
   printf("create table %s ( osm_id int4",table_name_line);
   for (i=0; i < sizeof(exportTags) / sizeof(exportTags[0]); i++)
      printf(",\"%s\" %s", exportTags[i].name, exportTags[i].type);
   printf(" );\n");
   printf("select AddGeometryColumn('%s', 'way', 4326, 'LINESTRING', 2 );\n", table_name_line);
   
   printf("drop table %s ;\n", table_name_polygon);
   printf("create table %s ( osm_id int4",table_name_polygon);
   for (i=0; i < sizeof(exportTags) / sizeof(exportTags[0]); i++)
      printf(",\"%s\" %s", exportTags[i].name, exportTags[i].type);
   printf(" );\n");
   printf("select AddGeometryColumn('%s', 'way', 4326, 'GEOMETRY', 2 );\n", table_name_polygon);
   
   printf("begin;\n");
   streamFile(argv[1]);
   printf("commit;\n");
   
   printf("vacuum analyze %s;\n", table_name_point);
   printf("vacuum analyze %s;\n", table_name_line);
   printf("vacuum analyze %s;\n", table_name_polygon);
   
   printf("CREATE INDEX way_index0 ON %s USING GIST (way GIST_GEOMETRY_OPS);\n", table_name_point);
   printf("ALTER TABLE %s ALTER COLUMN way SET NOT NULL;\n",table_name_point);
   printf("CLUSTER way_index0 on %s;\n",table_name_point);
   printf("vacuum analyze %s;\n", table_name_point);
   
   printf("CREATE INDEX way_index1 ON %s USING GIST (way GIST_GEOMETRY_OPS);\n", table_name_line);
   printf("ALTER TABLE %s ALTER COLUMN way SET NOT NULL;\n",table_name_line);
   printf("ALTER TABLE %s ADD COLUMN z_order int4 default 0;\n",table_name_line);
   printf("CLUSTER way_index1 on %s;\n",table_name_line);
   printf("vacuum analyze %s;\n", table_name_line);
   
   printf("CREATE INDEX way_index2 ON %s USING GIST (way GIST_GEOMETRY_OPS);\n", table_name_polygon);
   printf("ALTER TABLE %s ALTER COLUMN way SET NOT NULL;\n",table_name_polygon);
   printf("CLUSTER way_index2 on %s;\n",table_name_polygon);
   printf("vacuum analyze %s;\n", table_name_polygon);

   xmlCleanupParser();
   xmlMemoryDump();

   fprintf(stderr, "\n");

   fprintf(stderr, "Node stats: out(%d), total(%d), max(%d)\n", count_node, count_all_node, max_node);
   fprintf(stderr, "Segment stats: out(%d), total(%d), max(%d)\n", count_segment, count_all_segment, max_segment);
   fprintf(stderr, "Way stats: out(%d), total(%d), max(%d)\n", count_way, count_all_way, max_way);
   fprintf(stderr, "Way stats: duplicate segments in ways %d\n", count_way_seg);

   return 0;
}
Exemplo n.º 13
0
int pres_process_body(publ_info_t* publ, str** fin_body, int ver, str** tuple_param)
{

	xmlDocPtr doc= NULL;
	xmlNodePtr node= NULL;
	char* tuple_id= NULL, *person_id= NULL;
	int tuple_id_len= 0;
	char buf[50];
	str* body= NULL;
	int alloc_tuple= 0;
	str* tuple= NULL;

	doc= xmlParseMemory(publ->body->s, publ->body->len );
	if(doc== NULL)
	{
		LM_ERR("while parsing xml memory\n");
		goto error;
	}

	node= xmlDocGetNodeByName(doc, "tuple", NULL);
	if(node == NULL)
	{
		LM_ERR("while extracting tuple node\n");
		goto error;
	}
	tuple= *(tuple_param);

	tuple_id= xmlNodeGetAttrContentByName(node, "id");
	if(tuple_id== NULL)
	{

		if(tuple== NULL)	// generate a tuple_id
		{
			tuple_id= buf;
			tuple_id_len= sprintf(tuple_id, "%p", publ);
			tuple_id[tuple_id_len]= '\0'; 

			tuple=(str*)pkg_malloc(sizeof(str));
			if(tuple== NULL)
			{
				LM_ERR("No more memory\n");
				goto error;
			}
			tuple->s= (char*)pkg_malloc(tuple_id_len* sizeof(char));
			if(tuple->s== NULL)
			{
				LM_ERR("NO more memory\n");
				goto error;
			}
			memcpy(tuple->s, tuple_id, tuple_id_len);
			tuple->len= tuple_id_len;

			*tuple_param= tuple;
			alloc_tuple= 1;

			LM_DBG("allocated tuple_id\n\n");
		}
		else
		{
			tuple_id= buf;
			tuple_id_len= tuple->len;
			memcpy(tuple_id, tuple->s, tuple_id_len);
			tuple_id[tuple_id_len]= '\0';
		}
		/* add tuple id */
		if(!xmlNewProp(node, BAD_CAST "id", BAD_CAST tuple_id))
		{
			LM_ERR("while extracting xml"
						" node\n");
			goto error;
		}
	}
	else
	{
		if(tuple== NULL)
		{
			strcpy(buf, tuple_id);
			xmlFree(tuple_id);
			tuple_id= buf;
			tuple_id_len= strlen(tuple_id);
		
			tuple=(str*)pkg_malloc(sizeof(str));
			if(tuple== NULL)
			{
				LM_ERR("No more memory\n");
				goto error;
			}
			tuple->s= (char*)pkg_malloc(tuple_id_len* sizeof(char));
			if(tuple->s== NULL)
			{
				LM_ERR("NO more memory\n");
				goto error;
			}
			memcpy(tuple->s, tuple_id, tuple_id_len);
			tuple->len= tuple_id_len;
			*tuple_param= tuple;
			alloc_tuple= 1;
		}
	}

	node= xmlDocGetNodeByName(doc, "person", NULL);
	if(node)
	{
		LM_DBG("found person node\n");
		person_id= xmlNodeGetAttrContentByName(node, "id");
		if(person_id== NULL)
		{	
			if(!xmlNewProp(node, BAD_CAST "id", BAD_CAST tuple_id))
			{
				LM_ERR("while extracting xml"
						" node\n");
				goto error;
			}
		}
		else
		{
			xmlFree(person_id);
		}
	}	
	body= (str*)pkg_malloc(sizeof(str));
	if(body== NULL)
	{
		LM_ERR("NO more memory left\n");
		goto error;
	}
	memset(body, 0, sizeof(str));
	xmlDocDumpFormatMemory(doc,(xmlChar**)(void*)&body->s, &body->len, 1);	
	if(body->s== NULL || body->len== 0)
	{
		LM_ERR("while dumping xml format\n");
		goto error;
	}	
	xmlFreeDoc(doc);
	doc= NULL;
	
	*fin_body= body;
	xmlMemoryDump();
	xmlCleanupParser();
	return 1;

error:
	if(doc)
		xmlFreeDoc(doc);
	if(body)
		pkg_free(body);
	if(tuple && alloc_tuple)
	{
		if(tuple->s)
			pkg_free(tuple->s);
		pkg_free(tuple);
		tuple= NULL;
	}
	return -1;

}	
Exemplo n.º 14
0
int main(int argc, char **argv) {
    int i;
    int ret;
    int exit_value = 0;


    if (argc <= 1) {
	usage(argv[0]);
	return(1);
    }

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

	if (argv[i][0] != '-')
	    break;
	if ((!strcmp(argv[i], "-verbose")) ||
	    (!strcmp(argv[i], "-v")) ||
	    (!strcmp(argv[i], "--verbose"))) {
	    verbose++;
	    xmlCatalogSetDebug(verbose);
	} else if ((!strcmp(argv[i], "-noout")) ||
	    (!strcmp(argv[i], "--noout"))) {
            noout = 1;
	} else if ((!strcmp(argv[i], "-shell")) ||
	    (!strcmp(argv[i], "--shell"))) {
	    shell++;
            noout = 1;
	} else if ((!strcmp(argv[i], "-sgml")) ||
	    (!strcmp(argv[i], "--sgml"))) {
	    sgml++;
	} else if ((!strcmp(argv[i], "-create")) ||
	    (!strcmp(argv[i], "--create"))) {
	    create++;
	} else if ((!strcmp(argv[i], "-convert")) ||
	    (!strcmp(argv[i], "--convert"))) {
	    convert++;
	} else if ((!strcmp(argv[i], "-add")) ||
	    (!strcmp(argv[i], "--add"))) {
	    if (sgml)
		i += 2;
	    else
		i += 3;
	    add++;
	} else if ((!strcmp(argv[i], "-del")) ||
	    (!strcmp(argv[i], "--del"))) {
	    i += 1;
	    del++;
	} else {
	    fprintf(stderr, "Unknown option %s\n", argv[i]);
	    usage(argv[0]);
	    return(1);
	}
    }

    for (i = 1; i < argc; i++) {
	if ((!strcmp(argv[i], "-add")) ||
	    (!strcmp(argv[i], "--add"))) {
	    if (sgml)
		i += 2;
	    else
		i += 3;
	    continue;
	} else if ((!strcmp(argv[i], "-del")) ||
	    (!strcmp(argv[i], "--del"))) {
	    i += 1;
	    continue;
	} else if (argv[i][0] == '-')
	    continue;
	filename = argv[i];
	if (!sgml) {
	    ret = xmlLoadCatalog(argv[i]);
	    if ((ret < 0) && (create)) {
		xmlCatalogAdd(BAD_CAST "catalog", BAD_CAST argv[i], NULL);
	    }
	}
	break;
    }

    if (convert)
        ret = xmlCatalogConvert();

    if ((add) || (del)) {
	for (i = 1; i < argc ; i++) {
	    if (!strcmp(argv[i], "-"))
		break;

	    if (argv[i][0] != '-')
		continue;
	    if (strcmp(argv[i], "-add") && strcmp(argv[i], "--add") &&
		strcmp(argv[i], "-del") && strcmp(argv[i], "--del"))
		continue;

	    if (sgml) {
		/*
		 * Maintenance of SGML catalogs.
		 */
		xmlCatalogPtr catal = NULL;
		xmlCatalogPtr super = NULL;

		catal = xmlLoadSGMLSuperCatalog(argv[i + 1]);

		if ((!strcmp(argv[i], "-add")) ||
		    (!strcmp(argv[i], "--add"))) {
		    if (catal == NULL)
			catal = xmlNewCatalog(1);
		    super = xmlLoadSGMLSuperCatalog(XML_SGML_DEFAULT_CATALOG);
		    if (super == NULL)
			super = xmlNewCatalog(1);

		    xmlACatalogAdd(catal, BAD_CAST "CATALOG",
					 BAD_CAST argv[i + 2], NULL);
		    xmlACatalogAdd(super, BAD_CAST "CATALOG",
					 BAD_CAST argv[i + 1], NULL);
		} else {
		    if (catal != NULL)
			ret = xmlACatalogRemove(catal, BAD_CAST argv[i + 2]);
		    else
			ret = -1;
		    if (ret < 0) {
			fprintf(stderr, "Failed to remove entry from %s\n",
				argv[i + 1]);
			exit_value = 1;
		    }
		    if ((noout) && (catal != NULL) &&
			(xmlCatalogIsEmpty(catal))) {
			super = xmlLoadSGMLSuperCatalog(
				   XML_SGML_DEFAULT_CATALOG);
			if (super != NULL) {
			    ret = xmlACatalogRemove(super,
				    BAD_CAST argv[i + 1]);
			    if (ret < 0) {
				fprintf(stderr,
					"Failed to remove entry from %s\n",
					XML_SGML_DEFAULT_CATALOG);
				exit_value = 1;
			    }
			}
		    }
		}
		if (noout) {
		    FILE *out;

		    if (xmlCatalogIsEmpty(catal)) {
			remove(argv[i + 1]);
		    } else {
			out = fopen(argv[i + 1], "w");
			if (out == NULL) {
			    fprintf(stderr, "could not open %s for saving\n",
				    argv[i + 1]);
			    exit_value = 2;
			    noout = 0;
			} else {
			    xmlACatalogDump(catal, out);
			    fclose(out);
			}
		    }
		    if (super != NULL) {
			if (xmlCatalogIsEmpty(super)) {
			    remove(XML_SGML_DEFAULT_CATALOG);
			} else {
			    out = fopen(XML_SGML_DEFAULT_CATALOG, "w");
			    if (out == NULL) {
				fprintf(stderr,
					"could not open %s for saving\n",
					XML_SGML_DEFAULT_CATALOG);
				exit_value = 2;
				noout = 0;
			    } else {
				
				xmlACatalogDump(super, out);
				fclose(out);
			    }
			}
		    }
		} else {
		    xmlACatalogDump(catal, stdout);
		}
		i += 2;
	    } else {
		if ((!strcmp(argv[i], "-add")) ||
		    (!strcmp(argv[i], "--add"))) {
			if ((argv[i + 3] == NULL) || (argv[i + 3][0] == 0))
			    ret = xmlCatalogAdd(BAD_CAST argv[i + 1], NULL,
						BAD_CAST argv[i + 2]);
			else
			    ret = xmlCatalogAdd(BAD_CAST argv[i + 1],
						BAD_CAST argv[i + 2],
						BAD_CAST argv[i + 3]);
			if (ret != 0) {
			    printf("add command failed\n");
			    exit_value = 3;
			}
			i += 3;
		} else if ((!strcmp(argv[i], "-del")) ||
		    (!strcmp(argv[i], "--del"))) {
		    ret = xmlCatalogRemove(BAD_CAST argv[i + 1]);
		    if (ret < 0) {
			fprintf(stderr, "Failed to remove entry %s\n",
				argv[i + 1]);
			exit_value = 1;
		    }
		    i += 1;
		}
	    }
	}
	
    } else if (shell) {
	usershell();
    } else {
	for (i++; i < argc; i++) {
	    xmlURIPtr uri;
	    xmlChar *ans;
	    
	    uri = xmlParseURI(argv[i]);
	    if (uri == NULL) {
		ans = xmlCatalogResolvePublic((const xmlChar *) argv[i]);
		if (ans == NULL) {
		    printf("No entry for PUBLIC %s\n", argv[i]);
		    exit_value = 4;
		} else {
		    printf("%s\n", ans);
		    xmlFree(ans);
		}
	    } else {
                xmlFreeURI(uri);
		ans = xmlCatalogResolveSystem((const xmlChar *) argv[i]);
		if (ans == NULL) {
		    printf("No entry for SYSTEM %s\n", argv[i]);
		    exit_value = 4;
		} else {
		    printf("%s\n", ans);
		    xmlFree(ans);
		}
	    }
	}
    }
    if ((!sgml) && ((add) || (del) || (create) || (convert))) {
	if (noout) {
	    FILE *out;

	    out = fopen(filename, "w");
	    if (out == NULL) {
		fprintf(stderr, "could not open %s for saving\n", filename);
		exit_value = 2;
		noout = 0;
	    } else {
		xmlCatalogDump(out);
	    }
	} else {
	    xmlCatalogDump(stdout);
	}
    }

    /*
     * Cleanup and check for memory leaks
     */
    xmlCleanupParser();
    xmlMemoryDump();
    return(exit_value);
}
Exemplo n.º 15
0
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;
}
Exemplo n.º 16
0
int build_xmpp_content(str* to_uri, str* from_uri, str* body, str* id,
		int is_terminated)
{
	xmlDocPtr sip_doc= NULL;
	xmlDocPtr doc= NULL;
	xmlNodePtr xmpp_root= NULL;
	xmlNodePtr sip_root= NULL;
	xmlNodePtr new_node= NULL;
	xmlNodePtr node = NULL;
	xmlBufferPtr buffer= NULL;
	xmlAttrPtr attr= NULL;
	char* basic= NULL, *priority= NULL, *note= NULL;
	str xmpp_msg;

	LM_DBG("start...\n");

	/* creating the xml doc for the xmpp message*/
	doc= xmlNewDoc(0);
	if(doc== NULL)
	{
		LM_ERR("when creating new xml doc\n");
		goto error;
	}
	xmpp_root = xmlNewNode(NULL, BAD_CAST "presence");
	if(xmpp_root==0)
	{
		LM_ERR("when adding new node- presence\n");
		goto error;
	}
	xmlDocSetRootElement(doc, xmpp_root);

	attr= xmlNewProp(xmpp_root, BAD_CAST "to", BAD_CAST to_uri->s);
	if(attr== NULL)
	{
		LM_ERR("while adding new attribute\n");
		goto error;
	}
	attr= xmlNewProp(xmpp_root, BAD_CAST "from", BAD_CAST from_uri->s);
	if(attr== NULL)
	{
		LM_ERR("while adding new attribute\n");
		goto error;
	}
	if(is_terminated)
	{
		attr=  xmlNewProp(xmpp_root, BAD_CAST "type", BAD_CAST "unsubscribed");
		if(attr== NULL)
		{
			LM_ERR("while adding new attribute\n");
			goto error;
		}
		goto done;
	}
	if(body->s== NULL)
	{
		attr=  xmlNewProp(xmpp_root, BAD_CAST "type", BAD_CAST "unavailable");
		if(attr== NULL)
		{
			LM_ERR("while adding new attribute\n");
			goto error;
		}
		goto done;
	}

	/*extractiong the information from the sip message body*/
	sip_doc= xmlParseMemory(body->s, body->len);
	if(sip_doc== NULL)
	{
		LM_ERR("while parsing xml memory\n");
		return -1;
	}
	sip_root= XMLDocGetNodeByName(sip_doc, "presence", NULL);
	if(sip_root== NULL)
	{
		LM_ERR("while extracting 'presence' node\n");
		goto error;
	}

	node = XMLNodeGetNodeByName(sip_root, "basic", NULL);
	if(node== NULL)
	{
		LM_ERR("while extracting status basic node\n");
		goto error;
	}
	basic= (char*)xmlNodeGetContent(node);
	if(basic== NULL)
	{
		LM_ERR("while extracting status basic node content\n");
		goto error;
	}
	if(xmlStrcasecmp( (unsigned char*)basic,(unsigned char*) "closed")==0 )
	{
		attr= xmlNewProp(xmpp_root, BAD_CAST "type", BAD_CAST "unavailable");
		if(attr== NULL)
		{
			LM_ERR("while adding node attr\n");
			xmlFree(basic);
			goto error;
		}
		xmlFree(basic);
		goto done;
	}/* else the status is open so no type attr should be added */

	xmlFree(basic);
	/* addind show node */
	node= XMLNodeGetNodeByName(sip_root, "note", NULL);
	if(node== NULL)
	{
		LM_DBG("No note node found\n");
		node= XMLNodeGetNodeByName(sip_root, "person", NULL);
		if(node== NULL)
		{
			LM_DBG("No person node found\n");
			goto done;
		}
		node= XMLNodeGetNodeByName(node, "note", NULL);
		if(node== NULL)
		{
			LM_DBG("Person node has no note node\n");
			goto done;
		}
	}
	note= (char*)xmlNodeGetContent(node);
	if(note== NULL)
	{
		LM_ERR("while extracting note node content\n");
		goto error;
	}

	if(xmlStrcasecmp((unsigned char*)note, (unsigned char*)"away")== 0)
	{
		new_node = xmlNewChild(xmpp_root, NULL, BAD_CAST "show",
				BAD_CAST "away");
		if(new_node== NULL)
		{
			LM_ERR("while adding node show: away\n");
			goto error;
		}
	}
	else
		if(xmlStrcasecmp((unsigned char*)note, (unsigned char*)"busy")== 0)
		{
			new_node = xmlNewChild(xmpp_root, NULL, BAD_CAST "show"
					, BAD_CAST "xa");
			if(new_node== NULL)
			{
				LM_ERR("while adding node show: away\n");
				goto error;
			}
		}

		/*
		if(xmlStrcasecmp((unsigned char*)note, (unsigned char*)"on the phone")== 0)
		{
			new_node = xmlNewChild(xmpp_root, NULL, BAD_CAST "show", BAD_CAST "chat");
			if(new_node== NULL)
			{
				LM_ERR("while adding node show: chat\n");
				goto error;
			}
		}
		else
			if(xmlStrcasecmp((unsigned char*)note, (unsigned char*)"idle")== 0)
			{
				new_node = xmlNewChild(xmpp_root, NULL, BAD_CAST "show", BAD_CAST "idle");
				if(new_node== NULL)
				{
					LM_ERR("while adding node: idle\n");
					goto error;
				}
			}
			else */
				if((xmlStrcasecmp((unsigned char*)note,
					(unsigned char*)"dnd")== 0)||
					(xmlStrcasecmp((unsigned char*)note,
						(unsigned char*)"do not disturb")== 0))
				{
					new_node = xmlNewChild(xmpp_root, NULL, BAD_CAST "show",
							BAD_CAST "dnd");
					if(new_node== NULL)
					{
						LM_ERR("while adding node show: dnd\n");
						goto error;
					}
				}


	/* adding status node */
	new_node = xmlNewChild(xmpp_root, NULL, BAD_CAST "status", BAD_CAST note);
	if(new_node== NULL)
	{
		LM_ERR("while adding node status\n");
		goto error;
	}

	xmlFree(note);
	note= NULL;

	/* adding priotity node*/
	node= XMLNodeGetNodeByName(sip_root, "contact", NULL);
	if(node== NULL)
	{
		LM_DBG("No contact node found\n");
	}
	else
	{
		priority= XMLNodeGetAttrContentByName(node, "priority");
		if(priority== NULL)
			LM_DBG("No priority attribute found\n");
		else
		{
			new_node= xmlNewChild(xmpp_root, NULL, BAD_CAST "priority",
					BAD_CAST priority);
			if(sip_root== NULL)
			{
				LM_ERR("while adding node\n");
				xmlFree(priority);
				goto error;
			}
			xmlFree(priority);
		}
	}

done:
	buffer= xmlBufferCreate();
	if(buffer== NULL)
	{
		LM_ERR("while adding creating new buffer\n");
		goto error;
	}

	xmpp_msg.len= xmlNodeDump(buffer, doc, xmpp_root, 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_notify(from_uri, to_uri, &xmpp_msg, id)< 0)
	{
		LM_ERR("while sending xmpp_notify\n");
		goto error;
	}

	xmlBufferFree(buffer);
	xmlCleanupParser();
	xmlMemoryDump();

	if(sip_doc)
		xmlFreeDoc(sip_doc);
	if(doc)
		xmlFreeDoc(doc);
	return 0;

error:
	if(sip_doc)
		xmlFreeDoc(sip_doc);
	if(note)
		xmlFree(note);
	if(buffer)
		xmlBufferFree(buffer);
	xmlCleanupParser();
	xmlMemoryDump();

	return -1;

}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
#else
int OCG_main(char is_local_server[FILENAME_LENGTH_MAX])
{
#endif
  int state = STATE_START_OCG;
  char web_XML_folder[DIR_LENGTH_MAX] = "";
  char output_dir[DIR_LENGTH_MAX] = ""; // the output folder during the OCG procedure. Change step by step

  char *OPENAIR_TARGETS=getenv("OPENAIR_TARGETS");

  if (OPENAIR_TARGETS == NULL) {
    LOG_E(OCG, "please set the PATH for OPENAIR_TARGETS");
    exit(EXIT_FAILURE);
  }

  if (!strcmp(is_local_server, "0")) { // Eurecom web server
    strcpy(web_XML_folder, WEB_XML_FOLDER);
    strcat(output_dir, OUTPUT_DIR);
  } else { // local user

    sprintf(web_XML_folder,"%s/SIMU/EXAMPLES/OSD/WEBXML/",getenv("OPENAIR_TARGETS"));
    sprintf(output_dir,"%s/SIMU/EXAMPLES/OSD/RESULTS/",getenv("OPENAIR_TARGETS"));
    /*
    strcpy(web_XML_folder, OPENAIR_TARGETS);
    strcpy(output_dir, OPENAIR_TARGETS);

    char *slash;
    slash = web_XML_folder + strlen(web_XML_folder) - 1;
    if (strcmp(slash, "/")) { // check if the path OPENAIR_TARGETS is ended with a '/'
      strcat(web_XML_folder, "/");
      strcat(output_dir, "/");
    }
    strcat(web_XML_folder, "SIMU/EXAMPLES/OSD/WEBXML/");
    strcat(output_dir, "SIMU/EXAMPLES/OSD/RESULTS/");
    */
  }

  LOG_I(OCG, "Folder for detecting the XML configuration file is %s\n", web_XML_folder);
  LOG_I(OCG, "Folder for generating the results is %s\n", output_dir);
  LOG_I(OCG, "OSD XML config file is %s\n", is_local_server);


  while(state != STATE_END) {

    switch(state) {

    case STATE_START_OCG :
      LOG_I(OCG, "OCG starts ...\n\n");
      get_opt_OK = MODULE_NOT_PROCESSED; // -9999 is the initial value, representing the module not processed
      detect_file_OK = MODULE_NOT_PROCESSED;
      create_dir_OK = MODULE_NOT_PROCESSED;

      // to write the pid into a file 'OCG.pid' so that the web portal part could check if OCG is running
      /*
      pid_t pid;
      pid = getpid();
      FILE *OCG_pid;
      OCG_pid = fopen("OCG.pid", "w");
      fprintf(OCG_pid, "%d\n", pid);
      fclose(OCG_pid);
      */
#ifdef TEST_OCG
      state = STATE_GET_OPT;

    case STATE_GET_OPT :
      get_opt_OK = get_opt(argc, argv);

      if (get_opt_OK == MODULE_OK) {
        strcpy(src_file, LOCAL_XML_FOLDER);
        copy_or_move = 1;
        state = STATE_INI_EMU;
      } else if (get_opt_OK == GET_HELP) state = STATE_END;
      else state = STATE_DETECT_FILE;

      break;
#else
      state = STATE_DETECT_FILE;
      //get_opt_OK == MODULE_OK;
#endif

    case STATE_DETECT_FILE :
      strcpy(src_file, web_XML_folder);
      detect_file_OK = detect_file(src_file, is_local_server);

      if (detect_file_OK == MODULE_OK) {
        if ((!strcmp(is_local_server, "0")) || (!strcmp(is_local_server, "-1"))) copy_or_move = 2;

        state = STATE_INI_EMU;
      } else if (detect_file_OK == MODULE_ERROR) state = STATE_GENERATE_REPORT;
      else if (detect_file_OK == NO_FILE) {
        state = STATE_DETECT_FILE;
        sleep(1);
      }

      break;

    case STATE_INI_EMU : // before initiating an emu, an XML file should be found above
      parse_filename_OK = MODULE_NOT_PROCESSED;
      create_dir_OK = MODULE_NOT_PROCESSED;
      parse_XML_OK = MODULE_NOT_PROCESSED;
      save_XML_OK = MODULE_NOT_PROCESSED;
      //        call_emu_OK = MODULE_NOT_PROCESSED;
      //config_mobi_OK = MODULE_NOT_PROCESSED;
      generate_report_OK = MODULE_NOT_PROCESSED;

      LOG_I(OCG, "An emulation for file %s is initiated\n", filename);
      state = STATE_PARSE_FILENAME;
      break;

    case STATE_PARSE_FILENAME :
      strcat(src_file, filename);

      if ((parse_filename_OK = parse_filename(filename)) == MODULE_OK) state = STATE_CREATE_DIR;
      else {
        if (copy_or_move == 2) {
          remove(src_file);
          state = STATE_DETECT_FILE;
        } else state = STATE_GENERATE_REPORT;
      }

      break;

    case STATE_CREATE_DIR :
      if ((create_dir_OK = create_dir(output_dir, user_name, file_date)) == MODULE_OK) {
        state = STATE_PARSE_XML;
        strcat(output_dir, user_name);
        strcat(output_dir, "/");
        strcat(output_dir, file_date);
        strcat(output_dir, "/");
        strcpy(dst_dir, output_dir);
        oai_emulation.info.output_path = dst_dir; // information for other modules within OAI
      } else state = STATE_GENERATE_REPORT;

      break;

    case STATE_PARSE_XML :
      if ((parse_XML_OK = parse_XML(src_file)) == MODULE_OK) state = STATE_SAVE_XML;
      else {
        if (copy_or_move == 2) remove(src_file);

        state = STATE_GENERATE_REPORT;
      }

      break;

    case STATE_SAVE_XML :
      if ((save_XML_OK = save_XML(copy_or_move, src_file, output_dir, filename)) == MODULE_OK)
        state = STATE_CALL_EMU;
      else state = STATE_GENERATE_REPORT;

      break;

    case STATE_CALL_EMU : // change this state to set_params

      if ((detect_file_OK == MODULE_OK) && (parse_filename_OK == MODULE_OK) && (create_dir_OK == MODULE_OK) && (parse_XML_OK == MODULE_OK) && (save_XML_OK == MODULE_OK)) {
        // if the above tasks are all successful, we could tell the oaisim_config.c that everything is ready before running the emulation
        oai_emulation.info.ocg_ok = 1;
      }

#ifdef TEST_OCG
      call_emu_OK = call_emu(output_dir);
      // config_mobi_OK = config_mobi("RWMEmulator.xml", filename); // generate the XML for Mobigen
#endif
      state = STATE_GENERATE_REPORT;
      break;

    case STATE_GENERATE_REPORT :
      if (create_dir_OK != MODULE_OK) {
        // a temp folder is required when the output folder could not be correctly generated
        strncpy(output_dir, OPENAIR_TARGETS, sizeof(output_dir));
        output_dir[sizeof(output_dir) - 1] = 0; // terminate string
        strncat(output_dir, "SIMU/EXAMPLES/OSD/", sizeof(output_dir) - strlen(output_dir) - 1);
        strncat(output_dir, TEMP_OUTPUT_DIR, sizeof(output_dir) - strlen(output_dir) - 1);
        struct stat st;

        if(stat(output_dir, &st) != 0) { // if temp output directory does not exist, we create it here
          mkdir(output_dir, S_IRWXU | S_IRWXG | S_IRWXO);
          LOG_I(OCG, "temp output directory %s is created", output_dir);
        }
      } else {
        //strcat(output_dir, "SCENARIO/STATE/"); // if needeed the outpur directory can be further set
        LOG_I(OCG, "Output directory is %s \n", output_dir);
      }

      generate_report(output_dir, "OCG_report.xml");

      if (copy_or_move == 1) state = STATE_END;
      else state = STATE_END;

      //else state = STATE_DETECT_FILE;
      break;
    }
  } // end while

  // Cleanup function for the XML library.
  xmlCleanupParser();
  // this is to debug memory for regression tests
  xmlMemoryDump();
  LOG_I(OCG, "... OCG ends\n\n");
#ifdef TEST_OCG
  return 0;
#else
  return 1;
#endif
}
Exemplo n.º 18
0
void config_free(xmlDocPtr pdoc)
{
	xmlFreeDoc(pdoc);
	xmlCleanupParser();
	xmlMemoryDump();
}
Exemplo n.º 19
0
str* offline_nbody(str* body)
{
	xmlDocPtr doc= NULL;
	xmlDocPtr new_doc= NULL;
	xmlNodePtr node, tuple_node= NULL, status_node;
	xmlNodePtr root_node, add_node, pres_node;
	str* new_body;

	doc= xmlParseMemory(body->s, body->len);
	if(doc==  NULL)
	{
		LM_ERR("while parsing xml memory\n");
		return NULL;
	}
	node= xmlDocGetNodeByName(doc, "basic", NULL);
	if(node== NULL)
	{
		LM_ERR("while extracting basic node\n");
		goto error;
	}
	xmlNodeSetContent(node, (const unsigned char*)"closed");

	tuple_node= xmlDocGetNodeByName(doc, "tuple", NULL);
	if(tuple_node== NULL)
	{
		LM_ERR("while extracting tuple node\n");
		goto error;
	}
	status_node= xmlDocGetNodeByName(doc, "status", NULL);
	if(status_node== NULL)
	{
		LM_ERR("while extracting tuple node\n");
		goto error;
	}

	pres_node= xmlDocGetNodeByName(doc, "presence", NULL);
	if(node== NULL)
	{
		LM_ERR("while extracting presence node\n");
		goto error;
	}

    new_doc = xmlNewDoc(BAD_CAST "1.0");
    if(new_doc==0)
		goto error;
	root_node= xmlCopyNode(pres_node, 2);
	if(root_node== NULL)
	{
		LM_ERR("while copying node\n");
		goto error;
	}
    xmlDocSetRootElement(new_doc, root_node);

	tuple_node= xmlCopyNode(tuple_node, 2);
	if(tuple_node== NULL)
	{
		LM_ERR("while copying node\n");
		goto error;
	}
	xmlAddChild(root_node, tuple_node);

	add_node= xmlCopyNode(status_node, 1);
	if(add_node== NULL)
	{
		LM_ERR("while copying node\n");
		goto error;
	}
	xmlAddChild(tuple_node, add_node);

	new_body = (str*)pkg_malloc(sizeof(str));
	if(new_body == NULL)
	{
		ERR_MEM(PKG_MEM_STR);
	}
	memset(new_body, 0, sizeof(str));

	xmlDocDumpFormatMemory(new_doc,(xmlChar**)(void*)&new_body->s,
		&new_body->len, 1);

	xmlFreeDoc(doc);
	xmlFreeDoc(new_doc);
	xmlCleanupParser();
	xmlMemoryDump();

	return new_body;

error:
	if(doc)
		xmlFreeDoc(doc);
	if(new_doc)
		xmlFreeDoc(new_doc);
	return NULL;

}		
Exemplo n.º 20
0
int main(int argc, char **argv) {

    xmlInitMemory();

    if (argc == 1) {
	int ret;
	xmlAutomataPtr am;
	xmlAutomataStatePtr start, cur;
	xmlRegexpPtr regexp;
	xmlRegExecCtxtPtr exec;

	am = xmlNewAutomata();
	start = xmlAutomataGetInitState(am);

	
	cur = xmlAutomataNewTransition(am, start, NULL, BAD_CAST"a", NULL);
	xmlAutomataNewTransition(am, cur, cur, BAD_CAST"b", NULL);
	xmlAutomataNewTransition(am, cur, cur, BAD_CAST"a", NULL);
	cur = xmlAutomataNewCountTrans(am, cur, NULL, BAD_CAST"a", 2, 3, NULL);
	xmlAutomataSetFinalState(am, cur);

	
	regexp = xmlAutomataCompile(am);
	xmlFreeAutomata(am);

	
	xmlRegexpPrint(stdout, regexp);
	exec = xmlRegNewExecCtxt(regexp, NULL, NULL);
	ret = xmlRegExecPushString(exec, BAD_CAST"a", NULL);
	if (ret == 1)
	    printf("final\n");
	else if (ret < 0)
	    printf("error\n");
	ret =xmlRegExecPushString(exec, BAD_CAST"a", NULL);
	if (ret == 1)
	    printf("final\n");
	else if (ret < 0)
	    printf("error\n");
	ret =xmlRegExecPushString(exec, BAD_CAST"b", NULL);
	if (ret == 1)
	    printf("final\n");
	else if (ret < 0)
	    printf("error\n");
	ret =xmlRegExecPushString(exec, BAD_CAST"a", NULL);
	if (ret == 1)
	    printf("final\n");
	else if (ret < 0)
	    printf("error\n");
	ret =xmlRegExecPushString(exec, BAD_CAST"a", NULL);
	if (ret == 1)
	    printf("final\n");
	else if (ret < 0)
	    printf("error\n");
	ret =xmlRegExecPushString(exec, BAD_CAST"a", NULL);
	if (ret == 1)
	    printf("final\n");
	else if (ret < 0)
	    printf("error\n");
	ret =xmlRegExecPushString(exec, BAD_CAST"a", NULL);
	if (ret == 1)
	    printf("final\n");
	else if (ret < 0)
	    printf("error\n");
	if (ret == 0) {
	    ret = xmlRegExecPushString(exec, NULL, NULL);
	    if (ret == 1)
		printf("final\n");
	    else if (ret < 0)
		printf("error\n");
	}
	xmlRegFreeExecCtxt(exec);

	
	xmlRegFreeRegexp(regexp);
    } else {
	int i;

	for (i = 1;i < argc;i++)
	    testRegexpFile(argv[i]);
    }

    xmlCleanupParser();
    xmlMemoryDump();
    return(0);
}
Exemplo n.º 21
0
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;
}
Exemplo n.º 22
0
Arquivo: board.cpp Projeto: fkp/src
bool Board::InitFromXMLFile(const char * fileName)
{
  bool toReturn = false;
  xmlDocPtr doc;
  xmlXPathContextPtr xpathCtx; 
  xmlXPathObjectPtr xpathObj; 
  int ret;

  // Init libxml
  xmlInitParser();
  LIBXML_TEST_VERSION

  assert(fileName);
  assert(XPathExpression);

  // Load XML document
  doc = xmlParseFile(fileName);

  if (doc == NULL)
  {
    cout << "Error: unable to parse file " << fileName << endl;
    return false;
  }

  // Create xpath evaluation context
  xpathCtx = xmlXPathNewContext(doc);
  if(xpathCtx == NULL)
  {
    cout << "Error: unable to create new XPath context" << endl;
    xmlFreeDoc(doc); 
    return false;
  }
    
  // Evaluate xpath expression
  xpathObj = xmlXPathEvalExpression(BAD_CAST XPathExpression, xpathCtx);
  if(xpathObj == NULL)
  {
    cout << "Error: unable to evaluate xpath expression " << XPathExpression << endl;
    xmlXPathFreeContext(xpathCtx); 
    xmlFreeDoc(doc); 
    return false;
  }

  // Process the nodes in the file
  toReturn = ProcessNodes(xpathObj->nodesetval, stdout);

  // Cleanup
  xmlXPathFreeObject(xpathObj);
  xmlXPathFreeContext(xpathCtx); 
  xmlFreeDoc(doc); 
    
  // Shutdown libxml
  xmlCleanupParser();
    
  // This is to debug memory for regression tests
  xmlMemoryDump();

  // Build the UI table with the squares we have
  BuildTable();

  return toReturn;
}
Exemplo n.º 23
0
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 = HSTORE_NONE;
    int enable_hstore_index = 0;
    int hstore_match_only = 0;
    int enable_multi = 0;
    int parallel_indexing = 1;
    int flat_node_cache_enabled = 0;
#ifdef __amd64__
    int alloc_chunkwise = ALLOC_SPARSE | ALLOC_DENSE;
#else
    int alloc_chunkwise = ALLOC_SPARSE;
#endif
    int num_procs = 1;
    int droptemp = 0;
    int unlogged = 0;
    int excludepoly = 0;
    time_t start, end;
    time_t overall_start, overall_end;
    time_t now;
    time_t end_nodes;
    time_t end_way;
    time_t end_rel;
    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 *tblsmain_index = NULL; /* no default TABLESPACE for index on main tables */
    const char *tblsmain_data = NULL;  /* no default TABLESPACE for main tables */
    const char *tblsslim_index = NULL; /* no default TABLESPACE for index on slim mode tables */
    const char *tblsslim_data = NULL;  /* no default TABLESPACE for slim mode tables */
    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;
    const char *flat_nodes_file = NULL;
    const char *tag_transform_script = NULL;
    int n_hstore_columns = 0;
    int keep_coastlines=0;
    int cache = 800;
    struct output_options options;
    PGconn *sql_conn;
    
    int (*streamFile)(char *, int, struct osmdata_t *);

    fprintf(stderr, "osm2pgsql SVN version %s (%lubit id space)\n\n", VERSION, 8 * sizeof(osmid_t));

    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'},
            {"tablespace-slim-data", 1, 0, 200},
            {"tablespace-slim-index", 1, 0, 201},
            {"tablespace-main-data", 1, 0, 202},
            {"tablespace-main-index", 1, 0, 203},
            {"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-all", 0, 0, 'j'},
            {"hstore-column", 1, 0, 'z'},
            {"hstore-match-only", 0, 0, 208},
            {"hstore-add-index",0,0,211},
            {"multi-geometry", 0, 0, 'G'},
            {"keep-coastlines", 0, 0, 'K'},
            {"input-reader", 1, 0, 'r'},
            {"version", 0, 0, 'V'},
            {"disable-parallel-indexing", 0, 0, 'I'},
            {"cache-strategy", 1, 0, 204},
            {"number-processes", 1, 0, 205},
            {"drop", 0, 0, 206},
            {"unlogged", 0, 0, 207},
            {"flat-nodes",1,0,209},
            {"exclude-invalid-polygon",0,0,210},
            {"tag-transform-script",1,0,212},
            {0, 0, 0, 0}
        };

        c = getopt_long (argc, argv, "ab:cd:KhlmMp:suvU:WH:P:i:IE:C:S:e:o:O:xkjGz: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 'K': keep_coastlines=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': tblsmain_index=tblsslim_index=optarg; break;
            case 200: tblsslim_data=optarg; break;    
            case 201: tblsslim_index=optarg; break;    
            case 202: tblsmain_data=optarg; break;    
            case 203: tblsmain_index=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=HSTORE_NORM; break;
            case 208: hstore_match_only = 1; break;
            case 'j': enable_hstore=HSTORE_ALL; break;
            case 'z': 
                n_hstore_columns++;
                hstore_columns = (const char**)realloc(hstore_columns, sizeof(char *) * 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 'I': 
#ifdef HAVE_PTHREAD
                parallel_indexing=0; 
#endif
                break;
            case 204:
                if (strcmp(optarg,"dense") == 0) alloc_chunkwise = ALLOC_DENSE;
                else if (strcmp(optarg,"chunk") == 0) alloc_chunkwise = ALLOC_DENSE | ALLOC_DENSE_CHUNK;
                else if (strcmp(optarg,"sparse") == 0) alloc_chunkwise = ALLOC_SPARSE;
                else if (strcmp(optarg,"optimized") == 0) alloc_chunkwise = ALLOC_DENSE | ALLOC_SPARSE;
                else {fprintf(stderr, "ERROR: Unrecognized cache strategy %s.\n", optarg); exit(EXIT_FAILURE); }
                break;
            case 205:
#ifdef HAVE_FORK                
                num_procs = atoi(optarg);
#else
                fprintf(stderr, "WARNING: osm2pgsql was compiled without fork, only using one process!\n");
#endif
                break;
            case 206: droptemp = 1; break;
            case 207: unlogged = 1; break;
            case 209:
            	flat_node_cache_enabled = 1;
            	flat_nodes_file = optarg;
            	break;
            case 210: excludepoly = 1; exclude_broken_polygon(); break;
            case 211: enable_hstore_index = 1; break;
            case 212: tag_transform_script = optarg; 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 (droptemp && !slim) {
        fprintf(stderr, "Error: --drop only makes sense with --slim.\n");
        exit(EXIT_FAILURE);
    }

    if (unlogged && !create) {
        fprintf(stderr, "Warning: --unlogged only makes sense with --create; ignored.\n");
        unlogged = 0;
    }

    if (enable_hstore == HSTORE_NONE && !n_hstore_columns && hstore_match_only)
    {
        fprintf(stderr, "Warning: --hstore-match-only only makes sense with --hstore, --hstore-all, or --hstore-column; ignored.\n");
        hstore_match_only = 0;
    }

    if (enable_hstore_index && enable_hstore  == HSTORE_NONE && !n_hstore_columns) {
        fprintf(stderr, "Warning: --hstore-add-index only makes sense with hstore enabled.\n");
        enable_hstore_index = 0;
    }

    if (cache < 0) cache = 0;

    if (num_procs < 1) num_procs = 1;

    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, "Error: Connection to database failed: %s\n", PQerrorMessage(sql_conn));
        exit(EXIT_FAILURE);
    }
    if (unlogged && PQserverVersion(sql_conn) < 90100) {
        fprintf(stderr, "Error: --unlogged works only with PostgreSQL 9.1 and above, but\n");
        fprintf(stderr, "you are using PostgreSQL %d.%d.%d.\n", PQserverVersion(sql_conn) / 10000, (PQserverVersion(sql_conn) / 100) % 100, PQserverVersion(sql_conn) % 100);
        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.tblsmain_index = tblsmain_index;
    options.tblsmain_data = tblsmain_data;
    options.tblsslim_index = tblsslim_index;
    options.tblsslim_data = tblsslim_data;
    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.enable_hstore_index = enable_hstore_index;
    options.hstore_match_only = hstore_match_only;
    options.hstore_columns = hstore_columns;
    options.n_hstore_columns = n_hstore_columns;
    options.keep_coastlines = keep_coastlines;
    options.parallel_indexing = parallel_indexing;
    options.alloc_chunkwise = alloc_chunkwise;
    options.num_procs = num_procs;
    options.droptemp = droptemp;
    options.unlogged = unlogged;
    options.flat_node_cache_enabled = flat_node_cache_enabled;
    options.flat_node_file = flat_nodes_file;
    options.excludepoly = excludepoly;
    options.tag_transform_script = tag_transform_script;

    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);
    }
    options.out = osmdata.out;

    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 if (strcmp("o5m", input_reader) == 0) {
          streamFile = &streamFileO5m;
      } else {
        fprintf(stderr, "Input parser `%s' not recognised. Should be one of [libxml2, primitive, o5m"
#ifdef BUILD_READER_PBF
	      ", pbf"
#endif
	      "].\n", input_reader);
      exit(EXIT_FAILURE);
      }
    }

    time(&overall_start);
    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) {

          if (strcasecmp(".pbf",argv[optind]+strlen(argv[optind])-4) == 0) {
#ifdef BUILD_READER_PBF
            streamFile = &streamFilePbf;
#else
	    fprintf(stderr, "ERROR: PBF support has not been compiled into this version of osm2pgsql, please either compile it with pbf support or use one of the other input formats\n");
	    exit(EXIT_FAILURE);
#endif
          } else if (strcasecmp(".o5m",argv[optind]+strlen(argv[optind])-4) == 0 || strcasecmp(".o5c",argv[optind]+strlen(argv[optind])-4) == 0) {
              streamFile = &streamFileO5m;
          } else {
            streamFile = &streamFileXML2;
          }
        }
        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) {
        time(&now);
        end_nodes = osmdata.start_way > 0 ? osmdata.start_way : now;
        end_way = osmdata.start_rel > 0 ? osmdata.start_rel : now;
        end_rel =  now;
        fprintf(stderr, "\n");
        fprintf(stderr, "Node stats: total(%" PRIdOSMID "), max(%" PRIdOSMID ") in %is\n", osmdata.count_node, osmdata.max_node,
                osmdata.count_node > 0 ? (int)(end_nodes - osmdata.start_node) : 0);
        fprintf(stderr, "Way stats: total(%" PRIdOSMID "), max(%" PRIdOSMID ") in %is\n", osmdata.count_way, osmdata.max_way,
                osmdata.count_way > 0 ? (int)(end_way - osmdata.start_way) : 0);
        fprintf(stderr, "Relation stats: total(%" PRIdOSMID "), max(%" PRIdOSMID ") in %is\n", osmdata.count_rel, osmdata.max_rel,
                osmdata.count_rel > 0 ? (int)(end_rel - osmdata.start_rel) : 0);
    }
    osmdata.out->stop();
    
    free(osmdata.nds);
    free(osmdata.members);
    
    /* free the column pointer buffer */
    free(hstore_columns);

    project_exit();
    text_exit();
    fprintf(stderr, "\n");
    time(&overall_end);
    fprintf(stderr, "Osm2pgsql took %ds overall\n", (int)(overall_end - overall_start));

    return 0;
}
Exemplo n.º 24
0
/* ========================================================================= */
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
}
Exemplo n.º 25
0
void rp9_cleanup(void)
{
  del_tmpFiles();
  xmlCleanupParser();
  xmlMemoryDump();
}
Exemplo n.º 26
0
str* xml_dialog_gen_presence(str* pres_uri, int dlg_state)
{
	char* pres_note;
	xmlDocPtr pres_doc;
	xmlNodePtr node, root_node;
	xmlNodePtr tuple_node, person_node;
	str* dialog_body = NULL;
	char* entity;

	LM_DBG("dlg_state = %d\n", dlg_state);

	pres_note = presence_notes[dlg_state];

	/* if state is terminated, do not add anything */
	if(pres_note && strlen(pres_note) == 0)
	{
		LM_DBG("NULL pres note\n");
		return FAKED_BODY;
	}

	pres_doc= xmlNewDoc(BAD_CAST "1.0");
	if(pres_doc== NULL)
	{
		LM_ERR("allocating new xml doc\n");
		goto error;
	}

	root_node = xmlNewNode(NULL, BAD_CAST "presence");
	if(root_node== NULL)
	{
		LM_ERR("Failed to create xml node\n");
		goto error;
	}
	xmlDocSetRootElement(pres_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");

	entity= (char*)pkg_malloc(pres_uri->len + 1);
	if(entity == NULL)
	{
		LM_ERR("No more memory\n");
		goto error;
	}
	memcpy(entity, pres_uri->s, pres_uri->len);
	entity[pres_uri->len] = '\0';
	xmlNewProp(root_node, BAD_CAST "entity", BAD_CAST entity);
	pkg_free(entity);

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

	xmlNewProp(tuple_node, BAD_CAST "id", BAD_CAST "tuple_mixingid");

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

	if(pres_note && strlen(pres_note))
	{
		node = xmlNewChild(root_node, NULL, BAD_CAST "note",
			BAD_CAST pres_note) ;
		if(node ==NULL)
		{
			LM_ERR("while adding child\n");
			goto error;
		}
		/* put also the person node - to get status indication */
		person_node = xmlNewChild(root_node, 0, BAD_CAST "dm:person", NULL) ;
		if(person_node == NULL)
		{
			LM_ERR("while adding child\n");
			goto error;
		}
		/* now put the id for tuple and person */
		xmlNewProp(person_node, BAD_CAST "id", BAD_CAST "pers_mixingid");

		node = xmlNewChild(person_node, 0, BAD_CAST "rpid:activities", NULL) ;
		if(node == NULL)
		{
			LM_ERR("Failed to add person activities node\n");
			goto error;
		}

		if(xmlNewChild(node, 0, BAD_CAST "rpid:on-the-phone", NULL) == NULL)
		{
			LM_ERR("Failed to add activities child\n");
			goto error;
		}

		if(xmlNewChild(person_node, 0, BAD_CAST "dm:note",
					BAD_CAST pres_note) == NULL)
		{
			LM_ERR("Failed to add activities child\n");
			goto error;
		}
	}

	dialog_body = (str*)pkg_malloc(sizeof(str));
	if(dialog_body == NULL)
	{
		LM_ERR("No more memory\n");
		goto error;
	}
	xmlDocDumpMemory(pres_doc,(xmlChar**)(void*)&dialog_body->s,
			&dialog_body->len);

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

error:
	if(pres_doc)
		xmlFreeDoc(pres_doc);
	xmlCleanupParser();
	xmlMemoryDump();

	return dialog_body;
}
Exemplo n.º 27
0
int bla_process_body(publ_info_t* publ, str** fin_body, int ver, str** tuple)
{
	xmlNodePtr node= NULL;
	xmlDocPtr doc= NULL;
	char* version;
	str* body= NULL;
	int len;
	str* init_body;

	init_body= publ->body;

	doc= xmlParseMemory(init_body->s, init_body->len );
	if(doc== NULL)
	{
		LM_ERR("while parsing xml memory\n");
		goto error;
	}
	/* change version and state*/
	node= xmlDocGetNodeByName(doc, "dialog-info", NULL);
	if(node == NULL)
	{
		LM_ERR("while extracting dialog-info node\n");
		goto error;
	}
	version= int2str(ver,&len);
	version[len]= '\0';

	if( xmlSetProp(node, (const xmlChar *)"version",(const xmlChar*)version)== NULL)
	{
		LM_ERR("while setting version attribute\n");
		goto error;	
	}
	body= (str*)pkg_malloc(sizeof(str));
	if(body== NULL)
	{
		LM_ERR("NO more memory left\n");
		goto error;
	}
	memset(body, 0, sizeof(str));
	xmlDocDumpFormatMemory(doc, (xmlChar**)(void*)&body->s, &body->len, 1);	

	xmlFreeDoc(doc);
	doc= NULL;
	*fin_body= body;	
	if(*fin_body== NULL)
		LM_DBG("NULL fin_body\n");

	xmlMemoryDump();
	xmlCleanupParser();
	LM_DBG("successful\n");
	return 1;

error:
	if(doc)
		xmlFreeDoc(doc);
	if(body)
		pkg_free(body);
	
	xmlMemoryDump();
	xmlCleanupParser();
	return -1;
}
Exemplo n.º 28
0
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);
}
Exemplo n.º 29
0
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 ;
}
Exemplo n.º 30
0
str* build_offline_presence(str* pres_uri)
{
	xmlDocPtr pres_doc = NULL;
	xmlNodePtr root_node, tuple_node, node;
	char* entity;
	str* body = NULL;

	pres_doc= xmlNewDoc(BAD_CAST "1.0");
	if(pres_doc== NULL)
	{
		LM_ERR("allocating new xml doc\n");
		goto error;
	}

	root_node = xmlNewNode(NULL, BAD_CAST "presence");
	if(root_node== NULL)
	{
		LM_ERR("Failed to create xml node\n");
		goto error;
	}
	xmlDocSetRootElement(pres_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");

	entity= (char*)pkg_malloc(pres_uri->len + 1);
	if(entity == NULL)
	{
		LM_ERR("No more memory\n");
		goto error;
	}
	memcpy(entity, pres_uri->s, pres_uri->len);
	entity[pres_uri->len] = '\0';
	xmlNewProp(root_node, BAD_CAST "entity", BAD_CAST entity);
	pkg_free(entity);

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

	xmlNewProp(tuple_node, BAD_CAST "id", BAD_CAST "tuple_mixingid");

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

	body = (str*)pkg_malloc(sizeof(str));
	if(body == NULL)
	{
		LM_ERR("No more memory\n");
		goto error;
	}
	xmlDocDumpMemory(pres_doc,(xmlChar**)(void*)&body->s,
			&body->len);

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

error:
	if(pres_doc)
		xmlFreeDoc(pres_doc);
	xmlCleanupParser();
	xmlMemoryDump();

	return body;
}