Beispiel #1
0
void timer_send_notify(unsigned int ticks,void *param)
{
	db_key_t query_cols[2], update_cols[1], result_cols[7];
	db_val_t query_vals[2], update_vals[1];
	int did_col, resource_uri_col, auth_state_col, reason_col,
		body_col, ctype_col;
	int n_result_cols= 0, i;
	db_res_t *result= NULL;
	char* prev_did= NULL, * curr_did= NULL;
	db_row_t *row;	
	db_val_t *row_vals;
	char* resource_uri;
	str body;
	str callid, to_tag, from_tag;
	xmlDocPtr rlmi_doc= NULL;
	xmlNodePtr list_node= NULL, instance_node= NULL, resource_node;
	unsigned int hash_code= 0;
	int len;
	int size= BUF_REALLOC_SIZE, buf_len= 0;
	char* buf= NULL, *auth_state= NULL;
	int contor= 0, auth_state_flag;
	str bstr= {0, 0};
	str rlmi_cont= {0, 0}, multi_cont;
	subs_t* s, *dialog= NULL;
	char* rl_uri= NULL;
	char* str_aux = NULL;
	str ctype, cid;
	int add_len;

	query_cols[0]= &str_updated_col;
	query_vals[0].type = DB_INT;
	query_vals[0].nul = 0;
	query_vals[0].val.int_val= UPDATED_TYPE; 

	result_cols[did_col= n_result_cols++]= &str_rlsubs_did_col;
	result_cols[resource_uri_col= n_result_cols++]= &str_resource_uri_col;
	result_cols[auth_state_col= n_result_cols++]= &str_auth_state_col;
	result_cols[ctype_col= n_result_cols++]= &str_content_type_col;
	result_cols[reason_col= n_result_cols++]= &str_reason_col;
	result_cols[body_col= n_result_cols++]= &str_presence_state_col;

	/* query in alfabetical order after rlsusbs_did 
	 * (resource list Subscribe dialog indentifier)*/

	if (rls_dbf.use_table(rls_db, &rlpres_table) < 0) 
	{
		LM_ERR("in use_table\n");
		goto done;
	}

	if(rls_dbf.query(rls_db, query_cols, 0, query_vals, result_cols,
					1, n_result_cols, &str_rlsubs_did_col, &result)< 0)
	{
		LM_ERR("in sql query\n");
		goto done;
	}
	if(result== NULL || result->n<= 0)
		goto done;

	/* update the rlpres table */
	update_cols[0]= &str_updated_col;
	update_vals[0].type = DB_INT;
	update_vals[0].nul = 0;
	update_vals[0].val.int_val= NO_UPDATE_TYPE; 

	if (rls_dbf.use_table(rls_db, &rlpres_table) < 0) 
	{
		LM_ERR("in use_table\n");
		goto error;
	}
	if(rls_dbf.update(rls_db, query_cols, 0, query_vals, update_cols,
					update_vals, 1, 1)< 0)
	{
		LM_ERR("in sql update\n");
		goto error;
	}

	/* generate the boundary string */

	bstr.s= generate_string((int)time(NULL), BOUNDARY_STRING_LEN);
	if(bstr.s == NULL)
	{
		LM_ERR("failed to generate random string\n");
		goto error;
	}
	bstr.len= strlen(bstr.s);

	/* for the multipart body , use here also an initial allocated
	 * and reallocated on need buffer */
	buf= pkg_malloc(size);
	if(buf== NULL)
	{
		ERR_MEM(PKG_MEM_STR);
	}

	LM_DBG("found %d records with updated state\n", result->n);
	for(i= 0; i< result->n; i++)
	{
		row = &result->rows[i];
		row_vals = ROW_VALUES(row);
		
		curr_did=     (char*)row_vals[did_col].val.string_val;
		resource_uri= (char*)row_vals[resource_uri_col].val.string_val;
		auth_state_flag=     row_vals[auth_state_col].val.int_val;
		body.s=   (char*)row_vals[body_col].val.string_val;
		body.len= strlen(body.s);
		ctype.s = (char*)row_vals[ctype_col].val.string_val;
		ctype.len = strlen(ctype.s);

		/* if all the info for one dialog have been collected -> send notify */
		/* the 'dialog' variable must be filled with the dialog info */
		/* 'buf' must contain the body */
		if(prev_did!= NULL && strcmp(prev_did, curr_did)) 
		{
			xmlDocDumpMemory(rlmi_doc,(xmlChar**)(void*)&rlmi_cont.s,
				&rlmi_cont.len);
		
			multi_cont.s= buf;
			multi_cont.len= buf_len;
			 
			if(agg_body_sendn_update(&dialog->pres_uri, bstr, &rlmi_cont, 
						 (buf_len==0)?NULL:&multi_cont, dialog, hash_code)<0)
			 {
				 LM_ERR("in function agg_body_sendn_update\n");
				 goto error;
			 }
			xmlFree(rlmi_cont.s);

			xmlFreeDoc(rlmi_doc);
			rlmi_doc= NULL;
			pkg_free(rl_uri);
			rl_uri= NULL;
			pkg_free(dialog);
			dialog= NULL;
		}

		/* for the new dialog -> search the dialog info and 
		 * fill the dialog structure and start a new rlmi document */
		if(prev_did== NULL || strcmp(prev_did, curr_did)) 
		{
			/* search the subscription in rlsubs_table*/
			if( parse_rlsubs_did(curr_did, &callid, &from_tag, &to_tag)< 0)
			{
				LM_ERR("bad format for "
					"resource list Subscribe dialog indentifier(rlsubs did)\n");
				prev_did = NULL;
				continue;

			}
			hash_code= core_hash(&callid, &to_tag, hash_size);
		
			lock_get(&rls_table[hash_code].lock);
			s= pres_search_shtable(rls_table,callid,to_tag,from_tag,hash_code);
			if(s== NULL)
			{
				LM_DBG("record not found in hash_table [rlsubs_did]= %s\n",
						curr_did);
				LM_DBG("callid= %.*s\tfrom_tag= %.*s\tto_tag= %.*s\n",
						callid.len, callid.s,from_tag.len,from_tag.s,
						to_tag.len,to_tag.s);
				lock_release(&rls_table[hash_code].lock);
				prev_did = NULL;
				continue;
			}
			LM_DBG("Found rl-subs record in hash table\n");
					
			/* save dialog info and rl_uri*/
			dialog= pres_copy_subs(s, PKG_MEM_TYPE);
			if(dialog== NULL)
			{	
				LM_ERR("while copying subs_t structure\n");
				lock_release(&rls_table[hash_code].lock);
				goto done;
			}
			dialog->expires-= (int)time(NULL);
			lock_release(&rls_table[hash_code].lock);

			/* make new rlmi and multipart documents */
			rlmi_doc= xmlNewDoc(BAD_CAST "1.0");
			if(rlmi_doc== NULL)
			{
				LM_ERR("when creating new xml doc\n");
				goto done;
			}
			list_node= xmlNewNode(NULL, BAD_CAST "list");
			if(list_node== NULL)
			{
				LM_ERR("while creating new xml node\n");
				goto done;
			}
			rl_uri= (char*)pkg_malloc((dialog->pres_uri.len+ 1)* sizeof(char));
			if(rl_uri==  NULL)
			{
				ERR_MEM(PKG_MEM_STR);
			}
			memcpy(rl_uri, dialog->pres_uri.s, dialog->pres_uri.len);
			rl_uri[dialog->pres_uri.len]= '\0';

			xmlNewProp(list_node, BAD_CAST "uri", BAD_CAST rl_uri);
			xmlNewProp(list_node, BAD_CAST "xmlns", BAD_CAST "urn:ietf:params:xml:ns:rlmi");
			xmlNewProp(list_node, BAD_CAST "version", BAD_CAST int2str(dialog->version, &len));
			xmlNewProp(list_node, BAD_CAST "fullState", BAD_CAST "false");

			xmlDocSetRootElement(rlmi_doc, list_node);
			buf_len= 0;

			/* !!!! for now I will include the auth state without checking if 
			 * it has changed - > in future chech if it works */		
		}		

		/* add a node in rlmi_doc and if any presence state registered add 
		 * it in the buffer */
		
		resource_node= xmlNewChild(list_node,NULL,BAD_CAST "resource", NULL);
		if(resource_node== NULL)
		{
			LM_ERR("when adding resource child\n");
			goto done;
		}
		xmlNewProp(resource_node, BAD_CAST "uri", BAD_CAST resource_uri);
			
		/* there might be more records with the same uri- more instances-
		 * search and add them all */
		
		contor= 0;
		while(1)
		{
			contor++;
			cid.s= NULL;
			instance_node= xmlNewChild(resource_node, NULL, 
					BAD_CAST "instance", NULL);
			if(instance_node== NULL)
			{
				LM_ERR("while adding instance child\n");
				goto error;
			}
			str_aux = generate_string(contor, 8);
			if(str_aux == NULL)
			{
				LM_ERR("failed to create random string\n");
				goto error;
			}
			xmlNewProp(instance_node, BAD_CAST "id",
					BAD_CAST str_aux);
			pkg_free(str_aux);

			auth_state= get_auth_string(auth_state_flag);
			if(auth_state== NULL)
			{
				LM_ERR("bad authorization status flag\n");
				goto error;
			}
			xmlNewProp(instance_node, BAD_CAST "state", BAD_CAST auth_state);
		
			if(auth_state_flag & ACTIVE_STATE)
			{
				cid.s= generate_cid(resource_uri, strlen(resource_uri));
				cid.len = strlen(cid.s);
				xmlNewProp(instance_node, BAD_CAST "cid", BAD_CAST cid.s);
			}
			else
			if(auth_state_flag & TERMINATED_STATE)
			{
				xmlNewProp(instance_node, BAD_CAST "reason",
					BAD_CAST row_vals[resource_uri_col].val.string_val);
			}
		
			/* add in the multipart buffer */
			if(cid.s)
			{
				APPEND_MULTIPART_BODY();
				pkg_free(cid.s);
				cid.s = NULL;
			}

			i++;
			if(i== result->n)
			{
				i--;
				break;
			}

			row = &result->rows[i];
			row_vals = ROW_VALUES(row);
	
			if(strncmp(row_vals[resource_uri_col].val.string_val,resource_uri,
					strlen(resource_uri)) || strncmp(curr_did, 
					row_vals[did_col].val.string_val, strlen(curr_did)))
			{
				i--;
				break;
			}
			resource_uri= (char*)row_vals[resource_uri_col].val.string_val;
			auth_state_flag=     row_vals[auth_state_col].val.int_val;
			body.s=   (char*)row_vals[body_col].val.string_val;
			body.len = strlen(body.s);
		}

		prev_did= curr_did;
	}

	if(rlmi_doc)
	{
		xmlDocDumpMemory( rlmi_doc,(xmlChar**)(void*)&rlmi_cont.s,
		&rlmi_cont.len);
		
		multi_cont.s= buf;
		multi_cont.len= buf_len;
	
		 if(agg_body_sendn_update(&dialog->pres_uri, bstr, &rlmi_cont, 
			 (buf_len==0)?NULL:&multi_cont, dialog, hash_code)<0)
		 {
			 LM_ERR("in function agg_body_sendn_update\n");
			 goto error;
		}
		xmlFree(rlmi_cont.s);
		pkg_free(rl_uri);
		rl_uri= NULL;
		pkg_free(dialog);
		dialog= NULL;
	}

error:
done:
	if(result)
		rls_dbf.free_result(rls_db, result);
	if(rlmi_doc)
		xmlFreeDoc(rlmi_doc);
	if(rl_uri)
		pkg_free(rl_uri);
	if(bstr.s)
		pkg_free(bstr.s);
		
	if(buf)
		pkg_free(buf);
	if(dialog)
		pkg_free(dialog);
	return;
}
Beispiel #2
0
/**
 * htmlSetMetaEncoding:
 * @param doc the document
 * @param encoding the encoding string
 *
 * Sets the current encoding in the Meta tags
 * NOTE: this will not change the document content encoding, just
 * the META flag associated.
 *
 * Returns 0 in case of success and -1 in case of error
 */
XMLPUBFUNEXPORT int
htmlSetMetaEncoding(htmlDocPtr doc, const xmlChar *encoding) {
    htmlNodePtr cur, meta;
    const xmlChar *content;
    char newcontent[100];
	LOAD_GS_SAFE_DOC(doc)

    if (doc == NULL)
        return(-1);

    if (encoding != NULL) {
        snprintf(newcontent, sizeof(newcontent), "text/html; charset=%s",
                encoding);
        newcontent[sizeof(newcontent) - 1] = 0;
    }

    cur = doc->children;

    /*
     * Search the html
     */
    while (cur != NULL) {
        if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) {
            if (xmlStrcasecmp(cur->name, BAD_CAST"html") == 0)
                break;
            if (xmlStrcasecmp(cur->name, BAD_CAST"head") == 0)
                goto found_head;
            if (xmlStrcasecmp(cur->name, BAD_CAST"meta") == 0)
                goto found_meta;
        }
        cur = cur->next;
    }
    if (cur == NULL)
        return(-1);
    cur = cur->children;

    /*
     * Search the head
     */
    while (cur != NULL) {
        if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) {
            if (xmlStrcasecmp(cur->name, BAD_CAST"head") == 0)
                break;
            if (xmlStrcasecmp(cur->name, BAD_CAST"meta") == 0)
                goto found_meta;
        }
        cur = cur->next;
    }
    if (cur == NULL)
        return(-1);
found_head:
    if (cur->children == NULL) {
        if (encoding == NULL)
            return(0);
        meta = xmlNewDocNode(doc, NULL, BAD_CAST"meta", NULL);
        xmlAddChild(cur, meta);
        xmlNewProp(meta, BAD_CAST"http-equiv", BAD_CAST"Content-Type");
        xmlNewProp(meta, BAD_CAST"content", BAD_CAST newcontent);
        if ( OOM_FLAG )     //oom set in xmlNewProp
            return(-1);
        return(0);
    }
    cur = cur->children;

