void write_tasks_entries (GUI *appGUI) { gint i; xmlDocPtr doc; xmlNodePtr main_node, node, note_node; xmlAttrPtr attr; gchar temp[BUFFER_SIZE]; GtkTreeIter iter; gboolean done; gchar *priority, *category, *summary, *desc; guint32 due_date_julian, start_date_julian; doc = xmlNewDoc((const xmlChar *) "1.0"); attr = xmlNewDocProp (doc, (const xmlChar *) "encoding", (const xmlChar *) "utf-8"); main_node = xmlNewNode(NULL, (const xmlChar *) TASKS_NAME); xmlDocSetRootElement(doc, main_node); node = xmlNewChild(main_node, NULL, (const xmlChar *) TASKS_CATEGORY_ENTRIES_NAME, (xmlChar *) NULL); i = 0; while (gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(appGUI->opt->tasks_category_store), &iter, NULL, i++)) { gtk_tree_model_get(GTK_TREE_MODEL(appGUI->opt->tasks_category_store), &iter, 0, &category, -1); xmlNewChild(node, NULL, (const xmlChar *) "name", (xmlChar *) category); g_free(category); } node = xmlNewChild(main_node, NULL, (const xmlChar *) TASKS_ENTRIES_NAME, (xmlChar *) NULL); i = 0; while (gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(appGUI->tsk->tasks_list_store), &iter, NULL, i++)) { gtk_tree_model_get(GTK_TREE_MODEL(appGUI->tsk->tasks_list_store), &iter, COLUMN_DONE, &done, COLUMN_DUE_DATE_JULIAN, &due_date_julian, COLUMN_START_DATE_JULIAN, &start_date_julian, COLUMN_PRIORITY, &priority, COLUMN_CATEGORY, &category, COLUMN_SUMMARY, &summary, COLUMN_DESCRIPTION, &desc, -1); note_node = xmlNewChild(node, NULL, (const xmlChar *) "entry", (xmlChar *) NULL); sprintf(temp, "%d", (gint) done); xmlNewChild(note_node, NULL, (const xmlChar *) "status", (xmlChar *) temp); sprintf(temp, "%d", (guint32) due_date_julian); xmlNewChild(note_node, NULL, (const xmlChar *) "due_date", (xmlChar *) temp); sprintf(temp, "%d", (guint32) start_date_julian); xmlNewChild(note_node, NULL, (const xmlChar *) "start_date", (xmlChar *) temp); sprintf(temp, "%d", get_priority_index(gettext(priority))); xmlNewChild(note_node, NULL, (const xmlChar *) "priority", (xmlChar *) temp); g_free (priority); xmlNewChild(note_node, NULL, (const xmlChar *) "category", (xmlChar *) category); g_free (category); xmlNewChild(note_node, NULL, (const xmlChar *) "summary", (xmlChar *) summary); g_free (summary); xmlNewChild(note_node, NULL, (const xmlChar *) "description", (xmlChar *) desc); g_free (desc); } xmlSaveFormatFileEnc(prefs_get_config_filename(TASKS_ENTRIES_FILENAME), doc, "utf-8", 1); xmlFreeDoc(doc); }
str* offline_nbody(str* body) { xmlDocPtr doc= NULL; xmlDocPtr new_doc= NULL; xmlNodePtr node, tuple_node= NULL, status_node; xmlNodePtr root_node, add_node, pres_node; str* new_body; doc= xmlParseMemory(body->s, body->len); if(doc== NULL) { LM_ERR("while parsing xml memory\n"); return NULL; } node= xmlDocGetNodeByName(doc, "basic", NULL); if(node== NULL) { LM_ERR("while extracting basic node\n"); goto error; } xmlNodeSetContent(node, (const unsigned char*)"closed"); tuple_node= xmlDocGetNodeByName(doc, "tuple", NULL); if(tuple_node== NULL) { LM_ERR("while extracting tuple node\n"); goto error; } status_node= xmlDocGetNodeByName(doc, "status", NULL); if(status_node== NULL) { LM_ERR("while extracting tuple node\n"); goto error; } pres_node= xmlDocGetNodeByName(doc, "presence", NULL); if(node== NULL) { LM_ERR("while extracting presence node\n"); goto error; } new_doc = xmlNewDoc(BAD_CAST "1.0"); if(new_doc==0) goto error; root_node= xmlCopyNode(pres_node, 2); if(root_node== NULL) { LM_ERR("while copying node\n"); goto error; } xmlDocSetRootElement(new_doc, root_node); tuple_node= xmlCopyNode(tuple_node, 2); if(tuple_node== NULL) { LM_ERR("while copying node\n"); goto error; } xmlAddChild(root_node, tuple_node); add_node= xmlCopyNode(status_node, 1); if(add_node== NULL) { LM_ERR("while copying node\n"); goto error; } xmlAddChild(tuple_node, add_node); new_body = (str*)pkg_malloc(sizeof(str)); if(new_body == NULL) { ERR_MEM(PKG_MEM_STR); } memset(new_body, 0, sizeof(str)); xmlDocDumpFormatMemory(new_doc,(xmlChar**)(void*)&new_body->s, &new_body->len, 1); xmlFreeDoc(doc); xmlFreeDoc(new_doc); xmlCleanupParser(); xmlMemoryDump(); return new_body; error: if(doc) xmlFreeDoc(doc); if(new_doc) xmlFreeDoc(new_doc); return NULL; }
/** * Send report Data in XML to the client socket that is stored * in the given MonitorService object. */ void monitor_service_write_report(MonitorService *ms) { xmlNodePtr root_node, consumers_node, producers_node; xmlNodePtr buffer_node, events_node; xmlDocPtr doc; xmlChar *xmlbuff; int buffersize; doc = xmlNewDoc(BAD_CAST "1.0"); root_node = xmlNewNode(NULL, BAD_CAST "report"); xmlDocSetRootElement(doc, root_node); // print consumers as XML consumers_node = xmlNewChild(root_node, NULL, BAD_CAST "consumers", NULL); if (consumerList->count == 0) { // no consumers } else { ConsumerService *cs = consumerList->head; while (cs != NULL) { xmlNodePtr consumer; char consumer_data[1024]; consumer = xmlNewChild(consumers_node, NULL, BAD_CAST "consumer", NULL); sprintf(consumer_data, "%d", cs->id); xmlNewChild(consumer, NULL, BAD_CAST "id", BAD_CAST consumer_data); sprintf(consumer_data, "%d", cs->resources_consumed); xmlNewChild(consumer, NULL, BAD_CAST "resources_consumed", BAD_CAST consumer_data); sprintf(consumer_data, "%d", cs->status); xmlNewChild(consumer, NULL, BAD_CAST "status", BAD_CAST consumer_data); cs = cs->next; } } // print producers as XML producers_node = xmlNewChild(root_node, NULL, BAD_CAST "producers", NULL); int p; for (p = 0; p < pidx; p++) { xmlNodePtr producer_node; char producer_data[1024]; producer_node = xmlNewChild(producers_node, NULL, BAD_CAST "producer", NULL); sprintf(producer_data, "%d", producers[p]->id); xmlNewChild(producer_node, NULL, BAD_CAST "id", BAD_CAST producer_data); sprintf(producer_data, "%d", producers[p]->status); xmlNewChild(producer_node, NULL, BAD_CAST "status", BAD_CAST producer_data); sprintf(producer_data, "%d", producers[p]->resources_produced); xmlNewChild(producer_node, NULL, BAD_CAST "count", BAD_CAST producer_data); } buffer_node = xmlNewChild(root_node, NULL, BAD_CAST "buffer", NULL); // print buffer as XML ResourceBuffer *rb; rb = ms->env->bufferp; if (rb->count == 0) { // empty buffer } else { Resource *temp = rb->head; while (temp != NULL) { xmlNodePtr buffer_resource; char resource_data[1024]; buffer_resource = xmlNewChild(buffer_node, NULL, BAD_CAST "resource", NULL); sprintf(resource_data, "%d", temp->id); xmlNewChild(buffer_resource, NULL, BAD_CAST "id", BAD_CAST resource_data); sprintf(resource_data, "%d", temp->produced_by); xmlNewChild(buffer_resource, NULL, BAD_CAST "producer", BAD_CAST resource_data); temp = temp->next; } } events_node = xmlNewChild(root_node, NULL, BAD_CAST "events", NULL); /* * Dump the document to a buffer and print it * for demonstration purposes. */ xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1); write(ms->client_sock, xmlbuff, buffersize); // if (debug.print) printf("wrote to socket:\n%s", (char *) xmlbuff); /* * Free associated memory. */ xmlFree(xmlbuff); xmlFreeDoc(doc); }
static void command_move_clients(client_t *client, source_t *source, int response) { const char *dest_source; source_t *dest; xmlDocPtr doc; xmlNodePtr node; char buf[255]; int parameters_passed = 0; DEBUG0("Doing optional check"); if((COMMAND_OPTIONAL(client, "destination", dest_source))) { parameters_passed = 1; } DEBUG1("Done optional check (%d)", parameters_passed); if (!parameters_passed) { doc = admin_build_sourcelist(source->mount); admin_send_response(doc, client, response, MOVECLIENTS_TRANSFORMED_REQUEST); xmlFreeDoc(doc); return; } dest = source_find_mount (dest_source); if (dest == NULL) { client_send_400 (client, "No such destination"); return; } if (strcmp (dest->mount, source->mount) == 0) { client_send_400 (client, "supplied mountpoints are identical"); return; } if (dest->running == 0 && dest->on_demand == 0) { client_send_400 (client, "Destination not running"); return; } INFO2 ("source is \"%s\", destination is \"%s\"", source->mount, dest->mount); doc = xmlNewDoc (XMLSTR("1.0")); node = xmlNewDocNode(doc, NULL, XMLSTR("iceresponse"), NULL); xmlDocSetRootElement(doc, node); source_move_clients (source, dest); memset(buf, '\000', sizeof(buf)); snprintf (buf, sizeof(buf), "Clients moved from %s to %s", source->mount, dest_source); xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR(buf)); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("1")); admin_send_response(doc, client, response, ADMIN_XSL_RESPONSE); xmlFreeDoc(doc); }
static void command_metadata(client_t *client, source_t *source, int response) { const char *action; const char *song, *title, *artist, *charset; format_plugin_t *plugin; xmlDocPtr doc; xmlNodePtr node; int same_ip = 1; doc = xmlNewDoc (XMLSTR("1.0")); node = xmlNewDocNode (doc, NULL, XMLSTR("iceresponse"), NULL); xmlDocSetRootElement(doc, node); DEBUG0("Got metadata update request"); COMMAND_REQUIRE(client, "mode", action); COMMAND_OPTIONAL(client, "song", song); COMMAND_OPTIONAL(client, "title", title); COMMAND_OPTIONAL(client, "artist", artist); COMMAND_OPTIONAL(client, "charset", charset); if (strcmp (action, "updinfo") != 0) { xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR("No such action")); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("0")); admin_send_response(doc, client, response, ADMIN_XSL_RESPONSE); xmlFreeDoc(doc); return; } plugin = source->format; if (source->client && strcmp (client->con->ip, source->client->con->ip) != 0) if (response == RAW && connection_check_admin_pass (client->parser) == 0) same_ip = 0; if (same_ip && plugin && plugin->set_tag) { if (song) { plugin->set_tag (plugin, "song", song, charset); INFO2 ("Metadata on mountpoint %s changed to \"%s\"", source->mount, song); } else { if (artist && title) { plugin->set_tag (plugin, "title", title, charset); plugin->set_tag (plugin, "artist", artist, charset); INFO3("Metadata on mountpoint %s changed to \"%s - %s\"", source->mount, artist, title); } } /* updates are now done, let them be pushed into the stream */ plugin->set_tag (plugin, NULL, NULL, NULL); } else { xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR("Mountpoint will not accept URL updates")); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("1")); admin_send_response(doc, client, response, ADMIN_XSL_RESPONSE); xmlFreeDoc(doc); return; } xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR("Metadata update successful")); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("1")); admin_send_response(doc, client, response, ADMIN_XSL_RESPONSE); xmlFreeDoc(doc); }
int ploop_store_diskdescriptor(const char *fname, struct ploop_disk_images_data *di) { int i, rc = -1; xmlTextWriterPtr writer = NULL; xmlDocPtr doc = NULL; char tmp[PATH_MAX]; char basedir[PATH_MAX]; FILE *fp = NULL; ploop_log(0, "Storing %s", fname); if (convert_disk_descriptor(di)) return -1; if (di->runtime->xml_fname == NULL) di->runtime->xml_fname = strdup(fname); get_basedir(fname, tmp, sizeof(tmp)); if (tmp[0] == '\0') strcpy(tmp, "./"); if (realpath(tmp, basedir) == NULL) { ploop_err(errno, "Can't resolve %s", tmp); return -1; } doc = xmlNewDoc(BAD_CAST XML_DEFAULT_VERSION); if (doc == NULL) { ploop_err(0, "Error creating xml document tree"); return -1; } /* Create a new XmlWriter for DOM tree, with no compression. */ writer = xmlNewTextWriterTree(doc, NULL, 0); if (writer == NULL) { ploop_err(0, "Error creating xml writer"); goto err; } /* Start the document with the xml default for the version, * encoding ISO 8859-1 and the default for the standalone * declaration. */ rc = xmlTextWriterStartDocument(writer, NULL, NULL, NULL); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterStartDocument"); goto err; } rc = xmlTextWriterStartElement(writer, BAD_CAST "Parallels_disk_image"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterStartDocument"); goto err; } /********************************************* * Disk_Parameters ********************************************/ rc = xmlTextWriterStartElement(writer, BAD_CAST "Disk_Parameters"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Disk_Parameters"); goto err; } rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Disk_size", "%llu", di->size); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Disk_size"); goto err; } if (di->max_delta_size != 0) { rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Max_delta_size", "%llu", di->max_delta_size); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Max_delta_size"); goto err; } } rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Cylinders", "%u", di->cylinders); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Cylinders"); goto err; } rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Heads", "%u", di->heads); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Heads"); goto err; } rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Sectors", "%llu", di->size /(di->cylinders * di->heads)); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Sectors"); goto err; } rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Padding", "%u", 0); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Padding"); goto err; } /* Close Disk_Parameters */ rc = xmlTextWriterEndElement(writer); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterEndElement"); goto err; } /**************************************** * StorageData ****************************************/ rc = xmlTextWriterStartElement(writer, BAD_CAST "StorageData"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter StorageData"); goto err; } /* Start an element named "Storage" as child of StorageData. */ rc = xmlTextWriterStartElement(writer, BAD_CAST "Storage"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Storage"); goto err; } rc = xmlTextWriterWriteElement(writer, BAD_CAST "Start", BAD_CAST "0"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Start"); goto err; } rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "End", "%llu", di->size); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter End"); goto err; } rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Blocksize", "%d", di->blocksize); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Blocksize"); goto err; } if (di->mode == PLOOP_EXPANDED_PREALLOCATED_MODE) { rc = xmlTextWriterWriteElement(writer, BAD_CAST "Preallocated", BAD_CAST "1"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Preallocated"); goto err; } } /**************************************** * Images ****************************************/ for (i = 0; i < di->nimages; i++) { rc = xmlTextWriterStartElement(writer, BAD_CAST "Image"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Image"); goto err; } rc = xmlTextWriterWriteElement(writer, BAD_CAST "GUID", BAD_CAST di->images[i]->guid); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter GUID"); goto err; } rc = xmlTextWriterWriteElement(writer, BAD_CAST "Type", BAD_CAST (di->mode == PLOOP_RAW_MODE ? "Plain" : "Compressed")); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Type"); goto err; } normalize_image_name(basedir, di->images[i]->file, tmp, sizeof(tmp)); rc = xmlTextWriterWriteElement(writer, BAD_CAST "File", BAD_CAST tmp); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter File"); goto err; } /* Close Image */ rc = xmlTextWriterEndElement(writer); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterEndElement"); goto err; } } /* Close Storage */ rc = xmlTextWriterEndElement(writer); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterEndElement"); goto err; } /* Close StorageData. */ rc = xmlTextWriterEndElement(writer); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterEndElement"); goto err; } /**************************************** * Snapshots ****************************************/ rc = xmlTextWriterStartElement(writer, BAD_CAST "Snapshots"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Snapshots"); goto err; } if (di->top_guid != NULL) { rc = xmlTextWriterWriteElement(writer, BAD_CAST "TopGUID", BAD_CAST di->top_guid); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter TopGUID"); goto err; } } /**************************************** * Shot ****************************************/ for (i = 0; i < di->nsnapshots; i++) { rc = xmlTextWriterStartElement(writer, BAD_CAST "Shot"); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Shot"); goto err; } rc = xmlTextWriterWriteElement(writer, BAD_CAST "GUID", BAD_CAST di->snapshots[i]->guid); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterWrite GUID"); goto err; } rc = xmlTextWriterWriteElement(writer, BAD_CAST "ParentGUID", BAD_CAST di->snapshots[i]->parent_guid); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter ParentGUID"); goto err; } if (di->snapshots[i]->temporary) { rc = xmlTextWriterWriteElement(writer, BAD_CAST "Temporary", BAD_CAST ""); if (rc < 0) { ploop_err(0, "Error at xmlTextWriter Temporary"); goto err; } } /* Close Shot */ rc = xmlTextWriterEndElement(writer); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterEndElement"); goto err; } } /* Close Snapshots */ rc = xmlTextWriterEndElement(writer); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterEndElement"); goto err; } /* Close Parallels_disk_image */ rc = xmlTextWriterEndElement(writer); if (rc < 0) { ploop_err(0, "Error at xmlTextWriterEndElement"); goto err; } xmlFreeTextWriter(writer); writer = NULL; snprintf(tmp, sizeof(tmp), "%s.tmp", fname); fp = fopen(tmp, "w+"); if (fp == NULL) { ploop_err(errno, "Can't open %s", tmp); goto err; } rc = xmlDocFormatDump(fp, doc, 1); if (rc < 0) { ploop_err(0, "Error at xmlDocFormatDump %s", tmp); goto err; } rc = fsync(fileno(fp)); if (rc) { ploop_err(errno, "Failed to sync %s", tmp); goto err; } fclose(fp); fp = NULL; rc = rename(tmp, fname); if (rc < 0) { ploop_err(errno, "Can't rename %s to %s", tmp, fname); goto err; } rc = 0; err: if (fp) fclose(fp); if (writer) xmlFreeTextWriter(writer); if (doc) xmlFreeDoc(doc); if (rc) return SYSEXIT_DISKDESCR; return 0; }
static int command_metadata (client_t *client, source_t *source, int response) { const char *song, *title, *artist, *artwork, *charset, *url; format_plugin_t *plugin; xmlDocPtr doc; xmlNodePtr node; int same_ip = 1; doc = xmlNewDoc(XMLSTR("1.0")); node = xmlNewDocNode(doc, NULL, XMLSTR("iceresponse"), NULL); xmlDocSetRootElement(doc, node); DEBUG0("Got metadata update request"); COMMAND_OPTIONAL(client, "song", song); COMMAND_OPTIONAL(client, "title", title); COMMAND_OPTIONAL(client, "artist", artist); COMMAND_OPTIONAL(client, "url", url); COMMAND_OPTIONAL(client, "artwork", artwork); COMMAND_OPTIONAL(client, "charset", charset); plugin = source->format; if (source_running (source)) if (strcmp (client->connection.ip, source->client->connection.ip) != 0) if (response == RAW && connection_check_admin_pass (client->parser) == 0) same_ip = 0; /* Update stream metadata if needed */ if (same_ip) { static const struct { const char *param; const char *stat_name; const char *hdr[3]; } fwd[] = { {"xstreamname", "server_name", {"ice-name", "icy-name", "x-audiocast-name"}}, {"xstreamdesc", "server_description", {"ice-description", "icy-description", "x-audiocast-description"}}, {"xstreamurl", "server_url", {"ice-url", "icy-url", "x-audiocast-url"}}, {"xstreamgenre", "genre", {"ice-genre", "icy-genre", "x-audiocast-genre"}} }; unsigned i; for (i = 0; i < sizeof(fwd) / sizeof(*fwd); i++) { const char *value; unsigned j; COMMAND_OPTIONAL(client, fwd[i].param, value); if (value && *value) { value = auto_recode(value); if (source->format->charset) stats_set_conv (source->stats, fwd[i].stat_name, value, source->format->charset); else stats_set (source->stats, fwd[i].stat_name, value); } else if (value) { stats_set (source->stats, fwd[i].stat_name, NULL); } for (j = 0; j < 3; j++) { if (j == 0 && value && *value) { httpp_setvar(source->format->parser, fwd[i].hdr[j], value); } else if (value && !*value) { httpp_deletevar(source->format->parser, fwd[i].hdr[j]); } } } } do { if (same_ip == 0 || plugin == NULL) break; /* Charset detection (if none specified) */ if (!charset) { const char *r; int len; charset = "UTF8"; #define CCONV(s) \ if (s && (r = auto_recode(s))) { \ len = strlen(r); \ s = alloca(len + 1); \ memcpy((char*)s, r, len + 1); \ } CCONV(title); CCONV(song); CCONV(artist); } /* Now send prepared metadata */ if (artwork) stats_event (source->mount, "artwork", artwork); if (plugin->set_tag) { if (url) { plugin->set_tag (plugin, "url", url, charset); INFO2 ("Metadata url on %s set to \"%s\"", source->mount, url); } if (song) { plugin->set_tag (plugin, "artist", NULL, NULL); plugin->set_tag (plugin, "title", song, charset); INFO2("Metadata song on %s set to \"%s\"", source->mount, song); } if (artist) { plugin->set_tag (plugin, "artist", artist, charset); INFO2 ("Metadata artist on %s changed to \"%s\"", source->mount, artist); } if (title) { plugin->set_tag (plugin, "title", title, charset); INFO2 ("Metadata title on %s changed to \"%s\"", source->mount, title); } /* updates are now done, let them be pushed into the stream */ plugin->set_tag (plugin, NULL, NULL, NULL); } else { break; } thread_mutex_unlock (&source->lock); xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR("Metadata update successful")); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("1")); return admin_send_response(doc, client, response, "response.xsl"); } while (0); thread_mutex_unlock (&source->lock); xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR("Mountpoint will not accept this URL update")); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("1")); return admin_send_response(doc, client, response, "response.xsl"); }
/** * \brief Prepare basic information needed to dynamically load input plugin * specified to be the input of the specified \<collectingProcess\>. This * information is get from the user configuration (given as parameter) and from * internal configuration of the ipfixcol. * * @param[in] collector_node XML node with parameters for the particular * collectingProcess. This is part of user configuration file. * @param[in] internal_cfg internalcfg.xml file. * @return Information about first input plugin for the specified collector, * NULL in case of error. */ struct plugin_xml_conf_list* get_input_plugins(xmlNodePtr collector_node, char *internal_cfg) { int i, j; xmlChar *collector_name; xmlNodePtr auxNode = NULL, children1 = NULL, children2 = NULL, children3 = NULL; xmlXPathContextPtr internal_ctxt = NULL; xmlXPathObjectPtr xpath_obj_suppcolls = NULL, xpath_obj_file = NULL; struct plugin_xml_conf_list *retval = NULL; /* prepare return structure */ retval = (struct plugin_xml_conf_list *) malloc(sizeof(struct plugin_xml_conf_list)); if (retval == NULL) { MSG_ERROR(msg_module, "Memory allocation failed (%s:%d)", __FILE__, __LINE__); return (NULL); } retval->next = NULL; retval->config.xmldata = NULL; retval->config.file = NULL; /* initiate internal config - open xml file, get xmlDoc and prepare xpath context for it */ internal_ctxt = ic_init(BAD_CAST "cesnet-ipfixcol-int", internal_cfg); if (internal_ctxt == NULL) { free(retval); return (NULL); } /* * get the list of supported Collector types which will be used to get * collector information from the user configuration file */ xpath_obj_suppcolls = xmlXPathEvalExpression(BAD_CAST "/cesnet-ipfixcol-int:ipfixcol/cesnet-ipfixcol-int:supportedCollectors/cesnet-ipfixcol-int:name", internal_ctxt); if (xpath_obj_suppcolls == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_suppcolls->nodesetval)) { MSG_ERROR(msg_module, "No list of supported collectors found in internal configuration"); free(retval); retval = NULL; goto cleanup; } /* get paths to libraries implementing plugins from internal configuration */ for (j = 0; j < xpath_obj_suppcolls->nodesetval->nodeNr; j++) { auxNode = get_children(collector_node, xpath_obj_suppcolls->nodesetval->nodeTab[j]->children->content); /* finnish the loop if the collector description found */ if (auxNode) { break; } } /* if we didn't found any valid collector description, we have to quit */ if (!auxNode) { MSG_ERROR(msg_module, "No valid collecting process description found"); free(retval); retval = NULL; goto cleanup; } /* remember node with input plugin parameters */ retval->config.xmldata = xmlNewDoc(BAD_CAST "1.0"); xmlDocSetRootElement(retval->config.xmldata, xmlCopyNode(auxNode, 1)); /* * remember filename of input plugin implementation */ /* we are looking for the node with this name node */ collector_name = xpath_obj_suppcolls->nodesetval->nodeTab[j]->children->content; /* first get list of inputPlugin nodes in internal configuration file */ xpath_obj_file = xmlXPathEvalExpression(BAD_CAST "/cesnet-ipfixcol-int:ipfixcol/cesnet-ipfixcol-int:inputPlugin", internal_ctxt); if (xpath_obj_file == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_file->nodesetval)) { MSG_ERROR(msg_module, "No input plugin definition found in internal configuration"); free(retval); retval = NULL; goto cleanup; } /* and now select the one with required name element */ for (i = 0; i < xpath_obj_file->nodesetval->nodeNr; i++) { children1 = children2 = children3 = xpath_obj_file->nodesetval->nodeTab[i]->children; while (children1) { if ((!strncmp((char *) children1->name, "name", strlen ("name") + 1)) && (!xmlStrncmp(children1->children->content, collector_name, xmlStrlen (collector_name) + 1))) { /* find the processName of specified inputPlugin in internalcfg.xml */ while (children3) { if (!xmlStrncmp(children3->name, BAD_CAST "processName", strlen ("processName") + 1)) { strncpy_safe(retval->config.name, (char *) children3->children->content, 16); } children3 = children3->next; } /* find the file of specified inputPLugin in internalcfg.xml */ while (children2) { if (!xmlStrncmp(children2->name, BAD_CAST "file", strlen("file") + 1)) { retval->config.file = (char *) malloc(sizeof(char) * (strlen((char*) children2->children->content) + 1)); strncpy_safe(retval->config.file, (char *) children2->children->content, strlen((char *) children2->children->content) + 1); goto found_input_plugin_file; } children2 = children2->next; } } children1 = children1->next; } } found_input_plugin_file: if (retval->config.file == NULL) { MSG_ERROR(msg_module, "Unable to load input plugin; specification for '%s' could not be found", collector_name); free(retval); retval = NULL; } cleanup: /* Cleanup of XPath data */ if (xpath_obj_file) { xmlXPathFreeObject(xpath_obj_file); } if (xpath_obj_suppcolls) { xmlXPathFreeObject(xpath_obj_suppcolls); } if (internal_ctxt) { xmlFreeDoc(internal_ctxt->doc); xmlXPathFreeContext(internal_ctxt); } return (retval); }
/** * \brief Prepare basic information needed to dynamically load intermediate plugins. * This information is get from the user configuration (given as parameter) and from * internal configuration of the ipfixmed. * * @param[in] config User XML configuration. * @param[in] internal_cfg internalcfg.xml file. * @return List of information about intermediate plugins, * NULL in case of error. */ struct plugin_xml_conf_list* get_intermediate_plugins(xmlDocPtr config, char *internal_cfg) { int i; xmlXPathContextPtr internal_ctxt = NULL; xmlXPathContextPtr config_ctxt = NULL; xmlXPathObjectPtr xpath_obj_ipinter = NULL; xmlXPathObjectPtr xpath_obj_core = NULL; struct plugin_xml_conf_list *plugins = NULL; struct plugin_xml_conf_list *aux_plugin = NULL; struct plugin_xml_conf_list *last_plugin = NULL; xmlNodePtr node; xmlNodePtr plugin_config_internal; xmlChar *plugin_file = NULL, *thread_name = NULL; xmlDocPtr xmldata = NULL; uint8_t hit = 0; /* initiate internal config - open xml file, get xmlDoc and prepare xpath context for it */ if ((internal_ctxt = ic_init(BAD_CAST "cesnet-ipfixcol-int", internal_cfg)) == NULL) { goto cleanup; } /* get the list of supported intermediate plugins description from internal config */ xpath_obj_ipinter = xmlXPathEvalExpression(BAD_CAST "/cesnet-ipfixcol-int:ipfixcol/cesnet-ipfixcol-int:intermediatePlugin", internal_ctxt); if (xpath_obj_ipinter == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_ipinter->nodesetval)) { MSG_ERROR(msg_module, "No list of supported intermediate formats found in internal configuration"); goto cleanup; } /* create xpath evaluation context of user configuration */ if ((config_ctxt = xmlXPathNewContext(config)) == NULL) { MSG_ERROR(msg_module, "Unable to create XPath context for user configuration (%s:%d)", __FILE__, __LINE__); goto cleanup; } /* register namespace for the context of internal configuration file */ if (xmlXPathRegisterNs(config_ctxt, BAD_CAST "ietf-ipfix", BAD_CAST "urn:ietf:params:xml:ns:yang:ietf-ipfix-psamp") != 0) { MSG_ERROR(msg_module, "Unable to register namespace for user configuration (%s:%d)", __FILE__, __LINE__); goto cleanup; } /* look for <ipfixmedCore> */ xpath_obj_core = xmlXPathEvalExpression(BAD_CAST "/ietf-ipfix:ipfix/ietf-ipfix:intermediatePlugins", config_ctxt); if (xpath_obj_core == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_core->nodesetval)) { MSG_INFO(msg_module, "No intermediate plugin configured in user configuration"); goto cleanup; } node = xpath_obj_core->nodesetval->nodeTab[0]->children; /* Loop over all nodes and skip comments */ while (node != NULL) { /* Skip processing this node in case it's a comment */ if (node->type == XML_COMMENT_NODE) { node = node->next; continue; } plugin_file = NULL; xmldata = NULL; thread_name = NULL; hit = 0; /* find internal configuration for this Intermediate plugin */ for (i = 0; i < xpath_obj_ipinter->nodesetval->nodeNr; i++) { plugin_config_internal = xpath_obj_ipinter->nodesetval->nodeTab[i]->children; while (plugin_config_internal) { if ((!xmlStrncmp(plugin_config_internal->name, BAD_CAST "name", strlen("name") + 1)) && (!xmlStrncmp(plugin_config_internal->children->content, node->name, xmlStrlen(node->name)))) { hit = 1; } if (!xmlStrncmp(plugin_config_internal->name, BAD_CAST "file", strlen("file") + 1)) { plugin_file = xmlNodeListGetString(plugin_config_internal->doc, plugin_config_internal->children, 1); } if (!xmlStrncmp(plugin_config_internal->name, BAD_CAST "threadName", strlen("threadName") + 1)) { thread_name = xmlNodeListGetString(plugin_config_internal->doc, plugin_config_internal->children, 1); } plugin_config_internal = plugin_config_internal->next; } if (!hit) { xmlFree(plugin_file); xmlFree(thread_name); plugin_file = NULL; continue; } break; } if (!plugin_file) { MSG_ERROR(msg_module, "Unable to load intermediate plugin; specification for '%s' could not be found", (char *) node->name); node = node->next; continue; } xmldata = xmlNewDoc(BAD_CAST "1.0"); xmlDocSetRootElement(xmldata, xmlCopyNode(node, 1)); if (!xmldata) { xmlFree(plugin_file); xmlFree(thread_name); node = node->next; continue; } aux_plugin = (struct plugin_xml_conf_list *) malloc(sizeof(*aux_plugin)); if (!aux_plugin) { MSG_ERROR(msg_module, "Memory allocation failed (%s:%d)", __FILE__, __LINE__); goto cleanup; } memset(aux_plugin, 0, sizeof(*aux_plugin)); aux_plugin->config.file = (char *) plugin_file; if (thread_name) { strncpy_safe(aux_plugin->config.name, (char*) thread_name, 16); xmlFree(thread_name); } else { strncpy_safe(aux_plugin->config.name, (char *) node->name, 16); } aux_plugin->config.xmldata = xmldata; if (plugins) { last_plugin->next = aux_plugin; } else { plugins = aux_plugin; } last_plugin = aux_plugin; node = node->next; } /* inform that everything was done but no valid plugin has been found */ if (plugins == NULL) { MSG_WARNING(msg_module, "No valid intermediate plugin specification found for mediator"); } cleanup: /* Cleanup of XPath data */ if (xpath_obj_core) { xmlXPathFreeObject(xpath_obj_core); } if (xpath_obj_ipinter) { xmlXPathFreeObject(xpath_obj_ipinter); } if (config_ctxt) { xmlXPathFreeContext(config_ctxt); } if (internal_ctxt) { xmlFreeDoc(internal_ctxt->doc); xmlXPathFreeContext(internal_ctxt); } return (plugins); }
int EBC_Provider_XchgHiaRequest_H003(AB_PROVIDER *pro, GWEN_HTTP_SESSION *sess, AB_USER *u) { int rv; GWEN_CRYPT_TOKEN *ct; const GWEN_CRYPT_TOKEN_CONTEXT *ctx; uint32_t kid; const GWEN_CRYPT_TOKEN_KEYINFO *cryptKeyInfo=NULL; const GWEN_CRYPT_TOKEN_KEYINFO *authKeyInfo=NULL; xmlNsPtr ns; EB_MSG *msg; const char *userId; const char *partnerId; EB_MSG *mRsp; EB_RC rc; xmlDocPtr doc; xmlNodePtr root_node = NULL; xmlNodePtr node = NULL; /*xmlNodePtr nodeX = NULL;*/ GWEN_BUFFER *mbuf; GWEN_BUFFER *tbuf; const char *s; userId=AB_User_GetUserId(u); partnerId=AB_User_GetCustomerId(u); /* get crypt token and context */ rv=EBC_Provider_MountToken(pro, u, &ct, &ctx); if (rv<0) { DBG_INFO(AQEBICS_LOGDOMAIN, "here (%d)", rv); return rv; } /* get crypt key info */ kid=GWEN_Crypt_Token_Context_GetDecipherKeyId(ctx); if (kid) { cryptKeyInfo=GWEN_Crypt_Token_GetKeyInfo(ct, kid, GWEN_CRYPT_TOKEN_KEYFLAGS_HASMODULUS | GWEN_CRYPT_TOKEN_KEYFLAGS_HASEXPONENT | GWEN_CRYPT_TOKEN_KEYFLAGS_HASKEYVERSION | GWEN_CRYPT_TOKEN_KEYFLAGS_HASKEYNUMBER, 0); if (cryptKeyInfo==NULL) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Crypt key info not found on crypt token"); GWEN_Gui_ProgressLog(0, GWEN_LoggerLevel_Error, I18N("Crypt key info not found on crypt token")); return GWEN_ERROR_NOT_FOUND; } } /* get auth sign key info */ kid=GWEN_Crypt_Token_Context_GetAuthSignKeyId(ctx); if (kid) { authKeyInfo=GWEN_Crypt_Token_GetKeyInfo(ct, kid, GWEN_CRYPT_TOKEN_KEYFLAGS_HASMODULUS | GWEN_CRYPT_TOKEN_KEYFLAGS_HASEXPONENT | GWEN_CRYPT_TOKEN_KEYFLAGS_HASKEYVERSION | GWEN_CRYPT_TOKEN_KEYFLAGS_HASKEYNUMBER, 0); if (authKeyInfo==NULL) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Auth key info not found on crypt token"); GWEN_Gui_ProgressLog(0, GWEN_LoggerLevel_Error, I18N("Auth key info not found on crypt token")); return GWEN_ERROR_NOT_FOUND; } } /* create HIARequestOrderData */ doc=xmlNewDoc(BAD_CAST "1.0"); doc->encoding=xmlCharStrdup("UTF-8"); root_node=xmlNewNode(NULL, BAD_CAST "HIARequestOrderData"); xmlDocSetRootElement(doc, root_node); ns=xmlNewNs(root_node, BAD_CAST "http://www.ebics.org/H003", NULL); assert(ns); ns=xmlNewNs(root_node, BAD_CAST "http://www.w3.org/2000/09/xmldsig#", BAD_CAST "ds"); assert(ns); ns=xmlNewNs(root_node, BAD_CAST "http://www.w3.org/2001/XMLSchema-instance", BAD_CAST "xsi"); xmlNewNsProp(root_node, ns, BAD_CAST "schemaLocation", /* xsi:schemaLocation */ BAD_CAST "http://www.ebics.org/H003 " "http://www.ebics.org/H003/ebics_orders.xsd"); /* create auth key tree */ node=xmlNewChild(root_node, NULL, BAD_CAST "AuthenticationPubKeyInfo", NULL); rv=EB_Key_Info_toXml(authKeyInfo, node); if (rv<0) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Error response: (%d)", rv); xmlFreeDoc(doc); return GWEN_ERROR_INVALID; } xmlNewChild(node, NULL, BAD_CAST "AuthenticationVersion", BAD_CAST "X002"); /* create crypt key tree */ node=xmlNewChild(root_node, NULL, BAD_CAST "EncryptionPubKeyInfo", NULL); rv=EB_Key_Info_toXml(cryptKeyInfo, node); if (rv<0) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Error response: (%d)", rv); xmlFreeDoc(doc); return rv; } xmlNewChild(node, NULL, BAD_CAST "EncryptionVersion", BAD_CAST "E002"); /* store partner id and user id */ node=xmlNewChild(root_node, NULL, BAD_CAST "PartnerID", BAD_CAST partnerId); node=xmlNewChild(root_node, NULL, BAD_CAST "UserID", BAD_CAST userId); /* compress and base64 doc */ mbuf=GWEN_Buffer_new(0, 512, 0, 1); rv=EB_Xml_Compress64Doc(doc, mbuf); if (rv<0) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Error compressing/encoding doc (%d)", rv); xmlFreeDoc(doc); return rv; } xmlFreeDoc(doc); /* create request */ msg=EB_Msg_new(); doc=EB_Msg_GetDoc(msg); root_node=xmlNewNode(NULL, BAD_CAST "ebicsUnsecuredRequest"); xmlDocSetRootElement(doc, root_node); ns=xmlNewNs(root_node, BAD_CAST "http://www.ebics.org/H003", NULL); assert(ns); ns=xmlNewNs(root_node, BAD_CAST "http://www.w3.org/2000/09/xmldsig#", BAD_CAST "ds"); assert(ns); ns=xmlNewNs(root_node, BAD_CAST "http://www.w3.org/2001/XMLSchema-instance", BAD_CAST "xsi"); xmlNewNsProp(root_node, ns, BAD_CAST "schemaLocation", /* xsi:schemaLocation */ BAD_CAST "http://www.ebics.org/H003 " "http://www.ebics.org/H003/ebics_keymgmt_request.xsd"); xmlNewProp(root_node, BAD_CAST "Version", BAD_CAST "H003"); xmlNewProp(root_node, BAD_CAST "Revision", BAD_CAST "1"); /* header */ node=xmlNewChild(root_node, NULL, BAD_CAST "header", NULL); xmlNewProp(node, BAD_CAST "authenticate", BAD_CAST "true"); xmlNewChild(node, NULL, BAD_CAST "static", NULL); xmlNewChild(node, NULL, BAD_CAST "mutable", NULL); /* body */ node=xmlNewChild(root_node, NULL, BAD_CAST "body", NULL); /* fill */ s=EBC_User_GetPeerId(u); if (s) EB_Msg_SetCharValue(msg, "header/static/HostID", s); s=AB_User_GetCustomerId(u); if (s) EB_Msg_SetCharValue(msg, "header/static/PartnerID", s); EB_Msg_SetCharValue(msg, "header/static/UserID", AB_User_GetUserId(u)); EB_Msg_SetCharValue(msg, "header/static/OrderDetails/OrderType", "HIA"); tbuf=GWEN_Buffer_new(0, 16, 0, 1); rv=EBC_Provider_Generate_OrderId(pro, tbuf); if (rv<0) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Error exchanging messages (%d)", rv); GWEN_Buffer_free(tbuf); GWEN_Buffer_free(mbuf); EB_Msg_free(msg); return rv; } EB_Msg_SetCharValue(msg, "header/static/OrderDetails/OrderID", GWEN_Buffer_GetStart(tbuf)); GWEN_Buffer_free(tbuf); EB_Msg_SetCharValue(msg, "header/static/OrderDetails/OrderAttribute", "DZNNN"); EB_Msg_SetCharValue(msg, "header/static/SecurityMedium", "0200"); EB_Msg_SetCharValue(msg, "body/DataTransfer/OrderData", GWEN_Buffer_GetStart(mbuf)); GWEN_Buffer_free(mbuf); /* exchange requests */ rv=EBC_Dialog_ExchangeMessages(sess, msg, &mRsp); if (rv<0 || rv>=300) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Error exchanging messages (%d)", rv); EB_Msg_free(msg); return rv; } EB_Msg_free(msg); /* check response */ assert(mRsp); /* log results */ EBC_Provider_LogRequestResults(pro, mRsp, NULL); rc=EB_Msg_GetResultCode(mRsp); if ((rc & 0xff0000)==0x090000 || (rc & 0xff0000)==0x060000) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Error response: (%06x)", rc); EB_Msg_free(mRsp); return AB_ERROR_SECURITY; } rc=EB_Msg_GetBodyResultCode(mRsp); if (rc) { if ((rc & 0xff0000)==0x090000 || (rc & 0xff0000)==0x060000) { DBG_ERROR(AQEBICS_LOGDOMAIN, "Error response: (%06x)", rc); EB_Msg_free(mRsp); if ((rc & 0xfff00)==0x091300 || (rc & 0xfff00)==0x091200) return AB_ERROR_SECURITY; else return GWEN_ERROR_GENERIC; } } EB_Msg_free(mRsp); /* adjust user status and flags */ DBG_NOTICE(AQEBICS_LOGDOMAIN, "Adjusting user flags"); EBC_User_AddFlags(u, EBC_USER_FLAGS_HIA); if ((EBC_User_GetFlags(u) & (EBC_USER_FLAGS_INI | EBC_USER_FLAGS_HIA)) == (EBC_USER_FLAGS_INI | EBC_USER_FLAGS_HIA)) EBC_User_SetStatus(u, EBC_UserStatus_Init2); else EBC_User_SetStatus(u, EBC_UserStatus_Init1); return 0; }
/** * \brief Prepare basic information needed to dynamically load storage plugins * specified to be the output plugins of the collectingProcess. This information * is get from the user configuration (given as parameter) and from internal * configuration of the ipfixcol. * * @param[in] collector_node XML node with parameters for the particular * collectingProcess. This is part of user configuration file. * @param[in] config User XML configuration. * @param[in] internal_cfg internalcfg.xml file. * @return List of information about storage plugin for the specified collector, * NULL in case of error. */ struct plugin_xml_conf_list* get_storage_plugins(xmlNodePtr collector_node, xmlDocPtr config, char *internal_cfg) { int i, j, k, l; xmlDocPtr collector_doc = NULL, exporter_doc = NULL; xmlNodePtr aux_node = NULL, node_filewriter = NULL; xmlXPathContextPtr internal_ctxt = NULL, collector_ctxt = NULL, config_ctxt = NULL, exporter_ctxt = NULL; xmlXPathObjectPtr xpath_obj_expprocnames = NULL, xpath_obj_expproc = NULL, xpath_obj_destinations = NULL, xpath_obj_plugin_desc = NULL; xmlChar *file_format = (xmlChar *) "", *file_format_inter, *plugin_file, *odid, *thread_name, *single_mgr_txt; struct plugin_xml_conf_list* plugins = NULL, *aux_plugin = NULL; char *odidptr; bool single_mgr; /* initiate internal config - open xml file, get xmlDoc and prepare xpath context for it */ if ((internal_ctxt = ic_init(BAD_CAST "cesnet-ipfixcol-int", internal_cfg)) == NULL) { goto cleanup; } /* get the list of supported storage plugins description (including supported file formats) */ xpath_obj_plugin_desc = xmlXPathEvalExpression(BAD_CAST "/cesnet-ipfixcol-int:ipfixcol/cesnet-ipfixcol-int:storagePlugin", internal_ctxt); if (xpath_obj_plugin_desc == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_plugin_desc->nodesetval)) { MSG_ERROR(msg_module, "No list of supported storage formats found in internal configuration"); goto cleanup; } /* get all <exportingProcess>s from the collector node */ collector_doc = xmlNewDoc (BAD_CAST "1.0"); xmlDocSetRootElement (collector_doc, xmlCopyNode(collector_node, 1)); /* create xpath evaluation context of collector node */ if ((collector_ctxt = xmlXPathNewContext(collector_doc)) == NULL) { MSG_ERROR(msg_module, "Unable to create XPath context for collectingProcess (%s:%d)", __FILE__, __LINE__); goto cleanup; } /* register namespace for the context of internal configuration file */ if (xmlXPathRegisterNs(collector_ctxt, BAD_CAST "ietf-ipfix", BAD_CAST "urn:ietf:params:xml:ns:yang:ietf-ipfix-psamp") != 0) { MSG_ERROR(msg_module, "Unable to register namespace for collectingProcess (%s:%d)", __FILE__, __LINE__); return (NULL); } /* search for <exportingProcess>s nodes defining exporters (including fileWriters) */ xpath_obj_expprocnames = xmlXPathEvalExpression(BAD_CAST "/ietf-ipfix:collectingProcess/ietf-ipfix:exportingProcess", collector_ctxt); if (xpath_obj_expprocnames == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_expprocnames->nodesetval)) { MSG_ERROR(msg_module, "No exportingProcess defined for collectingProcess"); goto cleanup; } /* create xpath evaluation context of user configuration */ if ((config_ctxt = xmlXPathNewContext(config)) == NULL) { MSG_ERROR(msg_module, "Unable to create XPath context for user configuration (%s:%d)", __FILE__, __LINE__); goto cleanup; } /* register namespace for the context of internal configuration file */ if (xmlXPathRegisterNs(config_ctxt, BAD_CAST "ietf-ipfix", BAD_CAST "urn:ietf:params:xml:ns:yang:ietf-ipfix-psamp") != 0) { MSG_ERROR(msg_module, "Unable to register namespace for user configuration (%s:%d)", __FILE__, __LINE__); goto cleanup; } /* now look for <exportingProcess> definition with name(s) specified in <collectingProcess> */ /* first, get all <exportingProcess>es */ xpath_obj_expproc = xmlXPathEvalExpression(BAD_CAST "/ietf-ipfix:ipfix/ietf-ipfix:exportingProcess", config_ctxt); if (xpath_obj_expproc == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_expproc->nodesetval)) { MSG_ERROR(msg_module, "No exportingProcess defined in user configuration"); goto cleanup; } /* and then check them for searching names */ for (i = 0; i < xpath_obj_expprocnames->nodesetval->nodeNr; i++) { for (j = 0; j < xpath_obj_expproc->nodesetval->nodeNr; j++) { aux_node = xpath_obj_expproc->nodesetval->nodeTab[j]->children; while (aux_node) { /* get the <name> element */ if (!xmlStrncmp(aux_node->name, BAD_CAST "name", strlen ("name") + 1)) { /* compare the content of <name> in user config and <name> in the internal config */ if (!xmlStrncmp(xpath_obj_expprocnames->nodesetval->nodeTab[i]->children->content, aux_node->children->content, xmlStrlen(aux_node->children->content) + 1)) { /* we got it! maybe :) */ /* now check if it is a <fileWriter> because all storage plugins ARE <fileWriter>s */ exporter_doc = xmlNewDoc(BAD_CAST "1.0"); xmlDocSetRootElement(exporter_doc, xmlCopyNode (xpath_obj_expproc->nodesetval->nodeTab[j], 1)); /* check if single output data manager is required */ single_mgr = false; single_mgr_txt = get_children_content(xpath_obj_expproc->nodesetval->nodeTab[j], BAD_CAST "singleManager"); if (single_mgr_txt) { single_mgr = !xmlStrcmp(single_mgr_txt, BAD_CAST "yes"); } /* create xpath evaluation context of <exportingProcess> node */ exporter_ctxt = xmlXPathNewContext(exporter_doc); if (exporter_ctxt == NULL) { MSG_ERROR(msg_module, "Unable to create XPath context for exportingProcess (%s:%d)", __FILE__, __LINE__); goto cleanup; } /* register namespace for the context of <exportingProcess> in user config file */ if (xmlXPathRegisterNs(exporter_ctxt, BAD_CAST "ietf-ipfix", BAD_CAST "urn:ietf:params:xml:ns:yang:ietf-ipfix-psamp") != 0) { MSG_ERROR(msg_module, "Unable to register namespace for exportingProcess (%s:%d)", __FILE__, __LINE__); goto cleanup; } /* search for <destination> nodes defining ipfixcol's storage plugins */ xpath_obj_destinations = xmlXPathEvalExpression(BAD_CAST "/ietf-ipfix:exportingProcess/ietf-ipfix:destination", exporter_ctxt); if (xpath_obj_destinations == NULL || xmlXPathNodeSetIsEmpty(xpath_obj_destinations->nodesetval)) { /* no fileWriter found, continue with another exportingProcess */ goto loop_cleanup; } /* now we have a <fileWriter> node with description of storage plugin */ /* but first we have to check that we support this storage plugin type (according to fileFormat) */ for (k = 0; k < xpath_obj_destinations->nodesetval->nodeNr; k++) { plugin_file = NULL; node_filewriter = get_children(xpath_obj_destinations->nodesetval->nodeTab[k], BAD_CAST "fileWriter"); if (node_filewriter == NULL) { /* try next <destination> node */ continue; } for (l = 0; l < xpath_obj_plugin_desc->nodesetval->nodeNr; l++) { file_format_inter = get_children_content(xpath_obj_plugin_desc->nodesetval->nodeTab[l], BAD_CAST "fileFormat"); if (file_format_inter == NULL) { /* this plugin description node is invalid, there is no fileFormat element */ MSG_WARNING(msg_module, "Storage plugin with missing fileFormat detected"); continue; } file_format = get_children_content(node_filewriter, BAD_CAST "fileFormat"); if (file_format == NULL) { /* this fileWriter has no fileFormat element - use default format */ MSG_WARNING(msg_module, "User configuration contains fileWriter without format specification; using %s", DEFAULT_STORAGE_PLUGIN); /* do not allocate memory since we always use strings allocated at other places or static strings */ file_format = BAD_CAST DEFAULT_STORAGE_PLUGIN; } if (!xmlStrncmp(file_format_inter, file_format, xmlStrlen (file_format) + 1)) { /* now we are almost done - prepare an item of the plugin list for return */ plugin_file = get_children_content(xpath_obj_plugin_desc->nodesetval->nodeTab[l], BAD_CAST "file"); if (plugin_file == NULL) { MSG_WARNING(msg_module, "Unable to detect path to storage plugin file for format '%s' in internal configuration", file_format_inter); break; } /* load thread name from internalcfg.xml */ thread_name = get_children_content(xpath_obj_plugin_desc->nodesetval->nodeTab[l], BAD_CAST "threadName"); odid = get_children_content(xpath_obj_destinations->nodesetval->nodeTab[k], BAD_CAST "observationDomainId"); /* prepare plugin info structure for return list */ aux_plugin = (struct plugin_xml_conf_list*) calloc (1, sizeof(struct plugin_xml_conf_list)); if (odid != NULL) { strtol((char*) odid, &odidptr, 10); if (*odidptr == '\0') { aux_plugin->config.observation_domain_id = (char *) malloc (sizeof(char) *(xmlStrlen (odid) + 1)); strncpy_safe(aux_plugin->config.observation_domain_id, (char*) odid, xmlStrlen (odid) + 1); } else { MSG_WARNING(msg_module, "observationDomainId element '%s' not valid; ignoring...", (char*) odid); } } aux_plugin->config.file = (char *) malloc (sizeof(char) *(xmlStrlen (plugin_file) + 1)); strncpy_safe(aux_plugin->config.file, (char *) plugin_file, xmlStrlen (plugin_file) + 1); /* copy thread name to prepared string */ if (thread_name != NULL) { strncpy_safe(aux_plugin->config.name, (char *) thread_name, 16); } aux_plugin->config.xmldata = xmlNewDoc (BAD_CAST "1.0"); xmlDocSetRootElement(aux_plugin->config.xmldata, xmlCopyNode(node_filewriter, 1)); aux_plugin->config.require_single_manager = single_mgr; /* link new plugin item into the return list */ aux_plugin->next = plugins; plugins = aux_plugin; } } if (plugin_file == NULL) { MSG_ERROR(msg_module, "Unable to load storage plugin; specification for fileFormat '%s' could not be found", (char *) file_format); } } /* break while loop to get to another exportingProcess */ break; } } /* go to the next exportingProcess element */ aux_node = aux_node->next; } loop_cleanup: /* free data from previous iteration in case of multiple exportingProcesses (also erased in cleanup) */ xmlXPathFreeObject(xpath_obj_destinations); xpath_obj_destinations = NULL; xmlXPathFreeContext(exporter_ctxt); exporter_ctxt = NULL; xmlFreeDoc(exporter_doc); exporter_doc = NULL; } } /* inform that everything was done but no valid plugin has been found */ if (plugins == NULL) { MSG_WARNING(msg_module, "No valid storage plugin specification for collector found"); } cleanup: /* Cleanup of XPath data */ if (xpath_obj_expproc) { xmlXPathFreeObject(xpath_obj_expproc); } if (xpath_obj_expprocnames) { xmlXPathFreeObject(xpath_obj_expprocnames); } if (xpath_obj_plugin_desc) { xmlXPathFreeObject(xpath_obj_plugin_desc); } if (collector_ctxt) { xmlXPathFreeContext(collector_ctxt); } if (config_ctxt) { xmlXPathFreeContext(config_ctxt); } if (exporter_ctxt) { xmlXPathFreeContext(exporter_ctxt); } if (internal_ctxt) { xmlFreeDoc(internal_ctxt->doc); xmlXPathFreeContext(internal_ctxt); } if (exporter_doc) { xmlFreeDoc(exporter_doc); } if (collector_doc) { xmlFreeDoc(collector_doc); } return (plugins); }
char *createPresenceMsg(int state, char *text, char *to, char *from, int priority){ char *presText = NULL; int buffersize = 0; char *tmp = NULL; int ret = 0; xmlDocPtr doc = NULL; xmlNodePtr root_node = NULL; xmlChar *xmlbuff = NULL; switch(state){ case PRES_CHAT: presText="chat"; break; case PRES_DND: presText="dnd"; break; case PRES_AWAY: presText="away"; break; case PRES_XA: presText="xa"; break; case PRES_UNAVAILABLE: presText="unavailable"; break; } /* rfc3921 says priority has to be bigger than -129 and lower than 128 */ if(priority != 0 && priority >= -128 && priority <= 127){ tmp = malloc(sizeof(size_t)*8+1); if(tmp){ ret=ltostr(priority,10,tmp,sizeof(size_t)*8+1); if(ret != 0) tmp=NULL; } } doc = xmlNewDoc(BAD_CAST "1.0"); root_node = xmlNewNode(NULL, BAD_CAST "presence"); xmlDocSetRootElement(doc, root_node); xmlNewProp(root_node, BAD_CAST "xml:lang", BAD_CAST "en"); if(state == PRES_UNAVAILABLE) xmlNewProp(root_node, BAD_CAST "type", BAD_CAST presText); if(presText && state != PRES_UNAVAILABLE) xmlNewChild(root_node, NULL, BAD_CAST "show", BAD_CAST presText); if(to) if(strlen(to)>0) xmlNewProp(root_node, BAD_CAST "to", BAD_CAST to); if(from) if(strlen(from)>0) xmlNewProp(root_node, BAD_CAST "from", BAD_CAST from); if(text) if(strlen(text)>0 && state != PRES_AVAILABLE) xmlNewChild(root_node, NULL, BAD_CAST "status", BAD_CAST text); if(state != PRES_UNAVAILABLE){ if(tmp){ xmlNewChild(root_node, NULL, BAD_CAST "priority", BAD_CAST tmp); free(tmp); } } xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1); xmlFreeDoc(doc); xmlCleanupParser(); xmlMemoryDump(); return (char *)xmlbuff; }
int saveJobToXML( job *pjob, /* I - pointer to job */ const char *filename) /* I - filename to save to */ { xmlDocPtr doc = NULL; /* document pointer */ xmlNodePtr root_node = NULL; int lenwritten = 0, rc = PBSE_NONE; char log_buf[LOCAL_LOG_BUF_SIZE]; if ((doc = xmlNewDoc((const xmlChar*) "1.0"))) { root_node = xmlNewNode(NULL, (const xmlChar*) JOB_TAG); xmlDocSetRootElement(doc, root_node); add_fix_fields(&root_node, (const job*)pjob); add_union_fields(&root_node, (const job*)pjob); if (add_attributes(&root_node, pjob)) { xmlFreeDoc(doc); return -1; } #ifdef PBS_MOM add_mom_fields(&root_node, (const job*)pjob); #endif /* PBS_MOM */ #ifndef PBS_MOM lock_ss(); #endif /* !defined PBS_MOM */ lenwritten = xmlSaveFormatFileEnc(filename, doc, NULL, 1); #ifndef PBS_MOM unlock_ss(); #endif /* !defined PBS_MOM */ xmlFreeDoc(doc); } else { snprintf(log_buf, sizeof(log_buf), "could not create a new xml document"); log_event( PBSEVENT_JOB, PBS_EVENTCLASS_JOB, pjob->ji_qs.ji_jobid, log_buf); rc = -1; } if (lenwritten <= 0) { snprintf(log_buf, sizeof(log_buf), "failed writing job to the xml file %s", filename); log_event( PBSEVENT_JOB, PBS_EVENTCLASS_JOB, pjob->ji_qs.ji_jobid, log_buf); rc = -1; } return(rc); } /* saveJobToXML */
static int rest_add_feed(mtev_http_rest_closure_t *restc, int npats, char **pats) { mtev_http_session_ctx *ctx = restc->http_ctx; xmlXPathObjectPtr pobj = NULL; xmlDocPtr doc = NULL, indoc = NULL; xmlNodePtr node, root; acceptor_closure_t *ac = restc->ac; int error_code = 500, complete = 0, mask = 0, rv; const char *error = "internal error", *logname; char *name, *copy_from; mtev_log_stream_t feed; const char *jpath_with_sub; char jlogpath[PATH_MAX], *cp; jlog_ctx *jctx = NULL; jlog_id chkpt; if(npats != 0) goto error; indoc = rest_get_xml_upload(restc, &mask, &complete); if(!complete) return mask; if(indoc == NULL) { error = "xml parse error"; goto error; } if(!mtev_hash_retr_str(ac->config, "log_transit_feed_name", strlen("log_transit_feed_name"), &logname)) { goto error; } feed = mtev_log_stream_find("feed"); if(!feed) { error = "couldn't find feed"; goto error; } jpath_with_sub = mtev_log_stream_get_path(feed); strlcpy(jlogpath, jpath_with_sub, sizeof(jlogpath)); cp = strchr(jlogpath, '('); if(cp) *cp = '\0'; node = xmlDocGetRootElement(indoc); name = (char*)xmlGetProp(node, (xmlChar*)"name"); copy_from = (char*)xmlGetProp(node, (xmlChar*)"checkpoint_copy"); jctx = jlog_new(jlogpath); if (!jctx) { error = "couldn't open logpath"; goto error; } if (!jlog_get_checkpoint(jctx, name, &chkpt)) { error = "subscriber already exists, can't add"; goto error; } if (copy_from) { rv = jlog_ctx_add_subscriber_copy_checkpoint(jctx, name, copy_from); } else { rv = jlog_ctx_add_subscriber(jctx, name, JLOG_END); } if (rv == -1) { error = "couldn't add subscriber"; goto error; } mtev_http_response_ok(restc->http_ctx, "text/xml"); mtev_http_response_end(restc->http_ctx); goto cleanup; error: mtev_http_response_standard(ctx, error_code, "ERROR", "text/xml"); doc = xmlNewDoc((xmlChar *)"1.0"); root = xmlNewDocNode(doc, NULL, (xmlChar *)"error", NULL); xmlDocSetRootElement(doc, root); xmlNodeAddContent(root, (xmlChar *)error); mtev_http_response_xml(ctx, doc); mtev_http_response_end(ctx); cleanup: if (jctx) { jlog_ctx_close(jctx); } if(pobj) xmlXPathFreeObject(pobj); if(doc) xmlFreeDoc(doc); return 0; }
static void xslt_yelp_document (xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr comp) { YelpTransform *transform; YelpTransformPrivate *priv; xmlChar *page_id = NULL; gchar *temp; xmlChar *page_buf; gint buf_size; xsltStylesheetPtr style = NULL; const char *old_outfile; xmlDocPtr new_doc = NULL; xmlDocPtr old_doc; xmlNodePtr old_insert; debug_print (DB_FUNCTION, "entering\n"); if (ctxt->state == XSLT_STATE_STOPPED) return; if (!ctxt || !node || !inst || !comp) return; transform = YELP_TRANSFORM (ctxt->_private); priv = GET_PRIV (transform); page_id = xsltEvalAttrValueTemplate (ctxt, inst, (const xmlChar *) "href", NULL); if (page_id == NULL || *page_id == '\0') { if (page_id) xmlFree (page_id); else xsltTransformError (ctxt, NULL, inst, _("No href attribute found on " "yelp:document\n")); /* FIXME: put a real error here */ goto done; } debug_print (DB_ARG, " page_id = \"%s\"\n", page_id); old_outfile = ctxt->outputFile; old_doc = ctxt->output; old_insert = ctxt->insert; ctxt->outputFile = (const char *) page_id; style = xsltNewStylesheet (); if (style == NULL) { xsltTransformError (ctxt, NULL, inst, _("Out of memory")); goto done; } style->omitXmlDeclaration = TRUE; new_doc = xmlNewDoc (BAD_CAST "1.0"); new_doc->charset = XML_CHAR_ENCODING_UTF8; new_doc->dict = ctxt->dict; xmlDictReference (new_doc->dict); ctxt->output = new_doc; ctxt->insert = (xmlNodePtr) new_doc; xsltApplyOneTemplate (ctxt, node, inst->children, NULL, NULL); xsltSaveResultToString (&page_buf, &buf_size, new_doc, style); ctxt->outputFile = old_outfile; ctxt->output = old_doc; ctxt->insert = old_insert; g_mutex_lock (&priv->mutex); temp = g_strdup ((gchar *) page_id); xmlFree (page_id); g_async_queue_push (priv->queue, g_strdup ((gchar *) temp)); g_hash_table_insert (priv->chunks, temp, page_buf); g_object_ref (transform); g_idle_add ((GSourceFunc) transform_chunk, transform); g_mutex_unlock (&priv->mutex); done: if (new_doc) xmlFreeDoc (new_doc); if (style) xsltFreeStylesheet (style); }
static int command_metadata (client_t *client, source_t *source, int response) { const char *song, *title, *artist, *artwork, *charset, *url; format_plugin_t *plugin; xmlDocPtr doc; xmlNodePtr node; int same_ip = 1; doc = xmlNewDoc(XMLSTR("1.0")); node = xmlNewDocNode(doc, NULL, XMLSTR("iceresponse"), NULL); xmlDocSetRootElement(doc, node); DEBUG0("Got metadata update request"); COMMAND_OPTIONAL(client, "song", song); COMMAND_OPTIONAL(client, "title", title); COMMAND_OPTIONAL(client, "artist", artist); COMMAND_OPTIONAL(client, "url", url); COMMAND_OPTIONAL(client, "artwork", artwork); COMMAND_OPTIONAL(client, "charset", charset); plugin = source->format; if (source_running (source)) if (strcmp (client->connection.ip, source->client->connection.ip) != 0) if (response == RAW && connection_check_admin_pass (client->parser) == 0) same_ip = 0; do { if (same_ip == 0 || plugin == NULL) break; if (artwork) stats_event (source->mount, "artwork", artwork); if (plugin->set_tag) { if (url) { plugin->set_tag (plugin, "url", url, charset); INFO2 ("Metadata url on %s set to \"%s\"", source->mount, url); } if (song) { plugin->set_tag (plugin, "artist", NULL, NULL); plugin->set_tag (plugin, "title", song, charset); INFO2("Metadata song on %s set to \"%s\"", source->mount, song); } if (artist) { plugin->set_tag (plugin, "artist", artist, charset); INFO2 ("Metadata artist on %s changed to \"%s\"", source->mount, artist); } if (title) { plugin->set_tag (plugin, "title", title, charset); INFO2 ("Metadata title on %s changed to \"%s\"", source->mount, title); } /* updates are now done, let them be pushed into the stream */ plugin->set_tag (plugin, NULL, NULL, charset); } else { break; } thread_rwlock_unlock (&source->lock); xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR("Metadata update successful")); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("1")); return admin_send_response(doc, client, response, "response.xsl"); } while (0); INFO1 ("Metadata on mountpoint %s prevented", source->mount); thread_rwlock_unlock (&source->lock); xmlNewChild(node, NULL, XMLSTR("message"), XMLSTR("Mountpoint will not accept this URL update")); xmlNewChild(node, NULL, XMLSTR("return"), XMLSTR("1")); return admin_send_response(doc, client, response, "response.xsl"); }
void mtx_gauge_face_export_xml(MtxGaugeFace * gauge, const gchar * filename) { guint i = 0; xmlDocPtr doc = NULL; /* document pointer */ xmlNodePtr root_node = NULL;/* node pointers */ xmlDtdPtr dtd = NULL; /* DTD pointer */ MtxDispatchHelper *helper = NULL; MtxXMLFuncs * xml_funcs = NULL; MtxGaugeFacePrivate *priv = NULL; g_return_if_fail(gauge); g_return_if_fail(filename); priv = MTX_GAUGE_FACE_GET_PRIVATE(gauge); g_return_if_fail(priv); LIBXML_TEST_VERSION; /* * Creates a new document, a node and set it as a root node */ doc = xmlNewDoc(BAD_CAST "1.0"); root_node = xmlNewNode(NULL, BAD_CAST "gauge"); xmlDocSetRootElement(doc, root_node); /* * Creates a DTD declaration. Isn't mandatory. */ dtd = xmlCreateIntSubset(doc, BAD_CAST "gauge", NULL, BAD_CAST "mtxgauge.dtd"); /* Create a helper struct o bind data to for to * trim up the XML export functions. */ helper = g_new0(MtxDispatchHelper, 1); helper->gauge = gauge; helper->root_node = root_node; /** For each element, get the varname, the pointer to the memory * where the data is stored in the current gauge structure, and call * the export function defined in the xml_funcs struct passing in the * helper struct so that the generic export functions can get the * key names right and the memory addresses right. It looks confusing * but it works great. See gauge-xml.h for the static struct binding * keynames to import/export generic handler functions */ for (i=0;i<priv->xmlfunc_array->len;i++) { xml_funcs = g_array_index(priv->xmlfunc_array,MtxXMLFuncs *, i); if (!xml_funcs) continue; helper->element_name = xml_funcs->varname; helper->src = (gpointer)g_object_get_data(G_OBJECT(gauge),xml_funcs->varname); if (xml_funcs->export_func) xml_funcs->export_func(helper); } g_free(helper); /* */ xmlSaveFormatFileEnc(filename, 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(); if (priv->xml_filename) g_free(priv->xml_filename); priv->xml_filename = g_strdup(filename); }
/* 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 root_node = NULL, node = NULL, node1 = NULL;/* node pointers */ xmlDtdPtr dtd = NULL; /* DTD pointer */ char buff[256]; int i, j; LIBXML_TEST_VERSION; /* * Creates a new document, a node and set it as a root node */ doc = xmlNewDoc(BAD_CAST "1.0"); root_node = xmlNewNode(NULL, BAD_CAST "root"); xmlDocSetRootElement(doc, root_node); /* * Creates a DTD declaration. Isn't mandatory. */ dtd = xmlCreateIntSubset(doc, BAD_CAST "root", NULL, BAD_CAST "tree2.dtd"); /* * xmlNewChild() creates a new node, which is "attached" as child node * of root_node node. */ xmlNewChild(root_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(root_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(root_node, NULL, BAD_CAST "node3", BAD_CAST "this node has attributes"); xmlNewProp(node, BAD_CAST "attribute", BAD_CAST "yes"); 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(root_node, node); /* * A simple loop that "automates" nodes creation */ for (i = 5; i < 7; i++) { sprintf(buff, "node%d", i); node = xmlNewChild(root_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); }
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; }
static gboolean infd_note_plugin_text_session_write(InfdStorage* storage, InfSession* session, const gchar* path, gpointer user_data, GError** error) { InfUserTable* table; InfTextBuffer* buffer; InfTextBufferIter* iter; xmlNodePtr root; xmlNodePtr buffer_node; xmlNodePtr segment_node; guint author; gchar* content; gsize bytes; FILE* stream; xmlDocPtr doc; xmlErrorPtr xmlerror; g_assert(INFD_IS_FILESYSTEM_STORAGE(storage)); g_assert(INF_TEXT_IS_SESSION(session)); /* Open stream before exporting buffer to XML so possible errors are * catched earlier. */ stream = infd_filesystem_storage_open( INFD_FILESYSTEM_STORAGE(storage), "InfText", path, "w", error ); if(stream == NULL) return FALSE; root = xmlNewNode(NULL, (const xmlChar*)"inf-text-session"); buffer = INF_TEXT_BUFFER(inf_session_get_buffer(session)); table = inf_session_get_user_table(session); inf_user_table_foreach_user( table, infd_note_plugin_text_session_write_foreach_user_func, root ); buffer_node = xmlNewChild(root, NULL, (const xmlChar*)"buffer", NULL); iter = inf_text_buffer_create_iter(buffer); if(iter != NULL) { do { author = inf_text_buffer_iter_get_author(buffer, iter); content = inf_text_buffer_iter_get_text(buffer, iter); bytes = inf_text_buffer_iter_get_bytes(buffer, iter); segment_node = xmlNewChild( buffer_node, NULL, (const xmlChar*)"segment", NULL ); inf_xml_util_set_attribute_uint(segment_node, "author", author); inf_xml_util_add_child_text(segment_node, content, bytes); g_free(content); } while(inf_text_buffer_iter_next(buffer, iter)); inf_text_buffer_destroy_iter(buffer, iter); } doc = xmlNewDoc((const xmlChar*)"1.0"); xmlDocSetRootElement(doc, root); if(xmlDocFormatDump(stream, doc, 1) == -1) { xmlerror = xmlGetLastError(); fclose(stream); xmlFreeDoc(doc); g_set_error( error, g_quark_from_static_string("LIBXML2_OUTPUT_ERROR"), xmlerror->code, "%s", xmlerror->message ); return FALSE; } fclose(stream); xmlFreeDoc(doc); return TRUE; }
/* build an XML doc containing information about currently running sources. * If a mountpoint is passed then that source will not be added to the XML * doc even if the source is running */ xmlDocPtr admin_build_sourcelist (const char *mount) { avl_node *node; source_t *source; xmlNodePtr xmlnode, srcnode; xmlDocPtr doc; char buf[22]; time_t now = time(NULL); doc = xmlNewDoc (XMLSTR("1.0")); xmlnode = xmlNewDocNode (doc, NULL, XMLSTR("icestats"), NULL); xmlDocSetRootElement(doc, xmlnode); if (mount) { xmlNewChild (xmlnode, NULL, XMLSTR("current_source"), XMLSTR(mount)); } node = avl_get_first(global.source_tree); while(node) { source = (source_t *)node->key; if (mount && strcmp (mount, source->mount) == 0) { node = avl_get_next (node); continue; } if (source->running || source->on_demand) { ice_config_t *config; mount_proxy *mountinfo; srcnode = xmlNewChild(xmlnode, NULL, XMLSTR("source"), NULL); xmlSetProp(srcnode, XMLSTR("mount"), XMLSTR(source->mount)); xmlNewChild(srcnode, NULL, XMLSTR("fallback"), (source->fallback_mount != NULL)? XMLSTR(source->fallback_mount):XMLSTR("")); snprintf (buf, sizeof(buf), "%lu", source->listeners); xmlNewChild(srcnode, NULL, XMLSTR("listeners"), XMLSTR(buf)); config = config_get_config(); mountinfo = config_find_mount (config, source->mount); if (mountinfo && mountinfo->auth) { xmlNewChild(srcnode, NULL, XMLSTR("authenticator"), XMLSTR(mountinfo->auth->type)); } config_release_config(); if (source->running) { if (source->client) { snprintf (buf, sizeof(buf), "%lu", (unsigned long)(now - source->con->con_time)); xmlNewChild (srcnode, NULL, XMLSTR("Connected"), XMLSTR(buf)); } xmlNewChild (srcnode, NULL, XMLSTR("content-type"), XMLSTR(source->format->contenttype)); } } node = avl_get_next(node); } return(doc); }
int bzrtp_getSelfZID(bzrtpContext_t *context, uint8_t selfZID[12]) { if (context == NULL) { return ZRTP_ZIDCACHE_INVALID_CONTEXT; } /* load the cache buffer and parse it to an xml doc. TODO: lock it as we may write it */ if (context->zrtpCallbacks.bzrtp_loadCache != NULL) { uint8_t *cacheStringBuffer; uint32_t cacheStringLength; context->zrtpCallbacks.bzrtp_loadCache(context->channelContext[0]->clientData, &cacheStringBuffer, &cacheStringLength); context->cacheBuffer = xmlParseDoc(cacheStringBuffer); free(cacheStringBuffer); } else { /* we are running cacheless, return a random number */ bzrtpCrypto_getRandom(context->RNGContext, selfZID, 12); return 0; } uint8_t *selfZidHex = NULL; if (context->cacheBuffer != NULL ) { /* there is a cache, try to find our ZID */ xmlNodePtr cur = xmlDocGetRootElement(context->cacheBuffer); /* if we found a root element, parse its children node */ if (cur!=NULL) { cur = cur->xmlChildrenNode; } while (cur!=NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"selfZID"))){ /* self ZID found, extract it */ selfZidHex = xmlNodeListGetString(context->cacheBuffer, cur->xmlChildrenNode, 1); /* convert it from hexa string to bytes string */ bzrtp_strToUint8(selfZID, selfZidHex, strlen((char *)selfZidHex)); break; } cur = cur->next; } } /* if we didn't found anything in cache, or we have no cache at all: generate ZID, cache string and write it to file */ if (selfZidHex==NULL) { /* generate a random ZID */ bzrtpCrypto_getRandom(context->RNGContext, selfZID, 12); /* convert it to an Hexa String */ uint8_t newZidHex[25]; bzrtp_int8ToStr(newZidHex, selfZID, 12); newZidHex[24] = '\0'; /* the string must be null terminated for libxml2 to add it correctly in the element */ xmlFree(context->cacheBuffer); /* Create a new xml doc */ context->cacheBuffer = xmlNewDoc((const xmlChar *)"1.0"); /* root tag is "cache" */ xmlNodePtr rootNode = xmlNewDocNode(context->cacheBuffer, NULL, (const xmlChar *)"cache", NULL); xmlDocSetRootElement(context->cacheBuffer, rootNode); /* add the ZID child */ xmlNewTextChild(rootNode, NULL, (const xmlChar *)"selfZID", newZidHex); /* write the cache file and unlock it(TODO)*/ bzrtp_writeCache(context); } /* TODO unlock the cache */ xmlFree(selfZidHex); return 0; }
static void command_manageauth(client_t *client, source_t *source, int response) { xmlDocPtr doc; xmlNodePtr node, srcnode, msgnode; const char *action = NULL; const char *username = NULL; char *message = NULL; int ret = AUTH_OK; ice_config_t *config = config_get_config (); mount_proxy *mountinfo = config_find_mount (config, source->mount); do { if (mountinfo == NULL || mountinfo->auth == NULL) { WARN1 ("manage auth request for %s but no facility available", source->mount); break; } COMMAND_OPTIONAL(client, "action", action); COMMAND_OPTIONAL (client, "username", username); if (action == NULL) action = "list"; if (!strcmp(action, "add")) { const char *password = NULL; COMMAND_OPTIONAL (client, "password", password); if (username == NULL || password == NULL) { WARN1 ("manage auth request add for %s but no user/pass", source->mount); break; } ret = mountinfo->auth->adduser(mountinfo->auth, username, password); if (ret == AUTH_FAILED) { message = strdup("User add failed - check the icecast error log"); } if (ret == AUTH_USERADDED) { message = strdup("User added"); } if (ret == AUTH_USEREXISTS) { message = strdup("User already exists - not added"); } } if (!strcmp(action, "delete")) { if (username == NULL) { WARN1 ("manage auth request delete for %s but no username", source->mount); break; } ret = mountinfo->auth->deleteuser(mountinfo->auth, username); if (ret == AUTH_FAILED) { message = strdup("User delete failed - check the icecast error log"); } if (ret == AUTH_USERDELETED) { message = strdup("User deleted"); } } doc = xmlNewDoc (XMLSTR("1.0")); node = xmlNewDocNode(doc, NULL, XMLSTR("icestats"), NULL); srcnode = xmlNewChild(node, NULL, XMLSTR("source"), NULL); xmlSetProp(srcnode, XMLSTR("mount"), XMLSTR(source->mount)); if (message) { msgnode = xmlNewChild(node, NULL, XMLSTR("iceresponse"), NULL); xmlNewChild(msgnode, NULL, XMLSTR("message"), XMLSTR(message)); } xmlDocSetRootElement(doc, node); if (mountinfo && mountinfo->auth && mountinfo->auth->listuser) mountinfo->auth->listuser (mountinfo->auth, srcnode); config_release_config (); admin_send_response(doc, client, response, MANAGEAUTH_TRANSFORMED_REQUEST); free (message); xmlFreeDoc(doc); return; } while (0); config_release_config (); client_send_400 (client, "missing parameter"); }
void filterSaveXml(const char *docname,uint8_t silent) { xmlDocPtr xdoc; xmlNodePtr node; xmlAttrPtr attr; char tmpstring[1024]; VF_FILTERS tag; int max; UNUSED_ARG(silent); if( ! (xdoc = xmlNewDoc((const xmlChar *)"1.0")) ) {printf("Problem creating xml doc\n"); return ;} if( ! (xdoc->children = xmlNewNode(NULL,(xmlChar *)"filters")) ) { xmlFreeDoc(xdoc); xdoc = NULL; return ; } // we add # of filteras as attribute to the first children max=nb_active_filter; if(max) max--; sprintf(tmpstring,"%d",max); attr=xmlNewProp(xdoc->children,(xmlChar *)"FilterNumber",(xmlChar *)tmpstring); if(max) for(uint32_t curFilter=1;curFilter<nb_active_filter;curFilter++) { // for each filter we create a new node node= xmlNewChild(xdoc->children,NULL,(xmlChar *)"Filter",NULL ); tag=videofilters[curFilter].tag; // and fill-up some informations sprintf(tmpstring,"%d",tag); attr=xmlNewProp(node,(xmlChar *)"Tag",(xmlChar *)tmpstring); attr=xmlNewProp(node,(xmlChar *)"Conf",(xmlChar *)videofilters[curFilter].filter->printConf()); // now we create a child containing the config CONFcouple *setup; if( videofilters[curFilter].filter->getCoupledConf(&setup)) { // we create a new child parameters with # of parameter as attribute xmlNodePtr nodeConf; //,tmpnode; // xmlAttrPtr attrConf; char *nm,*val; nodeConf= xmlNewChild(node,NULL,(xmlChar *)"Parameters",NULL ); sprintf(tmpstring,"%"LU"",setup->getNumber()); xmlNewProp(nodeConf,(xmlChar *)"Number",(xmlChar *)tmpstring); // and write each attribute for(uint32_t i=0;i<setup->getNumber();i++) { ADM_assert(setup->getEntry(i,&nm,&val)); xmlNewChild(nodeConf,NULL,(xmlChar *)nm,(xmlChar *)val ); } delete setup; } } xmlSetDocCompressMode(xdoc,0); // we want pure text qxmlSaveFormatFile(docname,xdoc,1); xmlFreeDoc(xdoc); return ; }
void export_dash_xml(gchar * filename) { GtkWidget *dash = NULL; GList *children = NULL; GtkFixedChild *child = NULL; gchar * tmpbuf = NULL; guint i = 0; xmlDocPtr doc = NULL; /* document pointer */ xmlNodePtr root_node = NULL;/* node pointers */ xmlNodePtr node = NULL;/* node pointers */ xmlDtdPtr dtd = NULL; /* DTD pointer */ GtkTreeIter parent; GtkTreeIter iter; GtkTreeModel *model = NULL; gboolean state = FALSE; gchar * iname = NULL; gchar ** vector = NULL; GtkAllocation allocation; g_return_if_fail(filename); doc = xmlNewDoc(BAD_CAST "1.0"); root_node = xmlNewNode(NULL,BAD_CAST "dashboard"); xmlDocSetRootElement(doc,root_node); /* * Creates a DTD declaration. Isn't mandatory. */ dtd = xmlCreateIntSubset(doc, BAD_CAST "dashboard", NULL, BAD_CAST "mtxdashboard.dtd"); dash = GTK_WIDGET(gtk_builder_get_object(toplevel,"dashboard")); gtk_widget_get_allocation(dash, &allocation); node = xmlNewChild(root_node,NULL,BAD_CAST "dash_geometry", NULL); generic_xml_gint_export(node,"width",&allocation.width); generic_xml_gint_export(node,"height",&allocation.height); children = GTK_FIXED(dash)->children; for(i=0;i<g_list_length(GTK_FIXED(dash)->children);i++) { child = g_list_nth_data(GTK_FIXED(dash)->children,i); node = xmlNewChild(root_node,NULL,BAD_CAST "gauge", NULL); gtk_widget_get_allocation(child->widget, &allocation); generic_xml_gint_export(node,"width",&allocation.width); generic_xml_gint_export(node,"height",&allocation.height); generic_xml_gint_export(node,"x_offset",&child->x); generic_xml_gint_export(node,"y_offset",&child->y); tmpbuf = g_strrstr(mtx_gauge_face_get_xml_filename(MTX_GAUGE_FACE(child->widget)),"Gauges"); vector = g_strsplit(tmpbuf,PSEP,2); generic_xml_gchar_export(node,"gauge_xml_name",&vector[1]); g_strfreev(vector); state = gtk_combo_box_get_active_iter(GTK_COMBO_BOX(OBJ_GET((child->widget),"combo")),&iter); model = gtk_combo_box_get_model(GTK_COMBO_BOX(OBJ_GET((child->widget),"combo"))); gtk_tree_model_get(model,&iter,DATASOURCE_COL,&iname,-1); generic_xml_gchar_export(node,"datasource",&iname); } xmlSaveFormatFileEnc(filename, 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 ; }
static DiaSvgRenderer * new_svg_renderer(DiagramData *data, const char *filename) { DiaSvgRenderer *renderer; SvgRenderer *svg_renderer; FILE *file; gchar buf[512]; time_t time_now; Rectangle *extent; const char *name; xmlDtdPtr dtd; file = g_fopen(filename, "w"); if (file==NULL) { message_error(_("Can't open output file %s: %s\n"), dia_message_filename(filename), strerror(errno)); return NULL; } fclose(file); /* we need access to our base object */ renderer = DIA_SVG_RENDERER (g_object_new(SVG_TYPE_RENDERER, NULL)); renderer->filename = g_strdup(filename); renderer->dash_length = 1.0; renderer->dot_length = 0.2; renderer->saved_line_style = LINESTYLE_SOLID; /* apparently most svg readers don't like small values, especially not in the viewBox attribute */ renderer->scale = 20.0; /* set up the root node */ renderer->doc = xmlNewDoc((const xmlChar *)"1.0"); renderer->doc->encoding = xmlStrdup((const xmlChar *)"UTF-8"); renderer->doc->standalone = FALSE; dtd = xmlCreateIntSubset(renderer->doc, (const xmlChar *)"svg", (const xmlChar *)"-//W3C//DTD SVG 1.0//EN", (const xmlChar *)"http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd"); xmlAddChild((xmlNodePtr) renderer->doc, (xmlNodePtr) dtd); renderer->root = xmlNewDocNode(renderer->doc, NULL, (const xmlChar *)"svg", NULL); xmlAddSibling(renderer->doc->children, (xmlNodePtr) renderer->root); /* add namespaces to make strict parsers happy, e.g. Firefox */ svg_renderer = SVG_RENDERER (renderer); /* set the extents of the SVG document */ extent = &data->extents; g_snprintf(buf, sizeof(buf), "%dcm", (int)ceil((extent->right - extent->left))); xmlSetProp(renderer->root, (const xmlChar *)"width", (xmlChar *) buf); g_snprintf(buf, sizeof(buf), "%dcm", (int)ceil((extent->bottom - extent->top))); xmlSetProp(renderer->root, (const xmlChar *)"height", (xmlChar *) buf); g_snprintf(buf, sizeof(buf), "%d %d %d %d", (int)floor(extent->left * renderer->scale), (int)floor(extent->top * renderer->scale), (int)ceil((extent->right - extent->left) * renderer->scale), (int)ceil((extent->bottom - extent->top) * renderer->scale)); xmlSetProp(renderer->root, (const xmlChar *)"viewBox", (xmlChar *) buf); xmlSetProp(renderer->root,(const xmlChar *)"xmlns", (const xmlChar *)"http://www.w3.org/2000/svg"); xmlSetProp(renderer->root,(const xmlChar *)"xmlns", (const xmlChar *)"http://www.w3.org/2000/svg"); xmlSetProp(renderer->root,(const xmlChar *)"xmlns:xlink", (const xmlChar *)"http://www.w3.org/1999/xlink"); time_now = time(NULL); name = g_get_user_name(); #if 0 /* some comments at the top of the file ... */ xmlAddChild(renderer->root, xmlNewText("\n")); xmlAddChild(renderer->root, xmlNewComment("Dia-Version: "VERSION)); xmlAddChild(renderer->root, xmlNewText("\n")); g_snprintf(buf, sizeof(buf), "File: %s", dia->filename); xmlAddChild(renderer->root, xmlNewComment(buf)); xmlAddChild(renderer->root, xmlNewText("\n")); g_snprintf(buf, sizeof(buf), "Date: %s", ctime(&time_now)); buf[strlen(buf)-1] = '\0'; /* remove the trailing new line */ xmlAddChild(renderer->root, xmlNewComment(buf)); xmlAddChild(renderer->root, xmlNewText("\n")); g_snprintf(buf, sizeof(buf), "For: %s", name); xmlAddChild(renderer->root, xmlNewComment(buf)); xmlAddChild(renderer->root, xmlNewText("\n\n")); xmlNewChild(renderer->root, NULL, "title", dia->filename); #endif return renderer; }
static str* build_pidf(char *uri, char *id, enum purple_publish_basic basic, enum purple_publish_activity activity, const char *note) { LM_DBG("build pidf : %s, %d, %d, %s\n", uri, basic, activity, note); str* body = NULL; xmlDocPtr doc = NULL; xmlNodePtr root_node = NULL, status_node = NULL; xmlNodePtr tuple_node = NULL, basic_node = NULL; xmlNodePtr person_node = NULL, activities_node = NULL; xmlNsPtr pidf_ns, dm_ns, rpid_ns, cipid_ns; char* entity = NULL; entity = (char*)pkg_malloc(7+ strlen(uri)*sizeof(char)); if(entity == NULL) { LM_ERR("no more memory\n"); goto error; } strcpy(entity, "pres:"); memcpy(entity+5, uri+4, strlen(uri)-4); entity[1+ strlen(uri)] = '\0'; LM_DBG("building pidf for entity: %s\n", entity); doc = xmlNewDoc(BAD_CAST "1.0"); if(doc == NULL) { LM_ERR("allocating new xml doc\n"); goto error; } root_node = xmlNewNode(NULL, BAD_CAST "presence"); if(root_node == 0) { LM_ERR("extracting presence node\n"); goto error; } xmlDocSetRootElement(doc, root_node); xmlNewProp(root_node, BAD_CAST "entity", BAD_CAST entity); pidf_ns = xmlNewNs(root_node, BAD_CAST "urn:ietf:params:xml:ns:pidf", NULL); dm_ns = xmlNewNs(root_node, BAD_CAST "urn:ietf:params:xml:ns:pidf:data-model", BAD_CAST "dm"); rpid_ns = xmlNewNs(root_node, BAD_CAST "urn:ietf:params:xml:ns:pidf:rpid", BAD_CAST "rpid"); cipid_ns = xmlNewNs(root_node, BAD_CAST "urn:ietf:params:xml:ns:pidf:cipid", BAD_CAST "c"); tuple_node = xmlNewChild(root_node, NULL, BAD_CAST "tuple", NULL); if( tuple_node == NULL) { LM_ERR("while adding child\n"); goto error; } xmlNewProp(tuple_node, BAD_CAST "id", BAD_CAST id); status_node = xmlNewChild(tuple_node, pidf_ns, BAD_CAST "status", NULL); if( status_node ==NULL) { LM_ERR("while adding child\n"); goto error; } switch (basic) { case PURPLE_BASIC_OPEN: basic_node = xmlNewChild(status_node, pidf_ns, BAD_CAST "basic", BAD_CAST "open"); if(basic_node == NULL) { LM_ERR("while adding child\n"); goto error; } break; case PURPLE_BASIC_CLOSED: basic_node = xmlNewChild(status_node, pidf_ns, BAD_CAST "basic", BAD_CAST "closed") ; if(basic_node == NULL) { LM_ERR("while adding child\n"); goto error; } break; default: break; } person_node = xmlNewChild(root_node, dm_ns, BAD_CAST "person", NULL); if (person_node == NULL) { LM_ERR("while adding child\n"); goto error; } xmlNewProp(person_node, BAD_CAST "id", BAD_CAST id); activities_node = xmlNewChild(person_node, rpid_ns, BAD_CAST "activities", NULL); if (activities_node == NULL) { LM_ERR("while adding child\n"); goto error; } switch (activity) { case PURPLE_ACTIVITY_AVAILABLE: xmlNewChild(activities_node, rpid_ns, BAD_CAST "unknown", NULL); xmlNewChild(person_node, dm_ns, BAD_CAST "note", (note != NULL) ? BAD_CAST note : NULL); break; case PURPLE_ACTIVITY_BUSY: xmlNewChild(activities_node, rpid_ns, BAD_CAST "busy", NULL); xmlNewChild(activities_node, rpid_ns, BAD_CAST "unknown", NULL); if (note == NULL) xmlNewChild(person_node, dm_ns, BAD_CAST "note", BAD_CAST "Busy"); break; case PURPLE_ACTIVITY_AWAY: xmlNewChild(activities_node, rpid_ns, BAD_CAST "away", NULL); xmlNewChild(activities_node, rpid_ns, BAD_CAST "unknown", NULL); if (note == NULL) xmlNewChild(person_node, dm_ns, BAD_CAST "note", BAD_CAST "Away"); break; default: break; } if (note != NULL) xmlNewChild(person_node, dm_ns, BAD_CAST "note", BAD_CAST note); body = (str*)pkg_malloc(sizeof(str)); if(body == NULL) { LM_ERR("no more memory\n"); goto error; } xmlDocDumpFormatMemory(doc, (xmlChar**)(void*)&body->s, &body->len, 1); if(entity) pkg_free(entity); xmlFreeDoc(doc); return body; error: if(entity) pkg_free(entity); if(body) { if(body->s) { xmlFree(body->s); } pkg_free(body); } if(doc) { xmlFreeDoc(doc); } return NULL; }
int main(int argc, char **argv) { ssize_t size = 1; char c[1]; char f[LINE_MAX] = ""; /* field */ int lines = 0; int quot = 0; int len = 0; int flds = 0; xmlNodePtr n = NULL; xmlNodePtr nrow = NULL; xmlNodePtr nval = NULL; xmlDocPtr doc; char *xml; char *fieldname; xmlNodePtr nfld[5] = { NULL, NULL, NULL, NULL, NULL }; int i; int lspace = 0; char *amount; check_args(argc, argv); /* open file for reading, if not already */ if (fd == 0) { fd = open(filename, O_RDONLY); if (fd == -1) { perror("open()"); _exit(EXIT_FAILURE); } } /* start building xml document */ doc = xmlNewDoc(BAD_CAST "1.0"); n = xmlNewNode(NULL, BAD_CAST "resources"); xmlDocSetRootElement(doc, n); /* read file one character at a time */ while (size == 1) { size = read(fd, c, 1); if ((size == 1) && (flds == 1) && (len == 1)) nrow = xmlNewNode(NULL, BAD_CAST "bank"); if ((size == 0) && (f[len] != '\n')) c[0] = '\n'; if (c[0] == '"') { /* start/end quoted field */ quot = (len == 0) ? 1 : 0; } else if ((((quot == 0) && (c[0] == ',')) || (c[0] == '\n') || (size == 0)) && (len > 0)) { /* unquoted comma or newline - end field, start new */ fieldname = getfieldname(flds); if (fieldname != NULL) { if (lspace > 0) { /* we have a name and data */ fixupField(&f, bank, flds); /* HBOS hack */ if ((bank == 0) && ((flds == 1) || (flds == 4))) { if (flds == 1) { amount = strdup(f); } else if (flds == 4) { /* change debit to credit */ nval = xmlNewText(BAD_CAST amount); if (strcmp(f, "D") == 0) { nfld[3] = NULL; nfld[4] = xmlNewNode(NULL, BAD_CAST "credit"); xmlAddChild(nfld[4], nval); } else { nfld[3] = xmlNewNode(NULL, BAD_CAST "debit"); nfld[4] = NULL; xmlAddChild(nfld[3], nval); } free(amount); } } else { /* store fields in remapped order */ nfld[map[flds]] = xmlNewNode(NULL, BAD_CAST fieldname); nval = xmlNewText(BAD_CAST f); xmlAddChild(nfld[map[flds]], nval); } } else { nfld[map[flds]] = NULL; } free(fieldname); } flds++; if (c[0] == '\n') { lines++; flds = 0; /* append the fields in mapped order to row */ for (i=0; i<=4; i++) { if (nfld[i] != NULL) xmlAddChild(nrow, nfld[i]); } /* now append the row */ xmlAddChild(n, nrow); nrow = NULL; } len = 0; lspace = 0; } else { f[len] = c[0]; len++; if (c[0] != ' ') lspace++; /* keep track of last non-whitespace char */ if (len > LINE_MAX) { fprintf(stderr, "Line length overrun\n"); _exit(EXIT_FAILURE); } f[len] = '\0'; } } close(fd); /* if last line of the file didn't end in a newline, append it now */ if (nrow != NULL ) xmlAddChild(n, nrow); flattenxml(doc, &xml, 1); printf("%s", xml); xmlFreeDoc(doc); xmlCleanupParser(); free(xml); return 0; }
/* {{{ proto DOMDocument dom_domimplementation_create_document(string namespaceURI, string qualifiedName, DOMDocumentType doctype); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocument Since: DOM Level 2 */ PHP_METHOD(domimplementation, createDocument) { zval *node = NULL, *rv = NULL; xmlDoc *docp; xmlNode *nodep; xmlDtdPtr doctype = NULL; xmlNsPtr nsptr = NULL; int ret, uri_len = 0, name_len = 0, errorcode = 0; char *uri = NULL, *name = NULL; char *prefix = NULL, *localname = NULL; dom_object *doctobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ssO", &uri, &uri_len, &name, &name_len, &node, dom_documenttype_class_entry) == FAILURE) { return; } if (node != NULL) { DOM_GET_OBJ(doctype, node, xmlDtdPtr, doctobj); if (doctype->type == XML_DOCUMENT_TYPE_NODE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid DocumentType object"); RETURN_FALSE; } if (doctype->doc != NULL) { php_dom_throw_error(WRONG_DOCUMENT_ERR, 1 TSRMLS_CC); RETURN_FALSE; } } else { doctobj = NULL; } if (name_len > 0) { errorcode = dom_check_qname(name, &localname, &prefix, 1, name_len); if (errorcode == 0 && uri_len > 0 && ((nsptr = xmlNewNs(NULL, uri, prefix)) == NULL)) { errorcode = NAMESPACE_ERR; } } if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (localname != NULL) { xmlFree(localname); } php_dom_throw_error(errorcode, 1 TSRMLS_CC); RETURN_FALSE; } /* currently letting libxml2 set the version string */ docp = xmlNewDoc(NULL); if (!docp) { if (localname != NULL) { xmlFree(localname); } RETURN_FALSE; } if (doctype != NULL) { docp->intSubset = doctype; doctype->parent = docp; doctype->doc = docp; docp->children = (xmlNodePtr) doctype; docp->last = (xmlNodePtr) doctype; } if (localname != NULL) { nodep = xmlNewDocNode (docp, nsptr, localname, NULL); if (!nodep) { if (doctype != NULL) { docp->intSubset = NULL; doctype->parent = NULL; doctype->doc = NULL; docp->children = NULL; docp->last = NULL; } xmlFreeDoc(docp); xmlFree(localname); /* Need some type of error here */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unexpected Error"); RETURN_FALSE; } nodep->nsDef = nsptr; xmlDocSetRootElement(docp, nodep); xmlFree(localname); } DOM_RET_OBJ(rv, (xmlNodePtr) docp, &ret, NULL); if (doctobj != NULL) { doctobj->document = ((dom_object *)((php_libxml_node_ptr *)docp->_private)->_private)->document; php_libxml_increment_doc_ref((php_libxml_node_object *)doctobj, docp TSRMLS_CC); } }
int create_lost_req(xmlNode* location, char* service, loc_fmt d_loc_fmt, str* lost_req){ xmlDocPtr doc= NULL; xmlNodePtr root_node; xmlNodePtr loc_node = NULL, loc_copy=NULL; char * id = "1234"; char * profile; xmlChar * req_body = NULL; int req_len = 0; if(d_loc_fmt == ERR_LOC){ ERROR_LOG("cannot use location with errornous format\n"); goto error; } profile = map_profile[d_loc_fmt]; /* creating the xml doc for the LoST message*/ doc= xmlNewDoc(BAD_CAST "1.0"); if(doc== NULL){ ERROR_LOG("when creating new xml doc\n"); goto error; } root_node = xmlNewNode(NULL, BAD_CAST LOST_FIND_SERVICE_CMD); if(root_node==0){ ERROR_LOG("when adding new node %s\n", LOST_FIND_SERVICE_CMD); goto error; } xmlDocSetRootElement(doc, root_node); if(!xmlNewNs(root_node, BAD_CAST LOST_NS_HREF, NULL)){ ERROR_LOG("could not add the namespace %s to the root node\n", LOST_NS_HREF); goto error; } loc_node = xmlNewNode(NULL, BAD_CAST LOST_LOCATION_NODE); if(!loc_node){ ERROR_LOG("when creating new node %s\n", LOST_LOCATION_NODE); goto error; } if(!xmlNewProp(loc_node, BAD_CAST LOST_ID_PROP , BAD_CAST id)){ ERROR_LOG("could not add the property %s\n", LOST_ID_PROP); goto error; } if(!xmlNewProp(loc_node, BAD_CAST LOST_PROFILE_PROP , BAD_CAST profile)){ ERROR_LOG("could not add the property %s\n", LOST_ID_PROP); goto error; } //do a recursive copy of the location information loc_copy = xmlCopyNode(location, 1); if(!loc_copy){ ERROR_LOG("could not duplicate the location information node\n"); goto error; } if(!xmlAddChild(loc_node, loc_copy)){ ERROR_LOG("could not add the location information to the location node\n"); goto error; } loc_copy = NULL; if(!xmlAddChild(root_node, loc_node)){ ERROR_LOG("could not add the %s node to root\n", LOST_LOCATION_NODE); goto error; } loc_node = NULL; if(!xmlNewChild(root_node, NULL, BAD_CAST LOST_SERVICE_NODE, BAD_CAST service)){ ERROR_LOG("could not add the %s node to root\n", LOST_SERVICE_NODE); goto error; } //print_element_names(root_node); xmlDocDumpFormatMemoryEnc(doc, &req_body, &req_len, LOST_XML_ENC, 1); lost_req->s = (char*) req_body; lost_req->len = req_len; if(!lost_req->s || !lost_req->len){ ERROR_LOG("could not output the xml document\n"); goto error; } //DEBUG_LOG("lost request: %.*s\n", lost_req->len, lost_req->s); xmlFreeDoc(doc); return 0; error: if(loc_node) xmlFreeNode(loc_node); if(loc_copy) xmlFreeNode(loc_copy); if(doc) xmlFreeDoc(doc); return 1; }