found_meta:
    if (encoding != NULL) {
        /*
         * Create a new Meta element with the right attributes
         */

        meta = xmlNewDocNode(doc, NULL, BAD_CAST"meta", NULL);
        xmlAddPrevSibling(cur, meta);
        xmlNewProp(meta, BAD_CAST"http-equiv", BAD_CAST"Content-Type");
        xmlNewProp(meta, BAD_CAST"content", BAD_CAST newcontent);
    }

    /*
     * Search and destroy all the remaining the meta elements carrying
     * encoding informations
     */
    while (cur != NULL) {
        if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) {
            if (xmlStrcasecmp(cur->name, BAD_CAST"meta") == 0) {
                xmlAttrPtr attr = cur->properties;
                int http;
                const xmlChar *value;

                content = NULL;
                http = 0;
                while (attr != NULL) {
                    if ((attr->children != NULL) &&
                        (attr->children->type == XML_TEXT_NODE) &&
                        (attr->children->next == NULL)) {
                        value = attr->children->content;
                        if ((!xmlStrcasecmp(attr->name, BAD_CAST"http-equiv"))
                         && (!xmlStrcasecmp(value, BAD_CAST"Content-Type")))
                            http = 1;
                        else
                        {
                           if ((value != NULL) &&
                                (!xmlStrcasecmp(attr->name, BAD_CAST"content")))
                              content = value;
                        }
                        if ((http != 0) && (content != NULL))
                            break;
                    }
                    attr = attr->next;
                }
                if ((http != 0) && (content != NULL)) {
                    meta = cur;
                    cur = cur->next;
                    xmlUnlinkNode(meta);
                    xmlFreeNode(meta);
                    continue;
                }

            }
        }
        cur = cur->next;
    }
    return(0);
}
Beispiel #3
0
/* A simple example how to create DOM. Libxml2 automagically 
 * allocates the necessary amount of memory to it.
 */
int
main(int argc, char **argv)
{
  xmlDocPtr doc = NULL;       /* document pointer */
  xmlNodePtr feed_node = NULL, node = NULL, node1 = NULL;/* node pointers */

  char buff[256];
  int i, j;

  LIBXML_TEST_VERSION;

  /* 
   * Creates a new document, a node and set it as a feed node
   */
  doc = xmlNewDoc(BAD_CAST "1.0");
  feed_node = xmlNewNode(NULL, BAD_CAST "feed");
  xmlDocSetRootElement(doc, feed_node);
  xmlNewProp(feed_node, BAD_CAST "xmlns", BAD_CAST "http://www.w3.org/2005/Atom");
  xmlNewProp(feed_node, BAD_CAST "xmlns:batch", BAD_CAST "http://schemas.google.com/gdata/batch");
  xmlNewProp(feed_node, BAD_CAST 
        "xmlns:gs", BAD_CAST "http://schemas.google.com/spreadsheets/2006");



  /* 
   * xmlNewChild() creates a new node, which is "attached" as child node
   * of feed_node node. 
   */
  xmlNewChild(feed_node, NULL, BAD_CAST "node1",
	      BAD_CAST "content of node 1");
  /* 
   * The same as above, but the new child node doesn't have a content 
   */
  xmlNewChild(feed_node, NULL, BAD_CAST "node2", NULL);

  /* 
   * xmlNewProp() creates attributes, which is "attached" to an node.
   * It returns xmlAttrPtr, which isn't used here.
   */
    node =
      xmlNewChild(feed_node, NULL, BAD_CAST "node3",
		  BAD_CAST "this node has attributes");
    xmlNewProp(node, BAD_CAST "attribute", 
         BAD_CAST "=GoogleFinance(\"AAPL\", \"close\", \"1/1/2003\", \"1/31/2008\", \"1\")");
    xmlNewProp(node, BAD_CAST "foo", BAD_CAST "bar");

    /*
     * Here goes another way to create nodes. xmlNewNode() and xmlNewText
     * creates a node and a text node separately. They are "attached"
     * by xmlAddChild() 
     */
    node = xmlNewNode(NULL, BAD_CAST "node4");
    node1 = xmlNewText(BAD_CAST
		       "other way to create content (which is also a node)");
    xmlAddChild(node, node1);
    xmlAddChild(feed_node, node);

    /* 
     * A simple loop that "automates" nodes creation 
     */
    for (i = 5; i < 7; i++) {
      sprintf(buff, "node%d", i);
      node = xmlNewChild(feed_node, NULL, BAD_CAST buff, NULL);
      for (j = 1; j < 4; j++) {
	sprintf(buff, "node%d%d", i, j);
	node1 = xmlNewChild(node, NULL, BAD_CAST buff, NULL);
	xmlNewProp(node1, BAD_CAST "odd", BAD_CAST((j % 2) ? "no" : "yes"));
      }
    }

    /* 
     * Dumping document to stdio or file
     */
    xmlSaveFormatFileEnc(argc > 1 ? argv[1] : "-", doc, "UTF-8", 1);

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

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

    /*
     * this is to debug memory for regression tests
     */
    /*  xmlMemoryDump(); */
    return(0);
}
Beispiel #4
0
void SC_ASIYA::save_xml(string report_xml, string TGT, string REF, string METRIC, const MetricScore &m) {
    vector<vector<string> > idx = TESTBED::IDX[TGT];

    /*    cout << "-----------------idx-------------------" << endl;
        for (int i = 0; i < idx.size(); ++i) {
                //cout << "\tidx[" << i << "]" << endl;
                for(int j = 0; j < idx[i].size(); ++j) {
                        cout << "\t\tidx[" << i << "][" << j << "]: " << idx[i][j] << endl;
                }
                cout << endl;
        }
        cout << "---------------------------------------" << endl;

        for(int i = 0; i < doc_scores.size(); ++i) cout << "doc_scores[" << i  << "]: " << doc_scores[i] << endl;
        for(int i = 0; i < seg_scores.size(); ++i) cout << "seg_scores[" << i  << "]: " << seg_scores[i] << endl;*/



    int i = 1;
    int n_docs, n_doc_segs;
    n_docs = n_doc_segs = 0;

    string DOC = "-1";
    string document_id = "";

    // -> STORE IQREPORT
    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
    xmlNodePtr root_node = xmlNewNode(NULL, BAD_CAST "REPORT");
    xmlDocSetRootElement(doc, root_node);

    string app_name = Common::appNAME;
    boost::to_lower(app_name);
    string doc_type = app_name + ".dtd []"; //"!DOCTYPE " + SC_ASIYA::ROOT_ELEMENT + " \"" + app_name +".dtd\" []";
    xmlDtdPtr dtd = xmlCreateIntSubset(doc, BAD_CAST SC_FORMAT::ROOT_ELEMENT.c_str(), NULL, BAD_CAST doc_type.c_str());

/*
    xmlNewProp(root_node, BAD_CAST "hyp",       BAD_CAST    TGT.c_str());
    xmlNewProp(root_node, BAD_CAST "metric",    BAD_CAST    METRIC.c_str());

    char buffer[50];
    sprintf(buffer, "%d", n_docs);
    xmlNewProp(root_node, BAD_CAST "n_docs",    (const xmlChar *) buffer);

    sprintf(buffer, "%d", seg_scores.size());
    xmlNewProp(root_node, BAD_CAST "n_segments",(const xmlChar *) buffer);
    xmlNewProp(root_node, BAD_CAST "ref",       BAD_CAST    REF.c_str());

    //double x = Common::trunk_and_trim_number(sys_score, SC_ASIYA::FLOAT_LENGTH, SC_ASIYA::FLOAT_PRECISION);
    double x = sys_score;
    sprintf(buffer, "%f", x);
    xmlNewProp(root_node, BAD_CAST "score",     (const xmlChar *) buffer);
*/

    //double x;
    char buffer[256];
    xmlNodePtr doc_node = xmlNewChild(root_node, NULL, BAD_CAST "DOC", NULL);

    while (i < idx.size()) {
        if (idx[i][0] != document_id) { // NEW DOCUMENT

            if (DOC != "-1") {
                //x = Common::trunk_and_trim_number(doc_scores[n_docs - 1], SC_ASIYA::FLOAT_LENGTH, SC_ASIYA::FLOAT_PRECISION);
                //x = m.doc_scores[n_docs-1];
                xmlNewProp(doc_node, BAD_CAST "id",         BAD_CAST document_id.c_str());

                sprintf(buffer, "%d", n_docs);
                xmlNewProp(doc_node, BAD_CAST "n",          (const xmlChar *) buffer);

                sprintf(buffer, "%d", n_doc_segs);
                xmlNewProp(doc_node, BAD_CAST "n_segments", (const xmlChar *) buffer);

                //sprintf(buffer, "%.%df", x);
                //trunk_and_trim_number(m.doc_scores[n_docs-1]);
                xmlNewProp(doc_node, BAD_CAST "score",      (const xmlChar *) trunk_and_trim_number(m.doc_scores[n_docs-1]).c_str());

                doc_node = xmlNewChild(root_node, NULL, BAD_CAST "DOC", NULL);
            }
            DOC = document_id = idx[i][0];
            n_docs++;
            n_doc_segs = 0;
        }

        // CREATE A SEGMENT
        //x = Common::trunk_and_trim_number(seg_scores[i - 1], SC_ASIYA::FLOAT_LENGTH, SC_ASIYA::FLOAT_PRECISION);
        //x = m.seg_scores[i-1];
        //sprintf(buffer, "%f", x);
        xmlNodePtr seg_node = xmlNewChild(doc_node, NULL, BAD_CAST "S", (const xmlChar *) trunk_and_trim_number(m.seg_scores[i-1]).c_str());
        sprintf(buffer, "%d", i);
        xmlNewProp(seg_node, BAD_CAST "n", (const xmlChar *) buffer);
        n_doc_segs++;
        i++;
    }

    // PASTE LAST DOC (if any)
    if (DOC != "-1") {
        //x = Common::trunk_and_trim_number(doc_scores[n_docs - 1], SC_ASIYA::FLOAT_LENGTH, SC_ASIYA::FLOAT_PRECISION);
        //x = m.doc_scores[n_docs-1];
        //doc_node = xmlNewChild(root_node, NULL, BAD_CAST "DOC", NULL);
        xmlNewProp(doc_node, BAD_CAST "id",         BAD_CAST document_id.c_str());

        sprintf(buffer, "%d", n_docs);
        xmlNewProp(doc_node, BAD_CAST "n",          (const xmlChar *) buffer);

        sprintf(buffer, "%d", n_doc_segs);
        xmlNewProp(doc_node, BAD_CAST "n_segments", (const xmlChar *) buffer);

        //sprintf(buffer, "%f", x);
        xmlNewProp(doc_node, BAD_CAST "score",      (const xmlChar *) trunk_and_trim_number(m.doc_scores[n_docs-1]).c_str());
    }

    xmlNewProp(root_node, BAD_CAST "hyp",       BAD_CAST    TGT.c_str());
    xmlNewProp(root_node, BAD_CAST "metric",    BAD_CAST    METRIC.c_str());

    //char buffer[50];
    sprintf(buffer, "%d", n_docs);
    xmlNewProp(root_node, BAD_CAST "n_docs",    (const xmlChar *) buffer);

    sprintf(buffer, "%d", (int)m.seg_scores.size());
    xmlNewProp(root_node, BAD_CAST "n_segments",(const xmlChar *) buffer);
    xmlNewProp(root_node, BAD_CAST "ref",       BAD_CAST    REF.c_str());

    //double x = Common::trunk_and_trim_number(sys_score, SC_ASIYA::FLOAT_LENGTH, SC_ASIYA::FLOAT_PRECISION);
    //x = m.sys_score;
    //sprintf(buffer, "%f", x);
    xmlNewProp(root_node, BAD_CAST "score",     (const xmlChar *) trunk_and_trim_number(m.sys_score).c_str());

    xmlSaveFormatFileEnc(report_xml.c_str(), doc, "UTF-8", 1);
    xmlFreeDoc(doc);
    xmlCleanupParser();
}
Beispiel #5
0
str* build_pidf(ucontact_t* c)
{
	xmlDocPtr  doc = NULL; 
	xmlNodePtr root_node = NULL;
	xmlNodePtr tuple_node = NULL;
	xmlNodePtr status_node = NULL;
	xmlNodePtr basic_node = NULL;
	str *body= NULL;
	str pres_uri= {NULL, 0};
	char buf[265];
	char* at= NULL;

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

	pres_uri.s = buf;
	if(pres_prefix.s)
	{
		memcpy(pres_uri.s, pres_prefix.s, pres_prefix.len);
		pres_uri.len+= pres_prefix.len;
		memcpy(pres_uri.s+ pres_uri.len, ":", 1);
		pres_uri.len+= 1;
	}	
	memcpy(pres_uri.s+ pres_uri.len, c->aor->s, c->aor->len);
	pres_uri.len+= c->aor->len;

	at = memchr(c->aor->s, '@', c->aor->len);
	if(!at)
	{
		pres_uri.s[pres_uri.len++]= '@';
		memcpy(pres_uri.s+ pres_uri.len, default_domain.s, default_domain.len);
		pres_uri.len+= default_domain.len;		
	}
	pres_uri.s[pres_uri.len]= '\0';

	if(pres_uri.len> 256)
		return NULL;
	/* create the Publish body  */
	doc = xmlNewDoc(BAD_CAST "1.0");
	if(doc==0)
		return NULL;

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

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

	tuple_node =xmlNewChild(root_node, NULL, BAD_CAST "tuple", NULL) ;
	if( tuple_node ==NULL)
	{
		LM_ERR("while adding child\n");
		goto error;
	}
	
	status_node = xmlNewChild(tuple_node, NULL, BAD_CAST "status", NULL) ;
	if( status_node ==NULL)
	{
		LM_ERR("while adding child\n");
		goto error;
	}
	
	basic_node = xmlNewChild(status_node, NULL, BAD_CAST "basic",
		BAD_CAST "open") ;
	
	if( basic_node ==NULL)
	{
		LM_ERR("while adding child\n");
		goto error;
	}
	
	body = (str*)pkg_malloc(sizeof(str));
	if(body == NULL)
	{
		LM_ERR("while allocating memory\n");
		return NULL;
	}
	memset(body, 0, sizeof(str));

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

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

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

	return body;

error:
	if(body)
	{
		if(body->s)
			xmlFree(body->s);
		pkg_free(body);
	}
	if(doc)
		xmlFreeDoc(doc);
	return NULL;
}	
Beispiel #6
0
void GoFormModbusConfig(webs_t wp, char_t *path, char_t *query)
{
//	int shmid;
//	char *shmptr;
       char *devName, *seriaName;

	char *saveBtn;
	char *getBtn;


	char *nid;
	char *nname;
	char *ntime, *nbaud, *nparity, *ndata, *nstop, *ninfo;
 	printf("HELLO!\n");
	xmlDocPtr pdoc = NULL;
	xmlNodePtr proot = NULL, pcur = NULL;
	xmlChar *xmlId, *xmlName, *xmlBaud,*xmlParity, *xmlStop, *xmlData, *xmlTimeout, *xmlInfo;

        devName = websGetVar(wp,T("name"),"");
        seriaName = websGetVar(wp,T("serialName"),""); 
        printf("%s \n",strcpy(modArg.id,devName));
        printf("seria is %s \n",strcpy(modArg.name,seriaName)); 
        getBtn = websGetVar(wp,T("getBtn"),T(""));
	saveBtn = websGetVar(wp,T("saveBtn"),T(""));
        printf("ready button \n");
        if(strlen(getBtn)!=0)
	{

	    pdoc = xmlReadFile("modbus.xml","UTF-8",XML_PARSE_RECOVER);
	    
	    proot = xmlDocGetRootElement(pdoc);
            printf("get the proot !!!\n");
	    pcur = proot->xmlChildrenNode;
	    while(pcur!=NULL)
	    {
	 	if(!xmlStrcmp(pcur->name, (const xmlChar*)"dev")){
	  		xmlId = xmlGetProp(pcur,(const xmlChar*)"ID");
			xmlName = xmlGetProp(pcur,(const xmlChar*)"Sname"); 
                        printf("the devNa is %s\n",devName); 
			if(!strcmp(xmlId,devName) && !strcmp(xmlName,seriaName))
			{
              		     xmlBaud = xmlGetProp(pcur,(const xmlChar*)"baud");
 		             xmlTimeout = xmlGetProp(pcur,(const xmlChar*)"timeout");
                             xmlParity = xmlGetProp(pcur,(const xmlChar*)"parity");
                             xmlStop = xmlGetProp(pcur,(const xmlChar*)"stop");
		       	     xmlData = xmlGetProp(pcur,(const xmlChar*)"data");
                             xmlInfo = xmlGetProp(pcur,(const xmlChar*)"info"); 



			     printf("get the id is : %s\n",strcpy(modArg.id,xmlId));
                             printf("get the serianame is : %s\n",strcpy(modArg.name,xmlName));
                             printf("get the baud is :!!%s\n",strcpy(modArg.baud,xmlBaud));
			     printf("get the parity is : %s\n",strcpy(modArg.parity,xmlParity));
			     printf("get the data is :!!%s\n",strcpy(modArg.data_bit,xmlData));	 	
			     printf("get the stop_bit is : %s\n",strcpy(modArg.stop_bit,xmlStop));
                             printf("get the timeout is : %s\n",strcpy(modArg.time_out,xmlTimeout));
                             printf("get the information is :!!%s\n",strcpy(modArg.info,xmlInfo));


                             xmlFree(xmlId);
			     xmlFree(xmlName);
                             xmlFree(xmlBaud);
			     xmlFree(xmlTimeout);    
                             xmlFree(xmlParity);
			     xmlFree(xmlStop); 
                             xmlFree(xmlData);
                             xmlFree(xmlInfo); 
                             break;
			} 		
		}
		pcur = pcur->next;
	    }
	
        	xmlFreeDoc(pdoc);
        }else if(strlen(saveBtn)!=0){
	    printf("enter the save area!!!\n");


            pdoc = xmlReadFile("modbus.xml","UTF-8",XML_PARSE_RECOVER);
            proot = xmlDocGetRootElement(pdoc);
            pcur = proot->xmlChildrenNode;
            printf("the pcur is %s\n",pcur->name); 
       	    while(pcur!=NULL)
            {
                 printf("the pcur in while is%s\n",pcur->name); 
                 xmlId = xmlGetProp(pcur,(const xmlChar*)"ID");
	         if(!xmlStrcmp(xmlId, (const xmlChar*)devName))
	         {			

                         
         	                     printf("the dev is %s\n",devName); 
  		                   
                                     nid = websGetVar(wp,T("name"),T(""));		 
                                     nname = websGetVar(wp,T("serialName"),T("")); 
				     nbaud = websGetVar(wp,T("opSelect1"),T(""));
                                     nparity = websGetVar(wp,T("opSelect2"),T(""));
                                     ndata = websGetVar(wp,T("opSelect3"),T(""));
                                     nstop = websGetVar(wp,T("opSelect4"),T(""));
                                     ntime = websGetVar(wp,T("time"),T(""));
                                     ninfo = websGetVar(wp,T("info"),T(""));
                                      




                                     xmlSetProp(pcur,(const xmlChar*)"ID",(const xmlChar*)nid);
				     xmlSetProp(pcur,(const xmlChar*)"Sname",(const xmlChar*)nname);
	 	
                                     xmlSetProp(pcur,(const xmlChar*)"baud",(const xmlChar*)nbaud);
                                     xmlSetProp(pcur,(const xmlChar*)"parity",(const xmlChar*)nparity);
                                     xmlSetProp(pcur,(const xmlChar*)"data",(const xmlChar*)ndata);
                                     xmlSetProp(pcur,(const xmlChar*)"stop",(const xmlChar*)nstop); 
                                     xmlSetProp(pcur,(const xmlChar*)"timeout",(const xmlChar*)ntime);
                                     xmlSetProp(pcur,(const xmlChar*)"info",(const xmlChar*)ninfo); 
                                     
				     

				     xmlBaud = xmlGetProp(pcur,(const xmlChar*)"baud");
				     xmlParity = xmlGetProp(pcur,(const xmlChar*)"parity"); 
				     xmlTimeout = xmlGetProp(pcur,(const xmlChar*)"timeout"); 
				     xmlStop = xmlGetProp(pcur,(const xmlChar*)"stop");
                                     xmlData = xmlGetProp(pcur,(const xmlChar*)"data");
      

                                     xmlInfo = xmlGetProp(pcur,(const xmlChar*)"info");  
       

                                     printf("sur info ssss %s\n",strcpy(modArg.info,xmlInfo));
                                     printf("sur baud ssss %s\n",strcpy(modArg.baud,(const char*)xmlBaud));
				     printf("show parity %s\n",strcpy(modArg.parity,xmlParity));
                                     printf("save the timeout After is %s\n",strcpy(modArg.time_out,(const char*)xmlTimeout));
 				     printf("show the stop_bit is %s\n",strcpy(modArg.stop_bit,xmlStop)); 

                                     printf("data_bit is %s\n",strcpy(modArg.data_bit,xmlData));
                                        


			             xmlSaveFormatFileEnc("modbus.xml",pdoc,"UTF-8",1); 
                                
				     
                                     xmlFree(xmlBaud);
                                     xmlFree(xmlParity);
                                     xmlFree(xmlStop);
				     xmlFree(xmlTimeout);
                                     xmlFree(xmlData);
                                     xmlFree(xmlInfo);
                         
                                      break;
                 }
		 pcur = pcur->next;
  		if(pcur==NULL)
		{
			printf("make a new dev\n");
			pcur = xmlNewNode(NULL,(const xmlChar*)"dev");
			xmlAddChild(proot,pcur);
			xmlNewProp(pcur,(const xmlChar*)"ID",(const xmlChar*)devName);
			xmlNewProp(pcur,(const xmlChar*)"Sname",(const xmlChar*)seriaName);
			xmlNewProp(pcur,(const xmlChar*)"baud",(const xmlChar*)"NULL");
			xmlNewProp(pcur,(const xmlChar*)"parity",(const xmlChar*)"NULL");
			xmlNewProp(pcur,(const xmlChar*)"data",(const xmlChar*)"NULL");
			xmlNewProp(pcur,(const xmlChar*)"stop",(const xmlChar*)"NULL");
			xmlNewProp(pcur,(const xmlChar*)"timeout",(const xmlChar*)"NULL");
			xmlNewProp(pcur,(const xmlChar*)"info",(const xmlChar*)"NULL");
			printf("successful new!%s\n",pcur->name);	
		}
	   }
     

           xmlFreeDoc(pdoc); 

	} 
/*
	if((shmid = shmget(MYKEY,BUF_SIZE,IPC_CREAT)) ==-1)     
        {     
           printf("shmget error!\n");     
           exit(1);     
        }

        if((shmptr = shmat(shmid,0,0)) == (void *)-1)     
        {     
 	   printf("shmat error!\n");     
           exit(1);     
        }     
        
	   printf("string:%s\n",shmptr);
	   sleep(3);

        fp = fopen("modbus.txt","w");
        
        fprintf(fp, "%s\n",shmptr);

        fclose(fp);
*/
        websRedirect(wp,T("modbus.asp")); 
	return ;	
}
Beispiel #7
0
int
main ( int argc, char *argv[] )
{
//定义文档和节点指针
    //xmlDocPtr doc = xmlNewDoc(BAD_CAST"1.0");
    xmlDocPtr doc = xmlNewDoc(NULL);
    doc->standalone=-2;
    xmlNodePtr root_node = xmlNewNode(NULL,BAD_CAST"root");
    //设置根节点
    xmlDocSetRootElement(doc,root_node);
// cur = xmlDocGetRootElement(doc); //获取文档根结点
    //在根节点中直接创建节点
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode1", BAD_CAST "newNode1 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode2", BAD_CAST "newNode2 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode3", BAD_CAST "newNode3 content");
    /*
    xmlChar *key;
    key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1); //获取文本结点的文本,需用其子结点
    xmlFree(key);
    */

    //创建一个绑定在根节点的子节点
    xmlNewChild(root_node, NULL, BAD_CAST "node1",BAD_CAST "content of node1");
    /*
    xmlNodeSetContent(curNode, (xmlChar *) "content changed");//设置结点的文本内容
    //得到一个节点的内容:
    //xmlChar *value = xmlNodeGetContent(node);
    //返回值value应该使用xmlFree(value)释放内存

    xmlUnlinkNode(curNode); //将当前结点从文档中断链(unlink),这样本文档就不会再包含这个子结点
    xmlFreeNode(curNode); //手动删除断链结点的内存, 若没有xmlDelNode或者xmlRemoveNode,使用此函数

    xmlChar *uri;
    uri = xmlGetProp(cur, "uri"); //获取属性值
    xmlFree(uri); //释放内存

    xmlSetProp(curNode,BAD_(xmlChar *)"attribute", (xmlChar *) "no"); //设置当前结点的attribute属性的属性值为no
    */
    //创建一个节点,设置其内容和属性,然后加入根结点
    xmlNodePtr node = xmlNewNode(NULL,BAD_CAST"node2");
    xmlNodePtr content = xmlNewText(BAD_CAST"NODE CONTENT");
    xmlAddChild(root_node,node);
    xmlAddChild(node,content);
    xmlNewProp(node,BAD_CAST"attribute",BAD_CAST "yes");
    //通过xmlNewProp()增加一个节点的属性
    node=xmlNewChild(root_node, NULL, BAD_CAST "node3", BAD_CAST"node has attributes");
    xmlNewProp(node, BAD_CAST "attribute", BAD_CAST "no");
    //创建一个儿子和孙子节点
    node = xmlNewNode(NULL, BAD_CAST "son");
    xmlAddChild(root_node,node);
    xmlNodePtr grandson = xmlNewNode(NULL, BAD_CAST "grandson");
    xmlAddChild(node,grandson);
    xmlAddChild(grandson, xmlNewText(BAD_CAST "This is a grandson node"));
    //存储xml文档
    int nRel = xmlSaveFile("CreatedXml.xml",doc);
    if (nRel != -1)
    {
       printf("%s\n",d_ConvertCharset("GBK", "utf-8", "一个xml文档被创建\n"));
    }

    //保存文件
    /*
     * xmlSaveFormatFile (docname, doc, 1); 保存文件到磁盘,第一个参数是写入文件的名,第二个参数是一个xmlDoc结构指针,第三个参数设定为1,保证在输出上写入缩进。
     */
    xmlSaveFormatFileEnc(argc > 1 ? argv[1] : "-", doc, "UTF-8", 1);
//    doc = xmlRecoverMemory(tmpxml,strlen(tmpxml));
//    xmlDocDumpMemoryEnc(doc, &buf, &len, "utf-8"); 

//    test_html();

    //释放文档内节点动态申请的内存
    xmlFreeDoc(doc);
    /*free the document */
    xmlCleanupParser();
    xmlMemoryDump();//debug memory for regression tests

    /*
     * 加载配置文件
     */
    pthread_attr_t attr;
    if(pthread_attr_init(&attr))
    {
        printf("err\n");
        return -1;
    }
    if(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
    {
        printf("err\n");
        return -1;
    }
    if( pthread_create( &xmlcfg_tid, &attr, (void *(*)(void *))thread_checkconf, 0 ))
        printf("create err\n");
    pthread_attr_destroy(&attr);

    pthread_mutex_lock(&mtx);
    while(!xmlid)
        pthread_cond_wait(&cond,&mtx);
    pthread_mutex_unlock(&mtx);
    /* 注意:xmlReadFile可以控制option */
    printf("aaaa\n");
    //doc = xmlParseFile("beps.xml");
    doc = xmlReadFile("beps.xml","UTF-8", 1); //解析文件

    printf("aaaaaaaa\n");
    //int fd=open("log", O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP );
    //ctxt = xmlSaveToFd(1, "UTF-8", -2);
    xmlSaveCtxtPtr ctxt = xmlSaveToFd(1, NULL, 1|-2);
    root_node=xmlDocGetRootElement( doc );
    //xmlSaveTree(ctxt, root_node);
    doc->encoding=NULL;
    xmlSaveDoc(ctxt, doc);
    xmlSaveClose(ctxt);
    xmlSaveFormatFileEnc( "-", doc, "UTF-8", 1);
    printf("aaaaaaaa\n");
    //doc = xmlReadFile("beps.xsd","UTF8",XML_PARSE_RECOVER); //解析文件
    //检查解析文件是否成功,如果不成功,libxml将指一个注册的错误并停止。
    //一个常见错误是不适当的编码。XML标准文件除了用UTF-8或UTF-16外还可用其他编码保存。
    //如果文件是这样,libxml将自动地为你转换到UTF-8。更多关于XML编码信息包含在XML标准中.
    if (NULL == doc)
    {  
       fprintf(stderr,"Document not parsed successfully.%d\n", __LINE__);
       return -1; 
    } 
//    printf("xmlDoc name=%s\n",doc->name);
//    printf("type=%d\n", doc->type);
////    printf("oldNs.href=%s\n",doc->oldNs->href);
////    printf("oldNs.prefix=%s\n",doc->oldNs->prefix);
//    printf("URL=%s\n",doc->URL);
//    printf("children.type=%u\n",doc->children->type);
//    printf("children.name=%s\n",doc->children->name);
//    printf("children.content=%s\n",doc->children->content);
//    if (doc->children->next)
//    {
//        printf("children.next.type=%u\n",doc->children->next->type);
//        printf("children.next.name=%s\n",doc->children->next->name);
//    }
//    //printf("children.next.content=%s\n",doc->children->next->content);
//    //printf("children.last.type=%u\n",doc->children->last->type);
//    //printf("children.last.name=%s\n",doc->children->last->name);
//    //printf("children.last.content=%s\n",doc->children->last->content);
//    root_node=xmlDocGetRootElement( doc );
//
//    printf("root.type=%u\n",      root_node->type);
//    printf("root.name=%s\n",      root_node->name);
//    printf("root.content=%s\n",   root_node->content);
//    if( root_node->next )
//    {
//        printf("root.next.type=%u\n", root_node->next->type);
//        printf("root.next.name=%s\n", root_node->next->name);
//    }
//
//    if( root_node->properties )
//    {
//        printf("root.prop.type=%u\n",   root_node->properties->type);
//        printf("root.prop.name=%s\n",   root_node->properties->name);
//        if (root_node->properties->ns)
//        {
//        printf("root.prop.ns.type=%u\n",   root_node->properties->ns->type);
//        printf("root.prop.ns.href=%s\n",   root_node->properties->ns->href);
//        printf("root.prop.ns.prefix=%s\n", root_node->properties->ns->prefix);
//        printf("root.prop.ns.next.type=%u\n",   root_node->properties->ns->next->type);
//        printf("root.prop.ns.next.href=%s\n",   root_node->properties->ns->next->href);
//        printf("root.prop.ns.next.prefix=%s\n", root_node->properties->ns->next->prefix);
//        }
//    }
//
//    if (root_node->ns)
//    {
//    printf("root.ns.type=%u\n",   root_node->ns->type);
//    printf("root.ns.href=%s\n",   root_node->ns->href);
//    printf("root.ns.prefix=%s\n", root_node->ns->prefix);
//    if (root_node->ns->next)
//    {
//    printf("root.ns.next.type=%u\n",   root_node->ns->next->type);
//    printf("root.ns.next.href=%s\n",   root_node->ns->next->href);
//    printf("root.ns.next.prefix=%s\n", root_node->ns->next->prefix);
//    }
//    }

    /*
     --------------------------------------------------------------------------------------------------
     XPATH查询函数
     --------------------------------------------------------------------------------------------------
     l  xmlXPathContextPtr context; //XPATH上下文指针
     l  context = xmlXPathNewContext(doc); //获取context指针
     l  xmlXPathObjectPtr result;// XPATH对象指针,用来存储查询结果
     l  result = xmlXPathEvalExpression(xmlChar *xpath, context); //根据条件xpath以及context来进行查询,条件格式:xmlChar *szXpath =(xmlChar *) ("/root/node2[@attribute='yes']");
     l  xmlXPathFreeContext(context); //释放context内存
     l  if(xmlXPathNodeSetIsEmpty(result->nodesetval)) //判断查询后的结果是否为空
     l  xmlNodeSetPtr nodeset; //创建结点集指针
     l  nodeset = result->nodesetval; //这个结点集对象包含在集合中的元素数目(nodeNr)及一个结点数组(nodeTab)。
     l  for (i=0; i < nodeset->nodeNr; i++) //遍历结果结点集合
     l  keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1)
     l  xmlXPathFreeObject (result); //释放内存
     l  xmlCleanupParser();//清除由libxml2申请的内存
     --------------------------------------------------------------------------------------------------
     */

//    xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
//    int status = xmlXPathRegisterNs(xpathCtx,(const xmlChar *)"xs",
//      (const xmlChar *)"http://www.w3.org/2001/XMLSchema-instance");
//    status = xmlXPathRegisterNs(xpathCtx,(const xmlChar *)"ns",
//      (const xmlChar *)"urn:cnaps:std:beps:2010:tech:xsd:beps.121.001.01");
    xmlXPathObjectPtr result;
    //result=getNodeSet(doc, BAD_CAST"//node2[@attribute='yes']");
    //result=getNodeSet(doc, BAD_CAST"/root/*");
    //result=getNodeSet(doc, BAD_CAST"//newNode1");
    //result=getNodeSet(doc, "/Document/name[@id='1']/xcz");
//    result=getNodeSet(doc, "//element[@name='MsgId']");
    //result=xmlXPathEvalExpression("//xs:element[@name='MsgId']", xpathCtx);
    //result=xmlXPathEvalExpression(BAD_CAST"//ns:xcz[position()=2]", xpathCtx);
    //result=xmlXPathEvalExpression(BAD_CAST"/ns:Document/ns:name[@id='1']/ns:xcz", xpathCtx);
    //xmlXPathFreeContext(xpathCtx); //释放context内存
//    if(xmlXPathNodeSetIsEmpty(result->nodesetval)) //判断查询后的结果是否为空
//    {
//        xmlXPathFreeObject(result);
//        printf("nodeset is empty\n");
//        return 1;
//    }

    /*
    doc = xmlParseFile( FileName);
    xpathCtx = xmlXPathNewContext( doc);
    status = xmlXPathRegisterNs( xpathCtx,( const xmlChar *)"abc",
                      ( const xmlChar *)"http://www.abc.org");
                      */
//    printf("type=%d boolval=%d floatval=%lf stringval=%s\n", result->type, result->boolval, 
//                result->floatval, result->stringval);
//      xmlNodePtr nodet;
//      int n;
//      printf("nodeNr=%d nodeMax=%d\n", result->nodesetval->nodeNr, result->nodesetval->nodeMax );
//      n=result->nodesetval->nodeNr;
      int i;
//      nodet=*result->nodesetval->nodeTab;
//    while( n-- )
//    {
//        printf("type=[%d]\n", nodet->type);
//        printf("name=[%s]\n", nodet->name);
//        //printf("content=[%s]\n", nodet->content);
//        //printf("ns.href=[%s]ns.prefix=[%s]\n", nodet->ns->href, nodet->ns->prefix );
//        printf("attr.name=[%s]\n", nodet->properties->name);
//        printf("attr.children.content=[%s]\n", nodet->properties->children->content);
//        //printf("attr._private=[%s]\n", nodet->properties->_private);
//        //printf("children.content=[%s]\n", nodet->children->content);
//        nodet=*(result->nodesetval->nodeTab+i++);
//    }

//    xmlNodePtr cur;
//    xmlChar *value;
//    for (i=0; i < result->nodesetval->nodeNr; i++)
//    {
//        cur = result->nodesetval->nodeTab[i];
//       // cur = cur->xmlChildrenNode; 
//        if(cur!=NULL)
//        {  
//            value = xmlGetProp(cur,(const xmlChar *)"name");
//            if (value&&value[0])
//            {
//                printf("value: %s\n\n", d_ConvertCharset("utf-8", "GBK", (char *)value));
//                xmlFree(value);
//            }
//            value = xmlNodeGetContent(cur);
//            if (value&&value[0])
//            {
//                printf("value: %s\n\n", d_ConvertCharset("utf-8", "GBK", (char *)value));
//                xmlFree(value);
//            }
//        }
//    }

    //doc = xmlNewDoc(BAD_CAST"1.0");
    //printf("%d\n", __LINE__);
    //xmlDocSetRootElement(doc, *result->nodesetval->nodeTab);
    //printf("%d\n", __LINE__);
//    xmlSaveFile("1CreatedXml.xml",doc);
//    xml_tranid *xp;
//    xml_element *ep;
//    xp=xmlid;
    /*
     * 还需要考虑resolveconfig如何触发 可以起单独线程 间隔性检查文件修改时间
     * 另外修改时加读写锁
     * 遍历xmlid结构的方法 注意加读锁
     */
//    for( i=0; i<xmlnum; i++ )
//    {
//        printf("tranid=[%s]\n", xmlid[i].tranid);
//        ep=xmlid[i].ele;
//        while( ep )
//        {
//            printf("name=[%s]\n", ep->name);
//            printf("path=[%s]\n", ep->path);
//            printf("type=[%s]\n", ep->type);
//            printf("prop=[%s]\n", ep->prop);
//            ep=ep->next;
//        }
//    }


      /*
    int fd;
    fd=open("log", O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP );
    if (fd==-1)
    {
        printf("open log err\n");
    }
    if (dup2(fd, STDOUT_FILENO)!=STDOUT_FILENO)
    {
        printf("dup stdout err\n");
    }
    */


    char buf[128];
    if(!getxmlvalue( doc, "1111", "id1", 0, buf ))
        printf("get value err\n");
    printf("%s\n", buf);
    if(!getxmlvalue( doc, "1111", "nameid", 0, buf ))
        printf("get value err\n");
    printf("%s\n", buf);
    xmlFreeDoc(doc);
    /*free the document */
    xmlCleanupParser();
    xmlMemoryDump();//debug memory for regression tests
    while(1)
    {
    costt(1,0);
    doc = xmlParseFile("beps.xml");
        if(!getxmlvalue( doc, "1111", "count", 0, &i ))
            printf("get value err\n");
        printf("%d\n", i);
    xmlFreeDoc(doc);
    /*free the document */
    xmlCleanupParser();
    xmlMemoryDump();//debug memory for regression tests
    printf("%lf\n", costt(1,1));
        sleep(1);
    }
//    xmlXPathFreeObject (result);
    return EXIT_SUCCESS;
}               /* ----------  end of function main  ---------- */
Beispiel #8
0
int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params,
                           cgiRequestObj *req, owsRequestObj *ows_request)
{
  xmlDocPtr psDoc = NULL;       /* document pointer */
  xmlNodePtr psRootNode, psMainNode, psNode, psFtNode;
  const char *updatesequence=NULL;
  xmlNsPtr psNsOws, psNsXLink, psNsOgc;
  char *schemalocation = NULL;
  char *xsi_schemaLocation = NULL;
  const char *user_namespace_prefix = NULL;
  const char *user_namespace_uri = NULL;
  gmlNamespaceListObj *namespaceList=NULL; /* for external application schema support */

  char *script_url=NULL, *script_url_encoded=NULL, *formats_list;
  const char *value = NULL;
  const char *encoding;

  xmlChar *buffer = NULL;
  int size = 0, i;
  msIOContext *context = NULL;

  int ows_version = OWS_1_0_0;

  /* -------------------------------------------------------------------- */
  /*      Handle updatesequence                                           */
  /* -------------------------------------------------------------------- */

  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");

  encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");

  if (params->pszUpdateSequence != NULL) {
    i = msOWSNegotiateUpdateSequence(params->pszUpdateSequence, updatesequence);
    if (i == 0) { /* current */
      msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
      return msWFSException11(map, "updatesequence", "CurrentUpdateSequence", params->pszVersion);
    }
    if (i > 0) { /* invalid */
      msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
      return msWFSException11(map, "updatesequence", "InvalidUpdateSequence", params->pszVersion);
    }
  }

  /* -------------------------------------------------------------------- */
  /*      Create document.                                                */
  /* -------------------------------------------------------------------- */
  psDoc = xmlNewDoc(BAD_CAST "1.0");

  psRootNode = xmlNewNode(NULL, BAD_CAST "WFS_Capabilities");

  xmlDocSetRootElement(psDoc, psRootNode);

  /* -------------------------------------------------------------------- */
  /*      Name spaces                                                     */
  /* -------------------------------------------------------------------- */
  /*default name space*/
  xmlNewProp(psRootNode, BAD_CAST "xmlns", BAD_CAST "http://www.opengis.net/wfs");

  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wfs", BAD_CAST "wfs"));

  psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
  psNsXLink = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );

  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_uri");
  if(value) user_namespace_uri = value;

  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
  if(value) user_namespace_prefix = value;
  if(user_namespace_prefix != NULL && msIsXMLTagValid(user_namespace_prefix) == MS_FALSE)
    msIO_printf("<!-- WARNING: The value '%s' is not valid XML namespace. -->\n", user_namespace_prefix);
  else
    xmlNewNs(psRootNode, BAD_CAST user_namespace_uri, BAD_CAST user_namespace_prefix);

  /* any additional namespaces */
  namespaceList = msGMLGetNamespaces(&(map->web), "G");
  for(i=0; i<namespaceList->numnamespaces; i++) {
    if(namespaceList->namespaces[i].uri) {
      xmlNewNs(psRootNode, BAD_CAST namespaceList->namespaces[i].uri, BAD_CAST namespaceList->namespaces[i].prefix);
    }
  }
  msGMLFreeNamespaces(namespaceList);
  

  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->pszVersion );

  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");

  if (updatesequence)
    xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);

  /*schema*/
  schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
  xsi_schemaLocation = msStrdup("http://www.opengis.net/wfs");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wfs/1.1.0/wfs.xsd");
  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);

  /* -------------------------------------------------------------------- */
  /*      Service metadata.                                               */
  /* -------------------------------------------------------------------- */

  xmlAddChild(psRootNode,
                          msOWSCommonServiceIdentification(psNsOws, map, "OGC WFS", params->pszVersion, "FO"));

  /*service provider*/
  xmlAddChild(psRootNode, msOWSCommonServiceProvider(
                            psNsOws, psNsXLink, map, "FO"));

  /*operation metadata */
  if ((script_url=msOWSGetOnlineResource(map, "FO", "onlineresource", req)) == NULL
      || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
    msSetError(MS_WFSERR, "Server URL not found", "msWFSGetCapabilities11()");
    return msWFSException11(map, "mapserv", "NoApplicableCode", params->pszVersion);
  }

  /* -------------------------------------------------------------------- */
  /*      Operations metadata.                                            */
  /* -------------------------------------------------------------------- */
  psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psNsOws));

  /* -------------------------------------------------------------------- */
  /*      GetCapabilities                                                 */
  /* -------------------------------------------------------------------- */
  psNode = xmlAddChild(psMainNode,
                       msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetCapabilities",
                           OWS_METHOD_GETPOST, script_url_encoded));

  xmlAddChild(psMainNode, psNode);
  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                ows_version, psNsOws, "Parameter", "service", "WFS"));
  /*accept version*/
  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
              "Parameter", "AcceptVersions",
              "1.0.0,1.1.0"));
  /*format*/
  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
              "Parameter", "AcceptFormats",
              "text/xml"));


  /* -------------------------------------------------------------------- */
  /*      DescribeFeatureType                                             */
  /* -------------------------------------------------------------------- */
  if (msOWSRequestIsEnabled(map, NULL, "F", "DescribeFeatureType", MS_TRUE)) {
    psNode = xmlAddChild(psMainNode,
                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeFeatureType",
                             OWS_METHOD_GETPOST, script_url_encoded));
    xmlAddChild(psMainNode, psNode);

    /*output format*/
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                "Parameter", "outputFormat",
                "XMLSCHEMA,text/xml; subtype=gml/2.1.2,text/xml; subtype=gml/3.1.1"));
  }

  /* -------------------------------------------------------------------- */
  /*      GetFeature                                                      */
  /* -------------------------------------------------------------------- */
  if (msOWSRequestIsEnabled(map, NULL, "F", "GetFeature", MS_TRUE)) {

    psNode = xmlAddChild(psMainNode,
                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetFeature",
                             OWS_METHOD_GETPOST, script_url_encoded));
    xmlAddChild(psMainNode, psNode);

    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                "Parameter", "resultType",
                "results,hits"));

    formats_list = msWFSGetOutputFormatList( map, NULL, "1.1.0" );
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                "Parameter", "outputFormat",
                formats_list));
    msFree( formats_list );

    value = msOWSLookupMetadata(&(map->web.metadata), "FO", "maxfeatures");

    if (value) {
      xmlAddChild(psMainNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                  "Constraint", "DefaultMaxFeatures",
                  (char *)value));
    }
  }

  /* -------------------------------------------------------------------- */
  /*      FeatureTypeList                                                 */
  /* -------------------------------------------------------------------- */

  psFtNode = xmlNewNode(NULL, BAD_CAST "FeatureTypeList");
  xmlAddChild(psRootNode, psFtNode);
  psNode = xmlNewChild(psFtNode, NULL, BAD_CAST "Operations", NULL);
  xmlNewChild(psNode, NULL, BAD_CAST "Operation", BAD_CAST "Query");

  for(i=0; i<map->numlayers; i++) {
    layerObj *lp;
    lp = GET_LAYER(map, i);

    if (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))
      continue;

    /* List only vector layers in which DUMP=TRUE */
    if (msWFSIsLayerSupported(lp))
      xmlAddChild(psFtNode, msWFSDumpLayer11(map, lp, psNsOws));
  }





  /* -------------------------------------------------------------------- */
  /*      Filter capabilities.                                            */
  /* -------------------------------------------------------------------- */

  psNsOgc = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX);
  xmlAddChild(psRootNode, FLTGetCapabilities(psNsOgc, psNsOgc, MS_FALSE));
  /* -------------------------------------------------------------------- */
  /*      Write out the document.                                         */
  /* -------------------------------------------------------------------- */

  if( msIO_needBinaryStdout() == MS_FAILURE )
    return MS_FAILURE;

  if (encoding)
    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
  else
    msIO_setHeader("Content-Type","text/xml");
  msIO_sendHeaders();

  context = msIO_getHandler(stdout);

  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
  msIO_contextWrite(context, buffer, size);
  xmlFree(buffer);

  /*free buffer and the document */
  /*xmlFree(buffer);*/
  xmlFreeDoc(psDoc);
  xmlFreeNs(psNsOgc);

  free(script_url);
  free(script_url_encoded);
  free(xsi_schemaLocation);
  free(schemalocation);

  xmlCleanupParser();

  return(MS_SUCCESS);
}
Beispiel #9
0
int Sipreply2Xmpp(ua_pres_t* hentity, struct sip_msg * msg)
{
	/* named according to the direction of the message in xmpp*/
	str from_uri;
	str to_uri;
	xmlDocPtr doc= NULL;
	xmlNodePtr root_node= NULL, node = NULL;
	xmlAttrPtr attr= NULL;
	str xmpp_msg;
	int code;
	str reason;
	char* err_reason= NULL;
	xmlBufferPtr buffer= NULL;
	char buf_to[256];

	LM_DBG("*** Entered the callback\n");

	URI_ADD_NULL_TERM(to_uri, buf_to, hentity->watcher_uri);
 	from_uri.s = xmpp_uri_sip2xmpp(hentity->pres_uri);
	if(from_uri.s == NULL)
	{
		LM_ERR("Failed to traslate sip uri to xmpp uri\n");
		return -1;
	}
	from_uri.len= strlen(from_uri.s);

	doc= xmlNewDoc(BAD_CAST "1.0");
	if(doc==0)
		goto error;

	root_node = xmlNewNode(NULL, BAD_CAST "presence");

	if(root_node==0)
		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\n");
		goto error;
	}
	attr= xmlNewProp(root_node, BAD_CAST "from", BAD_CAST from_uri.s);
	if(attr== NULL)
	{
		LM_ERR("while adding attribute from\n");
		goto error;
	}

	if(msg== FAKED_REPLY)
	{
		code = 408;
		reason.s= "Request Timeout";
		reason.len= strlen(reason.s)- 1;
	}
	else
	{
		code= msg->first_line.u.reply.statuscode;
		reason= msg->first_line.u.reply.reason;
	}

	LM_DBG("SIP reply code=%d ; to_uri= %s ; from_uri= %s\n",
			code, to_uri.s, from_uri.s);

	if(code>=300)
	{
		err_reason= get_error_reason(code, &reason);
		if(err_reason== NULL)
		{
			LM_ERR("couldn't get response phrase\n");
			goto error;
		}

		attr= xmlNewProp(root_node, BAD_CAST "type", BAD_CAST "error");
		if(attr== NULL)
		{
			LM_ERR("while adding new attribute\n");
			goto error;
		}
		node= xmlNewChild(root_node, 0, BAD_CAST  "error", 0 );
		if(node== NULL)
		{
			LM_ERR("while adding new node\n");
			goto error;
		}
		node= xmlNewChild(node, 0,  BAD_CAST err_reason, 0 );
		if(node== NULL)
		{
			LM_ERR("while adding new node\n");
			goto error;
		}

		attr= xmlNewProp(node, BAD_CAST "xmlns",
				BAD_CAST "urn:ietf:params:xml:ns:xmpp-stanzas");
		if(attr== NULL)
		{
			LM_ERR("while adding new attribute\n");
			goto error;
		}
	}
	else
		if(code>=200 )
		{
			attr= xmlNewProp(root_node, BAD_CAST "type", BAD_CAST "subscribed");
			if(attr== NULL)
			{
				LM_ERR("while adding new attribute\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_packet(&from_uri, &to_uri, &xmpp_msg, &hentity->to_tag)< 0)
	{
		LM_ERR("while sending xmpp_reply_to_subscribe\n");
		goto error;
	}
	if(err_reason)
		pkg_free(err_reason);
	xmlFreeDoc(doc);

	return 0;

error:

	if(doc)
		xmlFreeDoc(doc);
	if(err_reason)
		pkg_free(err_reason);
	return -1;

}
Beispiel #10
0
/*>void testWriteAsPDBML(FILE *fp, PDB *pdb)
   -----------------------------------------
*//**

   \param[in]     *fp   PDB file pointer to be written
   \param[in]     *pdb  PDB linked list to write

   Write a PDB linked list in PDBML format.
   
   This test function is based on the bioplib function blWriteAsPDBML(). 
   The function calls blAddTagVariablesNodes() which writes additional 
   user-defined tags for each atom.

   Tags are written if gPDBTagWrite is TRUE.

-  25.08.14 Original. By: CTP
-  28.08.14 Use gNPDBTagFunctions to control output of user-defined tags.
            By: CTP

*/
void testWriteAsPDBML(FILE *fp, PDB  *pdb)
{
   /* PDBML format supported */
   PDB         *p;
   xmlDocPtr   doc         = NULL;
   xmlNodePtr  root_node   = NULL, 
               sites_node  = NULL, 
               atom_node   = NULL, 
               node        = NULL;
   xmlNsPtr    pdbx        = NULL,
               xsi         = NULL;
   char        buffer[16], 
               *buffer_ptr;
   
   /* Create doc */
   doc = xmlNewDoc((xmlChar *) "1.0");
   doc->encoding = xmlStrdup((xmlChar *) "UTF-8");
   
   /* Root node */
   root_node = xmlNewNode(NULL, (xmlChar *) "datablock");
   xmlDocSetRootElement(doc, root_node);
   pdbx = xmlNewNs(root_node, (xmlChar *) "null", (xmlChar *) "PDBx");
   xsi  = xmlNewNs(root_node, (xmlChar *) "null", (xmlChar *) "xsi");
   xmlSetNs(root_node,pdbx);
   
   
   /* Atom_sites node */
   sites_node = xmlNewChild(root_node, NULL,
                            (xmlChar *) "atom_siteCategory", NULL);
   
   /* Atom nodes */
   for(p = pdb ; p ; NEXT(p))
   {
      /* skip TER */
      if(!strncmp("TER",p->resnam,3))
      {
         continue;
      }

      /* Add atom node */
      atom_node = xmlNewChild(sites_node, NULL,
                              (xmlChar *) "atom_site", NULL);
      sprintf(buffer, "%d", p->atnum);
      xmlNewProp(atom_node, (xmlChar *) "id", (xmlChar *) buffer);
      
      /* Add atom data nodes */
      /* B value */
      sprintf(buffer,"%.2f", p->bval);
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "B_iso_or_equiv",
                         (xmlChar *) buffer);

      /* coordinates */
      sprintf(buffer,"%.3f", p->x);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "Cartn_x",
                         (xmlChar *) buffer);

      sprintf(buffer,"%.3f", p->y);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "Cartn_y",
                         (xmlChar *) buffer);

      sprintf(buffer,"%.3f", p->z);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "Cartn_z",
                         (xmlChar *) buffer);

      /* author atom site labels */
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_asym_id",
                         (xmlChar *) p->chain);

      strcpy(buffer,p->atnam);
      KILLTRAILSPACES(buffer);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_atom_id",
                         (xmlChar *) buffer);

      strcpy(buffer,p->resnam);
      KILLTRAILSPACES(buffer);
      KILLLEADSPACES(buffer_ptr,buffer);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_comp_id",
                         (xmlChar *) buffer_ptr);
      
      sprintf(buffer,"%d", p->resnum);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_seq_id",
                         (xmlChar *) buffer);

      /* record type atom/hetatm */
      strcpy(buffer,p->record_type);
      KILLTRAILSPACES(buffer);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "group_PDB",
                         (xmlChar *) buffer);

      /* atom site labels */
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "label_alt_id",
                         NULL);
      if(p->altpos == ' ')
      {
         xmlNewNsProp(node, xsi, (xmlChar *) "nil", (xmlChar *) "true");
      }
      else
      {
         buffer[0] = p->altpos;
         buffer[1] = '\0';
         xmlNodeSetContent(node, (xmlChar *) buffer);
      }
      
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "label_asym_id",
                         (xmlChar *) p->chain);

      strcpy(buffer,p->atnam);
      KILLTRAILSPACES(buffer);
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "label_atom_id",
                         (xmlChar *) buffer);

      strcpy(buffer,p->resnam);
      KILLTRAILSPACES(buffer);
      KILLLEADSPACES(buffer_ptr,buffer);
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "label_comp_id",
                         (xmlChar *) buffer_ptr);

      /* Note: Entity ID is not stored in PDB data structure. 
               Value set to 1 */
      node = xmlNewChild(atom_node, NULL,
                         (xmlChar *) "label_entity_id",
                         (xmlChar *) "1");
      
      sprintf(buffer,"%d", p->resnum);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "label_seq_id",
                         (xmlChar *) buffer);

      /* occupancy */
      sprintf(buffer,"%.2f", p->occ);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "occupancy",
                         (xmlChar *) buffer);
                         
      /* insertion code */
      /* Note: Insertion code node only included for residues with 
               insertion codes */
      if(strcmp(p->insert," "))
      {
         sprintf(buffer,"%s", p->insert);
         node = xmlNewChild(atom_node, NULL, 
                            (xmlChar *) "pdbx_PDB_ins_code",
                            (xmlChar *) buffer);
      }

      /* model number */
      /* Note: Model number is not stored in PDB data structure.
               Value set to 1 */
      node = xmlNewChild(atom_node, NULL,
                         (xmlChar *) "pdbx_PDB_model_num",
                         (xmlChar *) "1");

      /* formal charge */
      /* Note: Formal charge node not included for neutral atoms */
      if(p->formal_charge != 0)
      {
         sprintf(buffer,"%d", p->formal_charge);
         node = xmlNewChild(atom_node, NULL, 
                            (xmlChar *) "pdbx_formal_charge",
                            (xmlChar *) buffer);
      }

      /* atom symbol */
      /* Note: If the atomic symbol is not set in PDB data structure then
               the value set is based on columns 13-14 of pdb-formated
               text file.  */
      sprintf(buffer,"%s", p->element);
      KILLLEADSPACES(buffer_ptr,buffer);
      if(strlen(buffer_ptr))
      {
         node = xmlNewChild(atom_node, NULL, (xmlChar *) "type_symbol",
                            (xmlChar *) buffer_ptr);
      }
      else
      {
         blSetElementSymbolFromAtomName(buffer,p->atnam_raw);
         node = xmlNewChild(atom_node, NULL, (xmlChar *) "type_symbol",
                            (xmlChar *) buffer);
      }

      /* NEW CODE */
      /* user-defined tags */
      if(gNPDBTagFunctions)
      {
         blAddTagVariablesNodes(p,atom_node);
      }
   }

   /* Write to doc file pointer */
   xmlDocFormatDump(fp,doc,1);

   /* Free Memory */
    xmlFreeDoc(doc);
    xmlCleanupParser();

   return;
}
Beispiel #11
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;
}
Beispiel #12
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;

}
Beispiel #13
0
int Sipreply2Xmpp(ua_pres_t* hentity, struct sip_msg * msg)
{
	char* uri;
	/* named according to the direction of the message in xmpp*/
	str from_uri;
	str to_uri;
	xmlDocPtr doc= NULL;
	xmlNodePtr root_node= NULL, node = NULL;
	xmlAttrPtr attr= NULL;
	str xmpp_msg;
	int code;
	str reason;
	char* err_reason= NULL;
	xmlBufferPtr buffer= NULL;

	LM_DBG("start..\n");
	uri=(char*)pkg_malloc(sizeof(char)*( hentity->watcher_uri->len+1));
	if(uri== NULL)
	{
		LM_ERR("no more memory\n");
		goto error;
	}
	memcpy(uri, hentity->watcher_uri->s, hentity->watcher_uri->len);
	uri[hentity->watcher_uri->len]= '\0';
	to_uri.s= duri_sip_xmpp(uri);
	if(to_uri.s== NULL)
	{
		LM_ERR("whil decoding sip uri in xmpp\n");
		pkg_free(uri);
		goto error;
	}

	to_uri.len= strlen(to_uri.s);
	pkg_free(uri);

	uri=(char*)pkg_malloc(sizeof(char)*( hentity->pres_uri->len+1));
	if(uri== NULL)
	{
		LM_ERR("no more memory\n");
		goto error;
	}
	memcpy(uri, hentity->pres_uri->s, hentity->pres_uri->len);
	uri[hentity->pres_uri->len]= '\0';
	from_uri.s= euri_sip_xmpp(uri);
	if(from_uri.s== NULL)
	{
		LM_ERR("while encoding sip uri in xmpp\n");
		pkg_free(uri);
		goto error;
	}

	from_uri.len= strlen(from_uri.s);
	pkg_free(uri);

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

	if(root_node==0)
		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\n");
		goto error;
	}
	attr= xmlNewProp(root_node, BAD_CAST "from", BAD_CAST from_uri.s);
	if(attr== NULL)
	{
		LM_ERR("while adding attribute from\n");
		goto error;
	}

	if(msg== FAKED_REPLY)
	{
		code = 408;
		reason.s= "Request Timeout";
		reason.len= strlen(reason.s)- 1;
	}
	else
	{
		code= msg->first_line.u.reply.statuscode;
		reason= msg->first_line.u.reply.reason;
	}

	LM_DBG(" to_uri= %s\n\t from_uri= %s\n",
			to_uri.s, from_uri.s);

	if(code>=300)
	{
		LM_DBG(" error code(>= 300)\n");
		err_reason= get_error_reason(code, &reason);
		if(err_reason== NULL)
		{
			LM_ERR("couldn't get response phrase\n");
			goto error;
		}

		attr= xmlNewProp(root_node, BAD_CAST "type", BAD_CAST "error");
		if(attr== NULL)
		{
			LM_ERR("while adding new attribute\n");
			goto error;
		}
		node= xmlNewChild(root_node, 0, BAD_CAST  "error", 0 );
		if(node== NULL)
		{
			LM_ERR("while adding new node\n");
			goto error;
		}
		node= xmlNewChild(node, 0,  BAD_CAST err_reason, 0 );
		if(node== NULL)
		{
			LM_ERR("while adding new node\n");
			goto error;
		}

		attr= xmlNewProp(node, BAD_CAST "xmlns",
				BAD_CAST "urn:ietf:params:xml:ns:xmpp-stanzas");
		if(attr== NULL)
		{
			LM_ERR("while adding new attribute\n");
			goto error;
		}

	} else {
		if(code>=200 )
		{
			LM_DBG(" 2xx code\n");
			attr= xmlNewProp(root_node, BAD_CAST "type", BAD_CAST "subscribed");
			if(attr== NULL)
			{
				LM_ERR("while adding new attribute\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_packet(&from_uri, &to_uri, &xmpp_msg, &hentity->to_tag)< 0)
	{
		LM_ERR("while sending xmpp_reply_to_subscribe\n");
		goto error;
	}
	if(err_reason)
		pkg_free(err_reason);
	xmlFreeDoc(doc);

	return 0;

error:

	if(doc)
		xmlFreeDoc(doc);
	if(err_reason)
		pkg_free(err_reason);
	return -1;

}
Beispiel #14
0
/* methods for building reg publish */
str* build_reginfo_partial(ppublic_t *impu, struct pcontact* c, int type) {
	xmlDocPtr doc = NULL;
	xmlNodePtr root_node = NULL;
	xmlNodePtr registration_node = NULL;
	xmlNodePtr contact_node = NULL;
	xmlNodePtr uri_node = NULL;
	str * body = NULL;
	char buf[512];

	/* create the XML-Body */
	doc = xmlNewDoc(BAD_CAST "1.0");
	if (doc == 0) {
		LM_ERR("Unable to create XML-Doc\n");
		return NULL;
	}

	root_node = xmlNewNode(NULL, BAD_CAST "reginfo");
	if (root_node == 0) {
		LM_ERR("Unable to create reginfo-XML-Element\n");
		return NULL;
	}
	/* This is our Root-Element: */
	xmlDocSetRootElement(doc, root_node);

	xmlNewProp(root_node, BAD_CAST "xmlns", BAD_CAST "urn:ietf:params:xml:ns:reginfo");

	/* we set the version to 0 but it should be set to the correct value in the pua module */
	xmlNewProp(root_node, BAD_CAST "version", BAD_CAST "0");
	xmlNewProp(root_node, BAD_CAST "state", BAD_CAST "partial" );

	/* Registration Node */
	registration_node = xmlNewChild(root_node, NULL, BAD_CAST "registration", NULL);
	if (registration_node == NULL) {
		LM_ERR("while adding child\n");
		goto error;
	}

	/* Add the properties to this Node for AOR and ID: */
	//registration aor nodes
	memset(buf, 0, sizeof(buf));
	snprintf(buf, sizeof(buf), "%.*s", impu->public_identity.len, impu->public_identity.s);
	xmlNewProp(registration_node, BAD_CAST "aor", BAD_CAST buf);
	
	//registration id
	memset(buf, 0, sizeof(buf));
	snprintf(buf, sizeof(buf), "%p", impu);
	xmlNewProp(registration_node, BAD_CAST "id", BAD_CAST buf);

	//now the updated contact
	contact_node =xmlNewChild(registration_node, NULL, BAD_CAST "contact", NULL);
	if (contact_node == NULL) {
		LM_ERR("while adding child\n");
		goto error;
	}
	memset(buf, 0, sizeof(buf));
	snprintf(buf, sizeof(buf), "%p", c);
	xmlNewProp(contact_node, BAD_CAST "id", BAD_CAST buf);

	//TODO: currently we only support publish of termination for event unregistered and expires 0
	xmlNewProp(contact_node, BAD_CAST "state", BAD_CAST "terminated");
	xmlNewProp(contact_node, BAD_CAST "event", BAD_CAST "unregistered");
	memset(buf, 0, sizeof(buf));
	snprintf(buf, sizeof(buf), "%i", 0);
	xmlNewProp(contact_node, BAD_CAST "expires", BAD_CAST buf);

	/* URI-Node */
	memset(buf, 0, sizeof(buf));
	snprintf(buf, sizeof(buf), "%.*s", c->aor.len, c->aor.s);
	uri_node = xmlNewChild(contact_node, NULL, BAD_CAST "uri", BAD_CAST buf);
	if (uri_node == NULL) {
		LM_ERR("while adding child\n");
		goto error;
	}

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

	/* Write the XML into the body */
	xmlDocDumpFormatMemory(doc, (unsigned char**) (void*) &body->s, &body->len,
			1);

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

	return body;

error:
	if (body) {
		if (body->s)
			xmlFree(body->s);
		pkg_free(body);
	}
	if (doc)
		xmlFreeDoc(doc);
	return NULL;

}
Beispiel #15
0
void test_html()
{
    htmlDocPtr doc;
    doc = htmlNewDoc( "", "" );
    xmlNodePtr root_node = xmlNewNode(NULL,BAD_CAST"ap");
    //设置根节点
    xmlDocSetRootElement(doc,root_node);
// cur = xmlDocGetRootElement(doc); //获取文档根结点
    //在根节点中直接创建节点
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode1", BAD_CAST "newNode1 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode2", BAD_CAST "newNode2 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode3", BAD_CAST "newNode3 content");
    /*
    xmlChar *key;
    key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1); //获取文本结点的文本,需用其子结点
    xmlFree(key);
    */

    //创建一个绑定在根节点的子节点
    xmlNewChild(root_node, NULL, BAD_CAST "node1",BAD_CAST "content of node1");
    /*
    xmlNodeSetContent(curNode, (xmlChar *) "content changed");//设置结点的文本内容
    //得到一个节点的内容:
    //xmlChar *value = xmlNodeGetContent(node);
    //返回值value应该使用xmlFree(value)释放内存

    xmlUnlinkNode(curNode); //将当前结点从文档中断链(unlink),这样本文档就不会再包含这个子结点
    xmlFreeNode(curNode); //手动删除断链结点的内存, 若没有xmlDelNode或者xmlRemoveNode,使用此函数

    xmlChar *uri;
    uri = xmlGetProp(cur, "uri"); //获取属性值
    xmlFree(uri); //释放内存

    xmlSetProp(curNode,BAD_(xmlChar *)"attribute", (xmlChar *) "no"); //设置当前结点的attribute属性的属性值为no
    */
    //创建一个节点,设置其内容和属性,然后加入根结点
    xmlNodePtr node = xmlNewNode(NULL,BAD_CAST"node2");
    xmlNodePtr content = xmlNewText(BAD_CAST"NODE CONTENT");
    xmlAddChild(root_node,node);
    xmlAddChild(node,content);
    xmlNewProp(node,BAD_CAST"attribute",BAD_CAST "yes");
    //通过xmlNewProp()增加一个节点的属性
    node=xmlNewChild(root_node, NULL, BAD_CAST "node3", BAD_CAST"node has attributes");
    xmlNewProp(node, BAD_CAST "attribute", BAD_CAST "no");
    //创建一个儿子和孙子节点
    node = xmlNewNode(NULL, BAD_CAST "son");
    xmlAddChild(root_node,node);
    xmlNodePtr grandson = xmlNewNode(NULL, BAD_CAST "grandson");
    xmlAddChild(node,grandson);
    xmlAddChild(grandson, xmlNewText(BAD_CAST "This is a grandson node"));
    //存储xml文档
    int nRel = xmlSaveFile("CreatedXml.xml",doc);
    if (nRel != -1)
    {
       printf("%s\n",d_ConvertCharset("GBK", "utf-8", "一个xml文档被创建\n"));
    }

    //保存文件
    /*
     * xmlSaveFormatFile (docname, doc, 1); 保存文件到磁盘,第一个参数是写入文件的名,第二个参数是一个xmlDoc结构指针,第三个参数设定为1,保证在输出上写入缩进。
     */
    xmlSaveFormatFileEnc( "-", doc, "UTF-8", 1);
    doc=htmlReadFile("ap", NULL, -1);
    xmlSaveFormatFileEnc( "-", doc, "UTF-8", 1);

}
Beispiel #16
0
static xmlNodePtr msWFSDumpLayer11(mapObj *map, layerObj *lp, xmlNsPtr psNsOws)
{
  rectObj ext;

  xmlNodePtr psRootNode, psNode;
  const char *value    = NULL;
  const char *encoding = NULL;
  char *encoded=NULL;
  char *valueToFree;
  char **tokens;
  int n=0,i=0;

  encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
  if (!encoding)
    encoding = "ISO-8859-1";

  psRootNode = xmlNewNode(NULL, BAD_CAST "FeatureType");

  /* add namespace to layer name */
  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
  if(value) {
    n = strlen(value)+strlen(lp->name)+1+1;
    valueToFree = (char *) msSmallMalloc(sizeof(char*)*n);
    snprintf(valueToFree, n, "%s%s%s", (value ? value : ""), (value ? ":" : ""), lp->name);

    /*if there is an encoding using it on some of the items*/
    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Name", valueToFree, encoding);
    msFree(valueToFree);
  } else {
    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Name", lp->name, encoding);
  }

  if (lp->name && strlen(lp->name) > 0 &&
      (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
    xmlAddSibling(psNode,
                  xmlNewComment(BAD_CAST "WARNING: The layer name '%s' might contain spaces or "
                                "invalid characters or may start with a number. This could lead to potential problems"));

  value = msOWSLookupMetadata(&(lp->metadata), "FO", "title");
  if (!value)
    value =(const char*)lp->name;

  psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Title", value, encoding);


  value = msOWSLookupMetadata(&(lp->metadata), "FO", "abstract");
  if (value)
    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Abstract", value, encoding);



  value = msOWSLookupMetadata(&(lp->metadata), "FO", "keywordlist");

  if (value) {
    if (encoding)
      encoded = msGetEncodedString(value, encoding);
    else
      encoded = msGetEncodedString(value, "ISO-8859-1");

    msLibXml2GenerateList(
      xmlNewChild(psRootNode, psNsOws, BAD_CAST "Keywords", NULL),
      NULL, "Keyword", encoded, ',' );
    msFree(encoded);
  }
  /*support DefaultSRS and OtherSRS*/
  valueToFree = msOWSGetProjURN(&(map->projection),&(map->web.metadata),"FO",MS_FALSE);
  if (!valueToFree)
    valueToFree = msOWSGetProjURN(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);

  if (valueToFree) {
    tokens = msStringSplit(valueToFree, ' ', &n);
    if (tokens && n > 0) {
      psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "DefaultSRS", BAD_CAST tokens[0]);
      for (i=1; i<n; i++)
        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "OtherSRS", BAD_CAST tokens[i]);

      msFreeCharArray(tokens, n);
    }
  } else
    xmlAddSibling(psNode,
                  xmlNewComment(BAD_CAST "WARNING: Mandatory mapfile parameter: (at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs/ows_srs metadata was missing in this context."));

  free(valueToFree);
  valueToFree = NULL;

  /*TODO: adevertize only gml3?*/
  psNode = xmlNewNode(NULL, BAD_CAST "OutputFormats");
  xmlAddChild(psRootNode, psNode);

  {
    char *formats_list = msWFSGetOutputFormatList( map, lp, "1.1.0" );
    int iformat, n;
    char **tokens;

    n = 0;
    tokens = msStringSplit(formats_list, ',', &n);

    for( iformat = 0; iformat < n; iformat++ )
      xmlNewChild(psNode, NULL, BAD_CAST "Format",
                  BAD_CAST tokens[iformat] );
    msFree( formats_list );
    msFreeCharArray( tokens, n );
  }

  /*bbox*/
  if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS) {
    /*convert to latlong*/
    if (lp->projection.numargs > 0) {
      if (!pj_is_latlong(&lp->projection.proj))
        msProjectRect(&lp->projection, NULL, &ext);
    } else if (map->projection.numargs > 0 && !pj_is_latlong(&map->projection.proj))
      msProjectRect(&map->projection, NULL, &ext);

    xmlAddChild(psRootNode,
                msOWSCommonWGS84BoundingBox( psNsOws, 2,
                    ext.minx, ext.miny,
                    ext.maxx, ext.maxy));
  } else {
    xmlNewChild(psRootNode, psNsOws, BAD_CAST "WGS84BoundingBox", NULL);
    xmlAddSibling(psNode,
                  xmlNewComment(BAD_CAST "WARNING: Optional WGS84BoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement"));
  }

  value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_href");

  if (value) {
    psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "MetadataURL", BAD_CAST value);

    value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_format");

    if (!value)
      value = msStrdup("text/html"); /* default */

    xmlNewProp(psNode, BAD_CAST "format", BAD_CAST value);

    value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_type");

    if (!value)
      value = msStrdup("FGDC"); /* default */

    xmlNewProp(psNode, BAD_CAST "type", BAD_CAST value);
  }

  return psRootNode;
}
Beispiel #17
0
char* KmlRenderer::lookupPlacemarkStyle()
{
  char  lineHexColor[32];
  char  polygonHexColor[32];
  char  labelHexColor[32];
  char        *styleName=NULL;

  styleName = msStringConcatenate(styleName, "style");

  if (SymbologyFlag[Line]) {
    /*
      <LineStyle id="ID">
      <!-- inherited from ColorStyle -->
      <color>ffffffff</color>            <!-- kml:color -->
      <colorMode>normal</colorMode>      <!-- colorModeEnum: normal or random -->

      <!-- specific to LineStyle -->
      <width>1</width>                   <!-- float -->
      </LineStyle>
    */

    for (int i=0; i<numLineStyle; i++) {
      if (currentLayer && currentLayer->compositer && currentLayer->compositer->opacity > 0 && currentLayer->compositer->opacity < 100 &&
          LineStyle[i].color->alpha == 255)
        LineStyle[i].color->alpha = MS_NINT(currentLayer->compositer->opacity*2.55);

      sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[0].color->blue,
              LineStyle[i].color->green, LineStyle[i].color->red);

      char lineStyleName[32];
      sprintf(lineStyleName, "_line_%s_w%.1f", lineHexColor, LineStyle[i].width);
      styleName = msStringConcatenate(styleName, lineStyleName);
    }
  }

  if (SymbologyFlag[Polygon]) {
    /*
      <PolyStyle id="ID">
      <!-- inherited from ColorStyle -->
      <color>ffffffff</color>            <!-- kml:color -->
      <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->

      <!-- specific to PolyStyle -->
      <fill>1</fill>                     <!-- boolean -->
      <outline>1</outline>               <!-- boolean -->
      </PolyStyle>
    */

    if (currentLayer && currentLayer->compositer && currentLayer->compositer->opacity > 0 && currentLayer->compositer->opacity < 100 &&
        PolygonColor.alpha == 255)
      PolygonColor.alpha = MS_NINT(currentLayer->compositer->opacity*2.55);
    sprintf(polygonHexColor,"%02x%02x%02x%02x", PolygonColor.alpha, PolygonColor.blue, PolygonColor.green, PolygonColor.red);

    char polygonStyleName[64];
    sprintf(polygonStyleName, "_polygon_%s", polygonHexColor);
    styleName = msStringConcatenate(styleName, polygonStyleName);
  }

  if (SymbologyFlag[Label]) {
    /*
      <LabelStyle id="ID">
      <!-- inherited from ColorStyle -->
      <color>ffffffff</color>            <!-- kml:color -->
      <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->

      <!-- specific to LabelStyle -->
      <scale>1</scale>                   <!-- float -->
      </LabelStyle>
    */

    if (currentLayer && currentLayer->compositer && currentLayer->compositer->opacity > 0 && currentLayer->compositer->opacity < 100 &&
        LabelColor.alpha == 255)
      LabelColor.alpha = MS_NINT(currentLayer->compositer->opacity*2.55);
    sprintf(labelHexColor,"%02x%02x%02x%02x", LabelColor.alpha, LabelColor.blue, LabelColor.green, LabelColor.red);

    // __TODO__ add label scale

    char labelStyleName[64];
    sprintf(labelStyleName, "_label_%s", labelHexColor);
    styleName = msStringConcatenate(styleName, labelStyleName);
  }

  if (SymbologyFlag[Symbol]) {
    /*
    <Style id="randomColorIcon">
            <IconStyle>
            <color>ff00ff00</color>
            <colorMode>random</colorMode>
            <scale>1.1</scale>
            <Icon>
            <href>http://maps.google.com/mapfiles/kml/pal3/icon21.png</href>
            </Icon>
            </IconStyle>
    </Style>
    */

    /* __TODO__ add label scale */

    styleName = msStringConcatenate(styleName, "_");
    styleName = msStringConcatenate(styleName, SymbolName);
  }

  char *styleUrl = msLookupHashTable(StyleHashTable, styleName);
  if (!styleUrl) {
    char *styleValue=NULL;
    styleValue = msStringConcatenate(styleValue, "#");
    styleValue = msStringConcatenate(styleValue, styleName);
    hashObj *hash = msInsertHashTable(StyleHashTable, styleName, styleValue);
    styleUrl = hash->data;
    msFree(styleValue);

    /* Insert new Style node into Document node*/
    xmlNodePtr styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
    xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST styleName);

    if (SymbologyFlag[Polygon]) {
      xmlNodePtr polyStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "PolyStyle", NULL);
      xmlNewChild(polyStyleNode, NULL, BAD_CAST "color", BAD_CAST polygonHexColor);
    }

    if (SymbologyFlag[Line]) {
      for (int i=0; i<numLineStyle; i++) {
        xmlNodePtr lineStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LineStyle", NULL);
        sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[i].color->blue,
                LineStyle[i].color->green, LineStyle[i].color->red);
        xmlNewChild(lineStyleNode, NULL, BAD_CAST "color", BAD_CAST lineHexColor);

        char width[16];
        sprintf(width, "%.1f", LineStyle[i].width);
        xmlNewChild(lineStyleNode, NULL, BAD_CAST "width", BAD_CAST width);
      }
    }

    if (SymbologyFlag[Symbol]) {
      xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);

      xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
      xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST SymbolUrl);

      /*char scale[16];
        sprintf(scale, "%.1f", style->scale);
        xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
    } else {
      const char *value=msLookupHashTable(&currentLayer->metadata, "kml_default_symbol_href");
      if (value && strlen(value) > 0) {
        xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);

        xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
        xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST value);
      }
    }

    if (SymbologyFlag[Label]) {
      xmlNodePtr labelStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LabelStyle", NULL);
      xmlNewChild(labelStyleNode, NULL, BAD_CAST "color", BAD_CAST labelHexColor);

      /*char scale[16];
        sprintf(scale, "%.1f", style->scale);
        xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
    }
  }

  if (styleName)
    msFree(styleName);

  return styleUrl;
}
Beispiel #18
0
/***********************************************
 *  向Doc新增指定父结点的结点信息              *
 *  成功返回0和Doc文档                         *
 *  失败则返回-1和NULL                         *
 *  doc用完后请手动free                        *
 ***********************************************/
int appendRowToDoc(xmlDocPtr doc, byte * parentNodeName, Row row)
{
	int nRet = FAIL;
	int i,j;
	xmlNodePtr curNode = NULL;
	xmlNodePtr node = NULL;
	xmlAttrPtr newattr;
	byte * value = g2u(row.value);
	LIBXML_TEST_VERSION;
	
	if(doc == NULL) {
                ErrorLog(ERROR, "doc is null");
                printf("doc is null");
                return FAIL;
        }

	if(row.key == NULL && row.value == NULL) {
		ErrorLog(ERROR, "row can not empty");
		printf("row can not empty");
		return FAIL;
	}

        curNode = xmlDocGetRootElement(doc);
        if (curNode == NULL) {
                xmlFreeDoc(doc);
                ErrorLog(ERROR, "open doc fail, doc content is empty");
                printf("open doc fail, doc content is empty");
                return FAIL;
        }

        curNode = curNode->xmlChildrenNode;
        if (curNode == NULL) {
                xmlFreeDoc(doc);
                ErrorLog(ERROR, "can not find child node");
                printf("can not find child node");
                return FAIL;
        }

        /* if has child node, do while */
        while (curNode != NULL) {
                if(!xmlStrcmp(curNode->name, BAD_CAST parentNodeName)) {
			if(row.row_type == ONLY_ATTRIB) {
				if(row.column == NULL || row.column_num == 0) {
					xmlFreeDoc(doc);
					ErrorLog(ERROR, "row 's attrib is not exist");
					printf("row 's attrib is not exist");
					return FAIL;
				}
				
				node = xmlNewTextChild (curNode, NULL, (const xmlChar *)row.key, NULL);	
				for(i=0; i<row.column_num; i++) {
					newattr = xmlNewProp(node, (const xmlChar *)row.column[i].attrib, (const xmlChar *)g2u(row.column[i].value));
				}
				nRet = SUCC;
				break;
			}
			if(row.row_type == ONLY_VALUE) {
				node = xmlNewTextChild (curNode, NULL, (const xmlChar *)row.key, (const xmlChar *)value);
				if(node == NULL) {
					//xmlFreeDoc(doc);
					ErrorLog(ERROR, "append child text node fail");
					printf("append child text node fail");
					nRet = FAIL;
					break;
				}
				nRet = SUCC;
                		break;
			}	
			if(row.row_type == HAS_ATTR_VALUE) {
				if(row.column == NULL || row.column_num == 0) {
					xmlFreeDoc(doc);
					ErrorLog(ERROR, "row 's attrib is not exist");
					printf("row 's attrib is not exist");
					return FAIL;
				}
				
				node = xmlNewTextChild (curNode, NULL, (const xmlChar *)row.key, (const xmlChar *)value);	
				for(j=0; j<row.column_num; j++) {
					newattr = xmlNewProp(node, (const xmlChar *)row.column[j].attrib, (const xmlChar *)g2u(row.column[j].value));
				}
				nRet = SUCC;
				break;
			}		
                }
                curNode = curNode->next;
        }
	
	free(value);
	return nRet;
}
Beispiel #19
0
xmlNodePtr KmlRenderer::createDescriptionNode(shapeObj *shape)
{
  /*
    <description>
    <![CDATA[
    special characters here
    ]]>
    <description>
  */


  /*description nodes for vector layers:
    - if kml_description is set, use it
    - if not, dump the attributes */

  if (pszLayerDescMetadata) {
    char *pszTmp=NULL;
    char *pszTmpDesc = NULL;
    size_t bufferSize = 0;
    pszTmpDesc = msStrdup(pszLayerDescMetadata);

    for (int i=0; i<currentLayer->numitems; i++) {
      bufferSize = strlen(currentLayer->items[i]) + 3;
      pszTmp = (char *)msSmallMalloc(bufferSize);
      snprintf(pszTmp, bufferSize, "%%%s%%",currentLayer->items[i]);
      if (strcasestr(pszTmpDesc, pszTmp))
        pszTmpDesc = msCaseReplaceSubstring(pszTmpDesc,  pszTmp, shape->values[i]);
      msFree(pszTmp);
    }
    xmlNodePtr descriptionNode = xmlNewNode(NULL, BAD_CAST "description");
    xmlNodeAddContent(descriptionNode, BAD_CAST pszTmpDesc);
    msFree(pszTmpDesc);
    return descriptionNode;
  } else if ((papszLayerIncludeItems && nIncludeItems > 0) ||
             (papszLayerExcludeItems && nExcludeItems > 0)) {
    /* -------------------------------------------------------------------- */
    /*      preffered way is to use the ExtendedData tag (#3728)            */
    /*      http://code.google.com/apis/kml/documentation/extendeddata.html */
    /* -------------------------------------------------------------------- */

    xmlNodePtr extendedDataNode = xmlNewNode(NULL, BAD_CAST "ExtendedData");
    xmlNodePtr dataNode = NULL;
    const char*pszAlias=NULL;
    int bIncludeAll = MS_FALSE;

    if(papszLayerIncludeItems && nIncludeItems == 1 &&
        strcasecmp(papszLayerIncludeItems[0], "all") == 0)
      bIncludeAll = MS_TRUE;

    for (int i=0; i<currentLayer->numitems; i++) {
      int j=0,k=0;

      /*TODO optimize to calculate this only once per layer*/
      for (j=0; j<nIncludeItems; j++) {
        if (strcasecmp(currentLayer->items[i], papszLayerIncludeItems[j]) == 0)
          break;
      }
      if (j<nIncludeItems || bIncludeAll) {
        if (papszLayerExcludeItems && nExcludeItems > 0) {
          for (k=0; k<nExcludeItems; k++) {
            if (strcasecmp(currentLayer->items[i], papszLayerExcludeItems[k]) == 0)
              break;
          }
        }
        if (nExcludeItems == 0 || k == nExcludeItems) {
          dataNode = xmlNewNode(NULL, BAD_CAST "Data");
          xmlNewProp(dataNode, BAD_CAST "name", BAD_CAST  currentLayer->items[i]);
          pszAlias = getAliasName(currentLayer, currentLayer->items[i], "GO");
          if (pszAlias)
            xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  pszAlias);
          else
            xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  currentLayer->items[i]);
          if (shape->values[i] && strlen(shape->values[i]))
            xmlNewChild(dataNode, NULL, BAD_CAST "value", BAD_CAST  shape->values[i]);
          else
            xmlNewChild(dataNode, NULL, BAD_CAST "value", NULL);
          xmlAddChild(extendedDataNode, dataNode);
        }
      }
    }

    return extendedDataNode;


  }

  return NULL;
}
Beispiel #20
0
xmlNode *xccdf_benchmark_to_dom(struct xccdf_benchmark *benchmark, xmlDocPtr doc,
				xmlNode *parent, void *user_args)
{
	xmlNodePtr root_node = xccdf_item_to_dom(XITEM(benchmark), doc, parent);
	if (parent == NULL) {
		xmlDocSetRootElement(doc, root_node);
	}

	// FIXME!
	//xmlNewProp(root_node, BAD_CAST "xsi:schemaLocation", BAD_CAST XCCDF_SCHEMA_LOCATION);

	lookup_xsi_ns(doc);

	/* Handle attributes */
	if (xccdf_benchmark_get_resolved(benchmark))
		xmlNewProp(root_node, BAD_CAST "resolved", BAD_CAST "1");
	else
		xmlNewProp(root_node, BAD_CAST "resolved", BAD_CAST "0");

    const char *xmllang = xccdf_benchmark_get_lang(benchmark);
	if (xmllang) {
		xmlNs *ns_xml = xmlSearchNsByHref(doc, root_node, OSCAP_XML_XSI);
		if (ns_xml == NULL) {
			ns_xml = xmlNewNs(root_node, OSCAP_XML_XSI, BAD_CAST "xml");
		}
		xmlNewNsProp(root_node, ns_xml, BAD_CAST "lang", BAD_CAST xmllang);
	}

	const char *style = xccdf_benchmark_get_style(benchmark);
	if (style)
		xmlNewProp(root_node, BAD_CAST "style", BAD_CAST style);

	const char *style_href = xccdf_benchmark_get_style_href(benchmark);
	if (style_href)
		xmlNewProp(root_node, BAD_CAST "style-href", BAD_CAST style_href);

	// Export plain-text elements
	struct xccdf_plain_text_iterator *plain_text_it = xccdf_benchmark_get_plain_texts(benchmark);
	while (xccdf_plain_text_iterator_has_more(plain_text_it)) {
		struct xccdf_plain_text *plain_text = xccdf_plain_text_iterator_next(plain_text_it);
		xccdf_plain_text_to_dom(plain_text, doc, root_node, xccdf_benchmark_get_schema_version(benchmark));
	}
	xccdf_plain_text_iterator_free(plain_text_it);

	/* Handle children */
	if (xccdf_benchmark_get_cpe_list(benchmark)) {
		// CPE API can only export via xmlTextWriter, we export via DOM
		// this is used to bridge both methods
		xmlTextWriterPtr writer = xmlNewTextWriterTree(doc, root_node, 0);
		cpe_dict_export(xccdf_benchmark_get_cpe_list(benchmark), writer);
		xmlFreeTextWriter(writer);
	}
	if (xccdf_benchmark_get_cpe_lang_model(benchmark)) {
		// CPE API can only export via xmlTextWriter, we export via DOM
		// this is used to bridge both methods
		xmlTextWriterPtr writer = xmlNewTextWriterTree(doc, root_node, 0);
		cpe_lang_export(xccdf_benchmark_get_cpe_lang_model(benchmark), writer);
		xmlFreeTextWriter(writer);
	}

	xmlNs *ns_xccdf = lookup_xccdf_ns(doc, root_node, xccdf_benchmark_get_schema_version(benchmark));

	struct oscap_string_iterator *platforms = xccdf_benchmark_get_platforms(benchmark);
	while (oscap_string_iterator_has_more(platforms)) {
		xmlNode *platform_node = xmlNewTextChild(root_node, ns_xccdf, BAD_CAST "platform", NULL);

		const char *idref = oscap_string_iterator_next(platforms);
		if (idref)
			xmlNewProp(platform_node, BAD_CAST "idref", BAD_CAST idref);
	}
	oscap_string_iterator_free(platforms);

	const char *version = xccdf_benchmark_get_version(benchmark);
	if (version)
		xmlNewTextChild(root_node, ns_xccdf, BAD_CAST "version", BAD_CAST version);

	struct oscap_string_iterator* metadata = xccdf_item_get_metadata(XITEM(benchmark));
	while (oscap_string_iterator_has_more(metadata))
	{
		const char* meta = oscap_string_iterator_next(metadata);
		xmlNode *m = oscap_xmlstr_to_dom(root_node, "metadata", meta);
		xmlSetNs(m, ns_xccdf);
	}
	oscap_string_iterator_free(metadata);

	OSCAP_FOR(xccdf_model, model, xccdf_benchmark_get_models(benchmark)) {
		xmlNode *model_node = xmlNewTextChild(root_node, ns_xccdf, BAD_CAST "model", NULL);
		xmlNewProp(model_node, BAD_CAST "system", BAD_CAST xccdf_model_get_system(model));
	}
Beispiel #21
0
static void send_notifies(db1_res_t *result, int did_col, int resource_uri_col, int auth_state_col, int reason_col,
                   int pres_state_col, int content_type_col)
{
	int i;
	char* prev_did= NULL, * curr_did= NULL;
	db_row_t *row;	
	db_val_t *row_vals;
	char* resource_uri;
	str pres_state = {0, 0};
	xmlDocPtr rlmi_doc= NULL;
	xmlNodePtr list_node= NULL, instance_node= NULL, resource_node;
	unsigned int hash_code= 0;
	int size= BUF_REALLOC_SIZE, buf_len= 0;	
	char* buf= NULL, *auth_state= NULL, *boundary_string= NULL;
	str cid = {0,0};
	str content_type= {0, 0};
	int auth_state_flag;
	int chunk_len=0;
	str bstr= {0, 0};
	subs_t* dialog= NULL;
	int len_est = 0;
	int resource_added = 0; /* Flag to indicate that we have added at least one resource */

	/* generate the boundary string */
	boundary_string= generate_string(BOUNDARY_STRING_LEN);
	bstr.len= strlen(boundary_string);
	bstr.s= (char*)pkg_malloc((bstr.len+ 1)* sizeof(char));
	if(bstr.s== NULL)
	{
		ERR_MEM(PKG_MEM_STR);
	}
	memcpy(bstr.s, boundary_string, bstr.len);
	bstr.s[bstr.len]= '\0';

	/* Allocate an initial buffer for the multipart body.
	 * This buffer will be reallocated if neccessary */
	buf= pkg_malloc(size* sizeof(char));
	if(buf== NULL)
	{
		ERR_MEM(PKG_MEM_STR);
	}

	if (dbmode == RLS_DB_ONLY && rls_dbf.start_transaction)
	{
		if (rls_dbf.start_transaction(rls_db, DB_LOCKING_WRITE) < 0)
		{
			LM_ERR("in start_transaction\n");
			goto error;
		}
	}

	LM_DBG("found %d records with updated state\n", result->n);
	for(i= 0; i< result->n; i++)
	{
		row = &result->rows[i];
		row_vals = ROW_VALUES(row);
		
		curr_did=     (char*)row_vals[did_col].val.string_val;
		resource_uri= (char*)row_vals[resource_uri_col].val.string_val;
		auth_state_flag=     row_vals[auth_state_col].val.int_val;
		pres_state.s=   (char*)row_vals[pres_state_col].val.string_val;
		pres_state.len = strlen(pres_state.s);
		trim(&pres_state);
		
		/* If we have moved onto a new resource list Subscribe dialog indentifier, 
		   send a NOTIFY for the previous ID and then drop the existing documents. */
		if(prev_did!= NULL && strcmp(prev_did, curr_did)) 
		{
			if (send_notify(&rlmi_doc, buf, buf_len, bstr, dialog, hash_code))
			{  
				LM_ERR("in send_notify\n");
				goto error;
			}
			len_est = 0;
			pkg_free(dialog);
			dialog= NULL;
		}

		/*if first or different*/
		if(prev_did==NULL || strcmp(prev_did, curr_did)!=0)
		{
			/* Work out a subscription from the did. */
			get_dialog_from_did(curr_did, &dialog, &hash_code);
			if(dialog== NULL)
			{
				prev_did = NULL;
				LM_INFO("Dialog is NULL\n");
				continue;
			}
		
			len_est = create_empty_rlmi_doc(&rlmi_doc, &list_node, &dialog->pres_uri, dialog->version, 0);
			len_est += 2*strlen(boundary_string)+4+102+2+50+strlen(resource_uri)+20;
			buf_len= 0;
			resource_added = 0;

			/* !!!! for now I will include the auth state without checking if 
			 * it has changed - > in future chech if it works */		
		}

		/* add a node in rlmi_doc and if any presence state registered add 
		 * it in the buffer */
		
		resource_node= xmlNewChild(list_node,NULL,BAD_CAST "resource", NULL);
		if(resource_node== NULL)
		{
			LM_ERR("when adding resource child\n");
			goto done;
		}
		xmlNewProp(resource_node, BAD_CAST "uri", BAD_CAST resource_uri);
		len_est += strlen (resource_uri) + 35; /* <resource uri="[uri]"></resource>/r/n */
		resource_added = 1;

		/* there might be more records with the same uri- more instances-
		 * search and add them all */
		
		while(1)
		{
			cid.s= NULL;
			cid.len= 0;
			
			auth_state= get_auth_string(auth_state_flag);
			if(auth_state== NULL)
			{
				LM_ERR("bad authorization status flag\n");
				goto error;
			}	
			len_est += strlen(auth_state) + 38; /* <instance id="12345678" state="[auth_state]" />r/n */

			if(auth_state_flag & ACTIVE_STATE)
			{
				cid.s= generate_cid(resource_uri, strlen(resource_uri));
				cid.len = strlen(cid.s);
				len_est += cid.len + 8; /* cid="[cid]" */
				content_type.s = (char*)row_vals[content_type_col].val.string_val;
				content_type.len = strlen(content_type.s);
				chunk_len = 4 + bstr.len
							+ 35
							+ 16 + cid.len
							+ 18 + content_type.len
							+ 4 + pres_state.len + 8;
				len_est += chunk_len;
			}
			else
			if(auth_state_flag & TERMINATED_STATE)
			{
				len_est += strlen(row_vals[resource_uri_col].val.string_val) + 10; /* reason="[resaon]" */
			}
            
			if (rls_max_notify_body_len > 0 && len_est > rls_max_notify_body_len)
			{
				/* We have a limit on body length set, and we were about to exceed it */
				if (resource_added == 1)
				{
					/* We added at least one resource. */
					LM_DBG("timer_send_notify hit the size limit. len_est = %d\n", len_est);
					if (send_notify(&rlmi_doc, buf, buf_len, bstr, dialog, hash_code))
					{
						LM_ERR("in send_notify\n");
						goto error;
					}
					i --;
				}
				else
				{
					LM_DBG("timer_send_notify hit the size limit. NO RESOURCE ADDED len_est = %d\n", len_est);
				}
				len_est = 0;

				pkg_free(dialog);
				dialog= NULL;
				curr_did=NULL;
				break;
			}

			/* OK, we are happy this will fit */
			instance_node= xmlNewChild(resource_node, NULL, BAD_CAST "instance", NULL);
			if(instance_node== NULL)
			{
				LM_ERR("while adding instance child\n");
				goto error;
			}	

			/* Instance ID should be unique for each instance node
 			   within a resource node.  The same instance ID can be
			   used in different resource nodes.  Instance ID needs
			   to remain the same for each resource instance in
			   future updates.  We can just use a common string
			   here because you will only get multiple instances
			   for a resource when the back-end SUBSCRIBE is forked
			   and pua does not support this.  If/when pua supports
			   forking of the SUBSCRIBEs it sends this will need to
			   be fixed properly. */
			xmlNewProp(instance_node, BAD_CAST "id", 
					BAD_CAST instance_id);
			if(auth_state_flag & ACTIVE_STATE)
			{
				xmlNewProp(instance_node, BAD_CAST "state", BAD_CAST auth_state);
			}
			else
			if(auth_state_flag & TERMINATED_STATE)
			{
				xmlNewProp(instance_node, BAD_CAST "reason",
						BAD_CAST row_vals[resource_uri_col].val.string_val);
			}
			xmlNewProp(instance_node, BAD_CAST "cid", BAD_CAST cid.s);

			/* add in the multipart buffer */
			if(cid.s)
			{
	
				while(buf_len + chunk_len >= size)
				{
					REALLOC_BUF
				}
				buf_len+= sprintf(buf+ buf_len, "--%.*s\r\n", bstr.len,
						bstr.s);
				buf_len+= sprintf(buf+ buf_len,
						"Content-Transfer-Encoding: binary\r\n");
				buf_len+= sprintf(buf+ buf_len, "Content-ID: <%.*s>\r\n",
						cid.len, cid.s);
				buf_len+= sprintf(buf+ buf_len, "Content-Type: %.*s\r\n\r\n",
						content_type.len, content_type.s);
				buf_len+= sprintf(buf+buf_len,"%.*s\r\n\r\n", pres_state.len,
						pres_state.s);
			}

			i++;
			if(i== result->n)
			{
				i--;
				break;
			}
	
			row = &result->rows[i];
			row_vals = ROW_VALUES(row);

			if(strncmp(resource_uri, row_vals[resource_uri_col].val.string_val,
					strlen(resource_uri))
				|| strncmp(curr_did, row_vals[did_col].val.string_val,
					strlen(curr_did)))
			{
				i--;
				break;
			}
			resource_uri= (char*)row_vals[resource_uri_col].val.string_val;
			auth_state_flag=     row_vals[auth_state_col].val.int_val;
			pres_state.s=   (char*)row_vals[pres_state_col].val.string_val;
			pres_state.len= strlen(pres_state.s);
			trim(&pres_state);
		}

		prev_did= curr_did;
	}

	if(rlmi_doc)
	{
		LM_DBG("timer_send_notify at end len_est = %d resource_added = %d\n", len_est, resource_added);
		if (resource_added == 1)
		{
			send_notify(&rlmi_doc, buf, buf_len, bstr, dialog, hash_code);
		}
		if(dialog)
		{
			pkg_free(dialog);
		}
		dialog= NULL;
	}

done:
	if (dbmode == RLS_DB_ONLY && rls_dbf.end_transaction)
	{
		if (rls_dbf.end_transaction(rls_db) < 0)
		{
			LM_ERR("in end_transaction\n");
			goto error;
		}
	}

error:
	if(bstr.s)
		pkg_free(bstr.s);

	if(buf)
		pkg_free(buf);
	if(dialog)
		pkg_free(dialog);

	if (dbmode == RLS_DB_ONLY && rls_dbf.abort_transaction)
	{
		if (rls_dbf.abort_transaction(rls_db) < 0)
			LM_ERR("in abort_transaction\n");
	}

	return;
}
Beispiel #22
0
int
examine_document (xmlNode * node)
{
    /*Examine the parse tree, add semantic attributes and set indicators.*/
    xmlNode *child;
    logMessage(LOG_INFO, "Begin examine_document: node->name=%s", node->name);
    if (node == NULL)
        return 0;
    ud->stack[++ud->top] = set_sem_attr (node);
    if (ud->format_for == utd)
    {
        unsigned char *name = get_sem_name (node);
        if (name[0] != 0)
            xmlNewProp (node, (xmlChar *)"semantics", (xmlChar *)name);
    }
    switch (ud->stack[ud->top])
    {
    case skip:
        pop_sem_stack ();
        return 1;
    case configfile:
        doConfigfile (node);
        break;
    case configstring:
        do_configstring (node);
        break;
    case code:
        ud->has_comp_code = 1;
        break;
    case contentsheader:
        ud->has_contentsheader = 1;
        break;
    case math:
        ud->has_math = 1;
        break;
    case chemistry:
        ud->has_chem = 1;
        break;
    case graphic:
        ud->has_graphics = 1;
        break;
    case music:
        ud->has_music = 1;
        break;
    default:
        break;
    }
    child = node->children;
    while (child)
    {
        switch (child->type)
        {
        case XML_ELEMENT_NODE:
            examine_document (child);
            break;
        case XML_TEXT_NODE:
            examText (child);
            break;
        case XML_CDATA_SECTION_NODE:
            examCdataa (child);
            examine_document (child);
            break;
        default:
            break;
        }
        child = child->next;
    }
    ud->top--;
    return 1;
}
Beispiel #23
0
static xmlNodePtr Value2XMLNode(char *name, ValueStruct *val) {
  xmlNodePtr node;
  xmlNodePtr child;
  int i;

  if (val == NULL) {
    return NULL;
  }
  node = NULL;
  switch (ValueType(val)) {
  case GL_TYPE_INT:
    node = xmlNewNode(NULL, "int");
    xmlNodeAddContent(node, ValueToString(val, NULL));
    break;
  case GL_TYPE_FLOAT:
    node = xmlNewNode(NULL, "float");
    xmlNodeAddContent(node, ValueToString(val, NULL));
    break;
  case GL_TYPE_NUMBER:
    node = xmlNewNode(NULL, "number");
    xmlNodeAddContent(node, ValueToString(val, NULL));
    break;
  case GL_TYPE_BOOL:
    node = xmlNewNode(NULL, "bool");
    xmlNodeAddContent(node, ValueToString(val, NULL));
    break;
  case GL_TYPE_CHAR:
  case GL_TYPE_VARCHAR:
  case GL_TYPE_SYMBOL:
  case GL_TYPE_DBCODE:
  case GL_TYPE_TEXT:
    node = xmlNewNode(NULL, "string");
    xmlNodeAddContent(node, ValueToString(val, NULL));
    break;
  case GL_TYPE_ARRAY:
    node = xmlNewNode(NULL, "array");
    for (i = 0; i < ValueArraySize(val); i++) {
      child = Value2XMLNode(NULL, ValueArrayItem(val, i));
      if (child != NULL) {
        xmlAddChildList(node, child);
      }
    }
    break;
  case GL_TYPE_RECORD:
    node = xmlNewNode(NULL, "record");
    for (i = 0; i < ValueRecordSize(val); i++) {
      if (!strcmp(ValueRecordName(val, i), "mode")) {
        continue;
      }
      child = Value2XMLNode(ValueRecordName(val, i), ValueRecordItem(val, i));
      if (child != NULL) {
        xmlAddChildList(node, child);
      }
    }
    break;
  }
  if (node != NULL && name != NULL && strlen(name) > 0) {
    xmlNewProp(node, "name", name);
  }
  return node;
}