Exemple #1
0
int xml_count( 	const char	*xmlBuf,
       		const char	*elementName, 
		int		elementNumber,
		const char	*childName,
       		const char	*childValue, 
       		int		*iret )
/************************************************************************
 * xml_count                                                            *
 *                                                                      *
 * This function returns the number of specified elements that are      *
 * contained in an xml file.  						*
 * 									*
 * The input element is actually part of an XPath expression.  This     *
 * expression by default assumes the searched for element is a child    *
 * of the root node of the xml document (/root/elementName).  The root  *
 * node should not be specified in elementName, however.  This routine  *
 * will prepend "[slash]*[slash]" to the beginning of the element name, *
 * thus always matching the root.					* 
 *                                                                      *
 * See additional documentation and usage examples of this and other    *
 * cgemlib/xml library routines at:					*
 *									*
 *	$NAWIPS/doc/Prog_guid/xml/cgemlibxml.sxw.			*
 *									*
 * Valid Inputs:							*
 *                                                                      *
 * int xml_count( xmlBuf, elementName, elementNumber, childName,        *
 *                childValue, iret ) 					*
 *                                                                      *
 * Input parameters:                                                    *
 *      *xmlBuf		const char	buffer containing xml document  *
 *	*elementName	const char	element name to be counted	* 
 *	elementNumber	int		number of element or 0 for none *
 *	*childName	const char	optional child element name     *
 *	*childValue 	const char	optional element value or NULL  *
 *                                                                      *
 * Output parameters:                                                   *
 *      *iret           int             Return code                     *
 *                                        0 = normal                    *
 *					  1 = non-fatal xpath error     *
 *					       see Valid Inputs above   *
 *                                       -1 = bad xmlBuf pointer (NULL) *
 *                                       -2 = bufSize <= 0              *
 *					 -3 = fatal error creating      *
 *					       XPath expression		*
 *                                       -4 = unable to allocate memory *
 *					 -5 = xpath context error	*
 *					 -6 = error parsing xmlBuf	*
 *                                       -7 = xpath context error       *
 *                                       -8 = xpath expression error    *
 *                                       -9 = node list is empty        *
 * Return:								*
 *			int		number of instances of the 	*
 *					  specified element in xmlBuf  	*
 **                                                                     *
 * Log:                                                                 *
 * E. Safford/SAIC	11/05	initial coding (adapted from tutorial   *
 *				 by Aleksey Sanin, Copyright 2004, used *
 *                               under GNU Free Documentation License)  *
 ***********************************************************************/
{
    int 		count      = 0, ier = 0, bufSize = 0;

    xmlChar		*xpathExpr = NULL;
    xmlDocPtr 		doc        = NULL; 
    xmlXPathObjectPtr 	xpathObj   = NULL; 
    xmlNodeSetPtr	nodes      = NULL;
 /*--------------------------------------------------------------------*/

    *iret   = 0;

    /*
     *  Sanity check on input buffer
     */ 
    if( xmlBuf == NULL ) {
	*iret = -1;
	return( count );
    }

    bufSize = strlen( xmlBuf );
    if( bufSize <= 0 ) {
	*iret = -2;
	return( count );
    }


    /* 
     * Init libxml 
     */
    xmlInitParser();

    /*
     * Construct the XPath expression
     */
    xml_makeXpathExpr( elementName, elementNumber, childName, 0, childValue,
    			&xpathExpr, &ier );
    if( ier < 0 ) {
	*iret = -3;
	G_FREE( xpathExpr, xmlChar );
	return( count );
    }
    else if( ier > 0 ) {
	*iret = 1;
    }


    xml_executeXpathExpr( xmlBuf, bufSize, xpathExpr, &doc, &xpathObj, &ier );

    if( ier < 0 ) {
        *iret = -8;
    } 
    else {
        /* 
         * Process results 
         */
        nodes = xpathObj->nodesetval;
        count = nodes->nodeNr;
    }


    /* 
     * Shutdown libxml and cleanup
     */
    G_FREE( xpathExpr, xmlChar ); 
    xmlXPathFreeObject(xpathObj); 
    xmlFreeDoc(doc);   

    xmlCleanupParser();


    return( count );
}
bool Outfits::loadFromXml(const std::string& datadir)
{
	std::string filename = datadir + "outfits.xml";

	xmlDocPtr doc = xmlParseFile(filename.c_str());
	if(doc){
		xmlNodePtr root, p;
		root = xmlDocGetRootElement(doc);

		if(xmlStrcmp(root->name,(const xmlChar*)"outfits") != 0){
			xmlFreeDoc(doc);
			std::cout << "Warning: outfits.xml not found, using defaults." << std::endl;
			return true;
		}

		p = root->children;

		while(p){
			if(xmlStrcmp(p->name, (const xmlChar*)"outfit") == 0){
				int32_t intValue;
				std::string strValue;
				if(readXMLInteger(p, "id", intValue)){
					Outfit outfit;
					outfit.outfitId = intValue;
					outfit.isDefault = true;

					if(readXMLInteger(p, "premium", intValue)){
						outfit.isPremium = (intValue == 1);
					}

					if(readXMLInteger(p, "default", intValue)){
						outfit.isDefault = (intValue == 1);
					}

					xmlNodePtr pchild = p->children;
					while(pchild){
						if(xmlStrcmp(pchild->name, (const xmlChar*)"list") == 0){
							if(readXMLInteger(pchild, "looktype", intValue)){
								outfit.lookType = intValue;
							}
							else{
								std::cout << "Missing looktype for an outfit." << std::endl;
								pchild = pchild->next;
								continue;
							}

							if(readXMLInteger(pchild, "addons", intValue)){
								outfit.addons = intValue;
							}

							if(readXMLString(pchild, "name", strValue)){
								outfit.name = strValue;
							}

							if(readXMLString(pchild, "type", strValue)){
								PlayerSex_t playersex = PLAYERSEX_LAST;

								if(asLowerCaseString(strValue) == "female"){
									playersex = PLAYERSEX_FEMALE;
								}
								else if(asLowerCaseString(strValue) == "male"){
									playersex = PLAYERSEX_MALE;
								}
								else if(asLowerCaseString(strValue) == "femalegm"){
									playersex = PLAYERSEX_FEMALE_GAMEMASTER;
								}
								else if(asLowerCaseString(strValue) == "malegm"){
									playersex = PLAYERSEX_MALE_GAMEMASTER;
								}
								else if(asLowerCaseString(strValue) == "femalecm"){
									playersex = PLAYERSEX_FEMALE_MANAGER;
								}
								else if(asLowerCaseString(strValue) == "malecm"){
									playersex = PLAYERSEX_MALE_MANAGER;
								}
								else if(asLowerCaseString(strValue) == "femalegod"){
									playersex = PLAYERSEX_FEMALE_GOD;
								}
								else if(asLowerCaseString(strValue) == "malegod"){
									playersex = PLAYERSEX_MALE_GOD;
								}
								else{
									std::cout << "Invalid player sex " << strValue << " for an outfit." << std::endl;
									pchild = pchild->next;
									continue;
								}

								allOutfits.push_back(outfit);
								outfitMaps[playersex][outfit.outfitId] = outfit;
							}
							else{
								std::cout << "Missing playersex for an outfit." << std::endl;
								pchild = pchild->next;
								continue;
							}
						}

						pchild = pchild->next;
					}
				}
				else{
					std::cout << "Missing outfit id." << std::endl;
				}
			}
			p = p->next;
		}
		xmlFreeDoc(doc);
	}
	return true;
}
Exemple #3
0
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);
}
Exemple #4
0
/*函数功能:读取配置文件
 *函数参数:配置文件的路径
 *函数返回值:无
 */
void CConfig::ReadConfig(const char cPath[])
{
	char szIp[MAX_LEN] = {0};
	char szProtocol[MAX_LEN] = {0};
	char szPort[MAX_LEN] = {0};
	
	xmlDocPtr Doc;
	int ret = CConfig::XmlParserFile(&Doc, cPath);//打开配置文件
	if(FAULT == ret)
	{
		cout << "open file error\n" << endl;
		return ;
	}

	xmlNodePtr Cur, Tc, Tcc;
	CConfig::GetRoot(Doc, &Cur);//获取根节点
	char cszBuf[128];

	xmlChar *key;

	ZXDEBUG();
	if(Cur != NULL)
	{
		bzero(szIp, MAX_LEN);
		bzero(szProtocol, MAX_LEN);
		bzero(szPort, MAX_LEN);
		Cur = Cur->xmlChildrenNode;//二级节点NetPort、Mainframe
		while(Cur != NULL)
		{
			ZXDEBUG();
			if((!xmlStrcmp(Cur->name, (const xmlChar *)"NetPort")))
			{
				if(0 == CConfig::GetNodeValue(Doc, Cur, &key, (char *)"NetPort"))
				{
					strcpy(this->m_cpNetPort, (const char *)key);
        			xmlFree(key);
				}
			}
			Tc = Cur->xmlChildrenNode;//三级节点Ip、协议、端口
			while(NULL != Tc)
			{
				if((!xmlStrcmp(Tc->name, (const xmlChar *)"Ip")))	//获取Ip
				{
					if(0 == CConfig::GetNodeValue(Doc, Tc, &key, (char *)"Ip"))
					{
						sprintf(szIp, "host %s", (char *)key);
	        			xmlFree(key);
					}
				}
				else if((!xmlStrcmp(Tc->name, (const xmlChar *)"Ports")))//获取端口信息
				{
					Tcc = Tc->xmlChildrenNode;
					while(NULL != Tcc)
					{
						ZXDEBUG();
						if((!xmlStrcmp(Tcc->name, (const xmlChar *)"Port")))
						{
							if(0 == CConfig::GetNodeValue(Doc, Tcc, &key, (char *)"Port"))
							{
								if('\0' == szPort[0])
								{
									sprintf(szPort, "port %s", (char *)key);
								}
								else
								{
									sprintf(cszBuf, " or %s", key);
									strcat(szPort, cszBuf);
								}
			        			xmlFree(key);
							}
						}
						
						Tcc = Tcc->next;
					}
				}
				else if((!xmlStrcmp(Tc->name, (const xmlChar *)"Protocols")))//获取协议信息
				{
					Tcc = Tc->xmlChildrenNode;
					while(NULL != Tcc)
					{
						ZXDEBUG();
						if((!xmlStrcmp(Tcc->name, (const xmlChar *)"Protocol")))
						{
							if(0 == CConfig::GetNodeValue(Doc, Tcc, &key, (char *)"Protocol"))
							{
								if('\0' == szProtocol[0])
								{
									strcpy(szProtocol, (const char *)key);
								}
								else
								{
									sprintf(cszBuf, " or %s", key);
									strcat(szProtocol, cszBuf);
								}
			        			xmlFree(key);
							}
						}
						Tcc = Tcc->next;
					}
				
				}
				Tc = Tc->next;
			}
			if((!xmlStrcmp(Cur->name, (const xmlChar *)"Mainframe")))
			{
				this->StructureFilter(szProtocol, szIp, szPort);//调用函数构造过滤器
			}
			Cur = Cur->next;
		}
		
	}
				
	xmlFreeDoc(Doc);//关闭打开的配置文件,并释放其占用的资源
	xmlCleanupParser();
}
silvia_issuescript::silvia_issuescript(const std::string file_name)
{
	is_valid = false;

	////////////////////////////////////////////////////////////////////
	// Read the issuing script
	////////////////////////////////////////////////////////////////////
	xmlDocPtr xmldoc = xmlParseFile(file_name.c_str());
	
	if (xmldoc == NULL)
	{
		return;
	}
	
	// Check integrity
	xmlNodePtr root_elem = xmlDocGetRootElement(xmldoc);
	
	if ((root_elem == NULL) || (xmlStrcasecmp(root_elem->name, (const xmlChar*) "SilviaIssuingScript") != 0))
	{
		xmlFreeDoc(xmldoc);
	
		return;
	}
	
	// Parse the data
	xmlNodePtr child_elem = root_elem->xmlChildrenNode;

	bool userPIN_set = false;
	bool atLeastOneCredSpec = false;
	
	while (child_elem != NULL)
	{
		if (xmlStrcasecmp(child_elem->name, (const xmlChar*) "Description") == 0)
		{
			xmlChar* description_value = xmlNodeListGetString(xmldoc, child_elem->xmlChildrenNode, 1);
			
			if (description_value != NULL)
			{
				description = std::string((const char*) description_value);
				
				xmlFree(description_value);
			}
		}
		else if (xmlStrcasecmp(child_elem->name, (const xmlChar*) "UserPIN") == 0)
		{
			xmlChar* userPIN_value = xmlNodeListGetString(xmldoc, child_elem->xmlChildrenNode, 1);

			if (userPIN_value != NULL)
			{
				userPIN = std::string((const char*) userPIN_value);

				xmlFree(userPIN_value);

				userPIN_set = true;
			}
		}
		else if (xmlStrcasecmp(child_elem->name, (const xmlChar*) "Credentials") == 0)
		{
			xmlNodePtr credentials = child_elem->xmlChildrenNode;
			
			while (credentials != NULL)
			{
				if (xmlStrcasecmp(credentials->name, (const xmlChar*) "Credential") == 0)
				{
					std::string issueSpec;
					std::string issuerIPK;
					std::string issuerISK;

					xmlNodePtr credential_info = credentials->xmlChildrenNode;

					while (credential_info != NULL)
					{
						if (xmlStrcasecmp(credential_info->name, (const xmlChar*) "IssueSpecification") == 0)
						{
							xmlChar* issueSpec_value = xmlNodeListGetString(xmldoc, credential_info->xmlChildrenNode, 1);

							if (issueSpec_value != NULL)
							{
								issueSpec = std::string((const char*) issueSpec_value);

								xmlFree(issueSpec_value);
							}
						}
						else if (xmlStrcasecmp(credential_info->name, (const xmlChar*) "IssuerPublicKey") == 0)
						{
							xmlChar* issuerIPK_value = xmlNodeListGetString(xmldoc, credential_info->xmlChildrenNode, 1);

							if (issuerIPK_value != NULL)
							{
								issuerIPK = std::string((const char*) issuerIPK_value);

								xmlFree(issuerIPK_value);
							}
						}
						else if (xmlStrcasecmp(credential_info->name, (const xmlChar*) "IssuerPrivateKey") == 0)
						{
							xmlChar* issuerISK_value = xmlNodeListGetString(xmldoc, credential_info->xmlChildrenNode, 1);

							if (issuerISK_value != NULL)
							{
								issuerISK = std::string((const char*) issuerISK_value);

								xmlFree(issuerISK_value);
							}
						}

						credential_info = credential_info->next;
					}

					if (issueSpec.empty() || issuerIPK.empty() || issuerISK.empty())
					{
						return;
					}

					issue_specs.push_back(issueSpec);
					issuer_ipks.push_back(issuerIPK);
					issuer_isks.push_back(issuerISK);

					atLeastOneCredSpec = true;
				}
				
				credentials = credentials->next;
			}
		}
		
		child_elem = child_elem->next;
	}
	
	xmlFreeDoc(xmldoc);
	
	is_valid = userPIN_set && atLeastOneCredSpec;
}
Exemple #6
0
/**\brief Load an XML file
 * \arg filename The XML file that should be parsed.
 * \arg optional  If this is true, an error is not returned if the file doesn't exist.
 */
bool Components::Load(string filename, bool optional) {
	xmlDocPtr doc;
	xmlNodePtr cur, ver;
	int versionMajor = 0, versionMinor = 0, versionMacro = 0;
	int numObjs = 0;
	bool success = true;
	
	File xmlfile = File (filename);
	long filelen = xmlfile.GetLength();
	char *buffer = xmlfile.Read();
	doc = xmlParseMemory( buffer, static_cast<int>(filelen) );
	delete [] buffer;

	// This path will be used when saving the file later.
	filepath = filename;

	if( doc == NULL ) {
		LogMsg(ERR, "Could not load '%s' for parsing.", filename.c_str() );
		return optional;
	}
	
	cur = xmlDocGetRootElement( doc );
	
	if( cur == NULL ) {
		LogMsg(ERR, "'%s' file appears to be empty.", filename.c_str() );
		xmlFreeDoc( doc );
		return false;
	}
	
	if( xmlStrcmp( cur->name, (const xmlChar *)rootName.c_str() ) ) {
		LogMsg(ERR, "'%s' appears to be invalid. Root element was %s.", filename.c_str(), (char *)cur->name );
		xmlFreeDoc( doc );
		return false;
	} else {
		LogMsg(INFO, "'%s' file found and valid, parsing...", filename.c_str() );
	}
	
	// Get the version number
	if( (ver = FirstChildNamed(cur, "version-major")) != NULL ) {
		versionMajor = NodeToInt(doc,ver);
	}
	if( (ver = FirstChildNamed(cur, "version-minor")) != NULL ) {
		versionMinor = NodeToInt(doc,ver);
	}
	if( (ver = FirstChildNamed(cur, "version-macro")) != NULL ) {
		versionMacro = NodeToInt(doc,ver);
	}
	if( ( versionMajor != EPIAR_VERSION_MAJOR ) ||
	    ( versionMinor != EPIAR_VERSION_MINOR ) ||
	    ( versionMacro != EPIAR_VERSION_MICRO ) ) {
		LogMsg(WARN, "File '%s' is version %d.%d.%d. This may cause problems since it does not match the current version %d.%d.%d.",
			filename.c_str(),
			versionMajor, versionMinor, versionMacro,
			EPIAR_VERSION_MAJOR, EPIAR_VERSION_MINOR, EPIAR_VERSION_MICRO );
	}
	
	// Get the components
	cur = cur->xmlChildrenNode;
	while( success && cur != NULL ) {
		// Parse for the version information and any children nodes
		if( ( !xmlStrcmp( cur->name, BAD_CAST componentName.c_str() ) ) ) {
			// Parse a Component
			success = ParseXMLNode( doc, cur );
			assert(success || optional);
			if(success) numObjs++;
		}
		
		cur = cur->next;
	}
	
	xmlFreeDoc( doc );

	
	LogMsg(INFO, "Parsing of file '%s' done, found %d objects. File is version %d.%d.%d.", filename.c_str(), numObjs, versionMajor, versionMinor, versionMacro );
	return success;
}
static int
rest_set_filter(noit_http_rest_closure_t *restc,
                int npats, char **pats) {
  noit_http_session_ctx *ctx = restc->http_ctx;
  xmlDocPtr doc = NULL, indoc = NULL;
  xmlNodePtr node, parent, root, newfilter;
  char xpath[1024];
  int error_code = 500, complete = 0, mask = 0;
  const char *error = "internal error";

  if(npats != 2) goto error;

  indoc = rest_get_xml_upload(restc, &mask, &complete);
  if(!complete) return mask;
  if(indoc == NULL) FAIL("xml parse error");

  snprintf(xpath, sizeof(xpath), "//filtersets%sfilterset[@name=\"%s\"]",
           pats[0], pats[1]);
  node = noit_conf_get_section(NULL, xpath);
  if(!node && noit_filter_exists(pats[1])) {
    /* It's someone else's */
    error_code = 403;
    goto error;
  }

  if((newfilter = validate_filter_post(indoc)) == NULL) goto error;
  xmlSetProp(newfilter, (xmlChar *)"name", (xmlChar *)pats[1]);

  parent = make_conf_path(pats[0]);
  if(!parent) FAIL("invalid path");
  if(node) {
    xmlUnlinkNode(node);
    xmlFreeNode(node);
  }
  xmlUnlinkNode(newfilter);
  xmlAddChild(parent, newfilter);

  if(noit_conf_write_file(NULL) != 0)
    noitL(noit_error, "local config write failed\n");
  noit_conf_mark_changed();
  noit_filter_compile_add(newfilter);
  if(restc->call_closure_free) restc->call_closure_free(restc->call_closure);
  restc->call_closure_free = NULL;
  restc->call_closure = NULL;
  restc->fastpath = rest_show_filter;
  return restc->fastpath(restc, restc->nparams, restc->params);

 error:
  noit_http_response_standard(ctx, error_code, "ERROR", "text/html");
  doc = xmlNewDoc((xmlChar *)"1.0");
  root = xmlNewDocNode(doc, NULL, (xmlChar *)"error", NULL);
  xmlDocSetRootElement(doc, root);
  xmlNodeAddContent(root, (xmlChar *)error);
  noit_http_response_xml(ctx, doc);
  noit_http_response_end(ctx);
  goto cleanup;

 cleanup:
  if(doc) xmlFreeDoc(doc);
  return 0;
}
Exemple #8
0
Datum
xpath_table(PG_FUNCTION_ARGS)
{
	/* Function parameters */
	char	   *pkeyfield = text_to_cstring(PG_GETARG_TEXT_PP(0));
	char	   *xmlfield = text_to_cstring(PG_GETARG_TEXT_PP(1));
	char	   *relname = text_to_cstring(PG_GETARG_TEXT_PP(2));
	char	   *xpathset = text_to_cstring(PG_GETARG_TEXT_PP(3));
	char	   *condition = text_to_cstring(PG_GETARG_TEXT_PP(4));

	/* SPI (input tuple) support */
	SPITupleTable *tuptable;
	HeapTuple	spi_tuple;
	TupleDesc	spi_tupdesc;

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

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

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

	int			numpaths;
	int			ret;
	int			proc;
	int			i;
	int			j;
	int			rownr;			/* For issuing multiple rows from one original
								 * document */
	bool		had_values;		/* To determine end of nodeset results */
	StringInfoData query_buf;
	PgXmlErrorContext *xmlerrcxt;
	volatile xmlDocPtr doctree = NULL;

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

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

	/*
	 * The tuplestore must exist in a higher context than this function call
	 * (per_query_ctx is used)
	 */
	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

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

	MemoryContextSwitchTo(oldcontext);

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

	/* must have at least one output column (for the pkey) */
	if (ret_tupdesc->natts < 1)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("xpath_table must have at least one output column")));

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

	attinmeta = TupleDescGetAttInMetadata(ret_tupdesc);

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

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

	/*
	 * Split XPaths. xpathset is a writable CString.
	 *
	 * Note that we stop splitting once we've done all needed for tupdesc
	 */
	numpaths = 0;
	pos = xpathset;
	while (numpaths < (ret_tupdesc->natts - 1))
	{
		xpaths[numpaths++] = (xmlChar *) pos;
		pos = strstr(pos, pathsep);
		if (pos != NULL)
		{
			*pos = '\0';
			pos++;
		}
		else
			break;
	}

	/* Now build query */
	initStringInfo(&query_buf);

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

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

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

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

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

	/*
	 * Check that SPI returned correct result. If you put a comma into one of
	 * the function parameters, this will catch it when the SPI query returns
	 * e.g. 3 columns.
	 */
	if (spi_tupdesc->natts != 2)
	{
		ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						errmsg("expression returning multiple columns is not valid in parameter list"),
						errdetail("Expected two columns in SPI result, got %d.", spi_tupdesc->natts)));
	}

	/*
	 * Setup the parser.  This should happen after we are done evaluating the
	 * query, in case it calls functions that set up libxml differently.
	 */
	xmlerrcxt = pgxml_parser_init(PG_XML_STRICTNESS_LEGACY);

	PG_TRY();
	{
		/* For each row i.e. document returned from SPI */
		for (i = 0; i < proc; i++)
		{
			char	   *pkey;
			char	   *xmldoc;
			xmlXPathContextPtr ctxt;
			xmlXPathObjectPtr res;
			xmlChar    *resstr;
			xmlXPathCompExprPtr comppath;

			/* Extract the row data as C Strings */
			spi_tuple = tuptable->vals[i];
			pkey = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
			xmldoc = SPI_getvalue(spi_tuple, spi_tupdesc, 2);

			/*
			 * Clear the values array, so that not-well-formed documents
			 * return NULL in all columns.	Note that this also means that
			 * spare columns will be NULL.
			 */
			for (j = 0; j < ret_tupdesc->natts; j++)
				values[j] = NULL;

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

			/* Parse the document */
			if (xmldoc)
				doctree = xmlParseMemory(xmldoc, strlen(xmldoc));
			else	/* treat NULL as not well-formed */
				doctree = NULL;

			if (doctree == NULL)
			{
				/* not well-formed, so output all-NULL tuple */
				ret_tuple = BuildTupleFromCStrings(attinmeta, values);
				tuplestore_puttuple(tupstore, ret_tuple);
				heap_freetuple(ret_tuple);
			}
			else
			{
				/* New loop here - we have to deal with nodeset results */
				rownr = 0;

				do
				{
					/* Now evaluate the set of xpaths. */
					had_values = false;
					for (j = 0; j < numpaths; j++)
					{
						ctxt = xmlXPathNewContext(doctree);
						ctxt->node = xmlDocGetRootElement(doctree);

						/* compile the path */
						comppath = xmlXPathCompile(xpaths[j]);
						if (comppath == NULL)
							xml_ereport(xmlerrcxt, ERROR,
										ERRCODE_EXTERNAL_ROUTINE_EXCEPTION,
										"XPath Syntax Error");

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

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

									break;

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

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

							/*
							 * Insert this into the appropriate column in the
							 * result tuple.
							 */
							values[j + 1] = (char *) resstr;
						}
						xmlXPathFreeContext(ctxt);
					}

					/* Now add the tuple to the output, if there is one. */
					if (had_values)
					{
						ret_tuple = BuildTupleFromCStrings(attinmeta, values);
						tuplestore_puttuple(tupstore, ret_tuple);
						heap_freetuple(ret_tuple);
					}

					rownr++;
				} while (had_values);
			}

			if (doctree != NULL)
				xmlFreeDoc(doctree);
			doctree = NULL;

			if (pkey)
				pfree(pkey);
			if (xmldoc)
				pfree(xmldoc);
		}
	}
	PG_CATCH();
	{
		if (doctree != NULL)
			xmlFreeDoc(doctree);

		pg_xml_done(xmlerrcxt, true);

		PG_RE_THROW();
	}
	PG_END_TRY();

	if (doctree != NULL)
		xmlFreeDoc(doctree);

	pg_xml_done(xmlerrcxt, false);

	tuplestore_donestoring(tupstore);

	SPI_finish();

	rsinfo->setResult = tupstore;

	/*
	 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
	 * tuples are in our tuplestore and passed back through rsinfo->setResult.
	 * rsinfo->setDesc is set to the tuple description that we actually used
	 * to build our tuples with, so the caller can verify we did what it was
	 * expecting.
	 */
	return (Datum) 0;
}
Exemple #9
0
int pres_watcher_allowed(subs_t* subs)
{
	xmlDocPtr xcap_tree= NULL;
	xmlNodePtr node= NULL,  actions_node = NULL;
	xmlNodePtr sub_handling_node = NULL;
	char* sub_handling = NULL;
	int ret = 0;

	/* if force_active set status to active*/
	if(force_active)
	{
		subs->status= ACTIVE_STATUS;
		subs->reason.s= NULL;
		subs->reason.len= 0;
		return 0;
	}

	if(subs->auth_rules_doc== NULL)
	{
		subs->status= PENDING_STATUS;
		subs->reason.s= NULL;
		subs->reason.len= 0;
		return 0;
	}

	xcap_tree= xmlParseMemory(subs->auth_rules_doc->s,
			subs->auth_rules_doc->len);
	if(xcap_tree== NULL)
	{
		LM_ERR("parsing xml memory\n");
		return -1;
	}

	node= get_rule_node(subs, xcap_tree);
	if(node== NULL)
	{
		/* if no rule node was found and the previous state was active -> set the
		 * state to terminated with reason xcapauth_userdel_reason (default "probation") */
		if(subs->status != PENDING_STATUS)
		{
			subs->status= TERMINATED_STATUS;
			subs->reason= xcapauth_userdel_reason;
		}
		goto done;
	}

	subs->status= PENDING_STATUS;
	subs->reason.s= NULL;
	subs->reason.len= 0;

	/* process actions */
	actions_node = xmlNodeGetChildByName(node, "actions");
	if(actions_node == NULL)
	{
		LM_DBG("actions_node NULL\n");
		goto done;
	}
	LM_DBG("actions_node->name= %s\n",
			actions_node->name);
			
	sub_handling_node = xmlNodeGetChildByName(actions_node, "sub-handling");
	if(sub_handling_node== NULL)
	{
		LM_DBG("sub_handling_node NULL\n");
		goto done;
	}
	sub_handling = (char*)xmlNodeGetContent(sub_handling_node);
		LM_DBG("sub_handling_node->name= %s\n",
			sub_handling_node->name);
	LM_DBG("sub_handling_node->content= %s\n",
			sub_handling);
	
	if(sub_handling== NULL)
	{
		LM_ERR("Couldn't get sub-handling content\n");
		ret = -1;
		goto done;
	}
	if( strncmp((char*)sub_handling, "block",5 )==0)
	{	
		subs->status = TERMINATED_STATUS;;
		subs->reason.s= "rejected";
		subs->reason.len = 8;
	}
	else	
	if( strncmp((char*)sub_handling, "confirm",7 )==0)
	{	
		subs->status = PENDING_STATUS;
	}
	else
	if( strncmp((char*)sub_handling , "polite-block",12 )==0)
	{	
		subs->status = ACTIVE_STATUS;
		subs->reason.s= "polite-block";
		subs->reason.len = 12;
	}
	else
	if( strncmp((char*)sub_handling , "allow",5 )==0)
	{
		subs->status = ACTIVE_STATUS;
	}
	else
	{
		LM_ERR("unknown subscription handling action\n");
		ret = -1;
	}

done:
	if(sub_handling)
		xmlFree(sub_handling);
	xmlFreeDoc(xcap_tree);
	return ret;
}
Exemple #10
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;
	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((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);
	}
}
// TODO: This looks like should be ported to C code. or a big part of it.
bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected)
{
	static const char errPrefix[] = "divelog.de-upload:";
	if (!amount_selected) {
		report_error(tr("no dives were selected").toUtf8());
		return false;
	}

	xsltStylesheetPtr xslt = NULL;
	struct zip *zip;

	xslt = get_stylesheet("divelogs-export.xslt");
	if (!xslt) {
		qDebug() << errPrefix << "missing stylesheet";
		report_error(tr("stylesheet to export to divelogs.de is not found").toUtf8());
		return false;
	}


	int error_code;
	zip = zip_open(QFile::encodeName(QDir::toNativeSeparators(tempfile)), ZIP_CREATE, &error_code);
	if (!zip) {
		char buffer[1024];
		zip_error_to_str(buffer, sizeof buffer, error_code, errno);
		report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer);
		return false;
	}

	/* walk the dive list in chronological order */
	int i;
	struct dive *dive;
	for_each_dive (i, dive) {
		char filename[PATH_MAX];
		int streamsize;
		const char *membuf;
		xmlDoc *transformed;
		struct zip_source *s;
		struct membuffer mb = {};

		/*
		 * Get the i'th dive in XML format so we can process it.
		 * We need to save to a file before we can reload it back into memory...
		 */
		if (selected && !dive->selected)
			continue;
		/* make sure the buffer is empty and add the dive */
		mb.len = 0;

		struct dive_site *ds = get_dive_site_by_uuid(dive->dive_site_uuid);

		if (ds) {
			put_format(&mb, "<divelog><divesites><site uuid='%8x' name='", dive->dive_site_uuid);
			put_quoted(&mb, ds->name, 1, 0);
			put_format(&mb, "'");
			if (ds->latitude.udeg || ds->longitude.udeg) {
				put_degrees(&mb, ds->latitude, " gps='", " ");
				put_degrees(&mb, ds->longitude, "", "'");
			}
			put_format(&mb, "/>\n</divesites>\n");
		}

		save_one_dive_to_mb(&mb, dive);

		if (ds) {
			put_format(&mb, "</divelog>\n");
		}
		membuf = mb_cstring(&mb);
		streamsize = strlen(membuf);
		/*
		 * Parse the memory buffer into XML document and
		 * transform it to divelogs.de format, finally dumping
		 * the XML into a character buffer.
		 */
		xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0);
		if (!doc) {
			qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!";
			report_error(tr("internal error").toUtf8());
			goto error_close_zip;
		}
		free((void *)membuf);

		transformed = xsltApplyStylesheet(xslt, doc, NULL);
		if (!transformed) {
			qWarning() << errPrefix << "XSLT transform failed for dive: " << i;
			report_error(tr("Conversion of dive %1 to divelogs.de format failed").arg(i).toUtf8());
			continue;
		}
		xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize);
		xmlFreeDoc(doc);
		xmlFreeDoc(transformed);

		/*
		 * Save the XML document into a zip file.
		 */
		snprintf(filename, PATH_MAX, "%d.xml", i + 1);
		s = zip_source_buffer(zip, membuf, streamsize, 1);
		if (s) {
			int64_t ret = zip_add(zip, filename, s);
			if (ret == -1)
				qDebug() << errPrefix << "failed to include dive:" << i;
		}
	}
Exemple #12
0
static GList *
anjuta_profile_read_plugins_from_xml (AnjutaProfile *profile,
									  GFile *file,
									  GError **error)
{
	gchar *read_buf;
	gsize size;
	xmlDocPtr xml_doc;
	GList *descs_list = NULL;
	GList *not_found_names = NULL;
	GList *not_found_urls = NULL;
	gboolean parse_error;

	/* Read xml file */
	if (!g_file_load_contents (file, NULL, &read_buf, &size, NULL, error))
	{
		return NULL;
	}
	
	/* Parse xml file */
	parse_error = TRUE;
	xml_doc = xmlParseMemory (read_buf, size);
	g_free (read_buf);
	if (xml_doc != NULL)
	{
		xmlNodePtr xml_root;
		
		xml_root = xmlDocGetRootElement(xml_doc);
		if (xml_root &&
			(xml_root->name) &&
			xmlStrEqual(xml_root->name, (const xmlChar *)"anjuta"))
		{
			xmlNodePtr xml_node;

			parse_error = FALSE;
			for (xml_node = xml_root->xmlChildrenNode; xml_node; xml_node = xml_node->next)
			{
				GList *groups = NULL;
				GList *attribs = NULL;
				GList *values = NULL;
				xmlChar *name, *url, *mandatory_text;
				xmlNodePtr xml_require_node;
				gboolean mandatory;

				if (!xml_node->name ||
					!xmlStrEqual (xml_node->name, (const xmlChar*)"plugin"))
				{
					continue;
				}
	
				name = xmlGetProp (xml_node, (const xmlChar*)"name");
				url = xmlGetProp (xml_node, (const xmlChar*)"url");
		
				/* Ensure that both name is given */
				if (!name)
				{
					g_warning ("XML error: Plugin name should be present in plugin tag");
					parse_error = TRUE;
					break;
				}
				if (!url)
					url = xmlCharStrdup ("http://anjuta.org/plugins/");
									 
				/* Check if the plugin is mandatory */
				mandatory_text = xmlGetProp (xml_node, (const xmlChar*)"mandatory");
				mandatory = mandatory_text && (xmlStrcasecmp (mandatory_text, (const xmlChar *)"yes") == 0);
				xmlFree(mandatory_text);
										 
				/* For all plugin attribute conditions */
				for (xml_require_node = xml_node->xmlChildrenNode;
			 		xml_require_node;
			 		xml_require_node = xml_require_node->next)
				{
					xmlChar *group;
					xmlChar *attrib;
					xmlChar *value;
		
					if (!xml_require_node->name ||
						!xmlStrEqual (xml_require_node->name,
									  (const xmlChar*)"require"))
					{
						continue;
					}
					group = xmlGetProp (xml_require_node,
										(const xmlChar *)"group");
					attrib = xmlGetProp(xml_require_node,
										(const xmlChar *)"attribute");
					value = xmlGetProp(xml_require_node,
									   (const xmlChar *)"value");
			
					if (group && attrib && value)
					{
						groups = g_list_prepend (groups, group);
						attribs = g_list_prepend (attribs, attrib);
						values = g_list_prepend (values, value);
					}
					else
					{
						if (group) xmlFree (group);
						if (attrib) xmlFree (attrib);
						if (value) xmlFree (value);
						parse_error = TRUE;
						g_warning ("XML parse error: group, attribute and value should be defined in require");
						break;
					}
				}

				if (!parse_error)
				{
					if (g_list_length (groups) == 0)
					{
						parse_error = TRUE;
						g_warning ("XML Error: No attributes to match given");
					}
					else
					{
						GList *plugin_descs;
						
						plugin_descs =
							anjuta_plugin_manager_list_query (profile->priv->plugin_manager,
															  groups,
															  attribs,
															  values);
						if (plugin_descs)
						{
							descs_list = g_list_prepend (descs_list, plugin_descs);
						}
						else if (mandatory)
						{
							not_found_names = g_list_prepend (not_found_names, g_strdup ((const gchar *)name));
							not_found_urls = g_list_prepend (not_found_urls, g_strdup ((const gchar *)url));
						}
					}
				}
				g_list_foreach (groups, (GFunc)xmlFree, NULL);
				g_list_foreach (attribs, (GFunc)xmlFree, NULL);
				g_list_foreach (values, (GFunc)xmlFree, NULL);
				g_list_free (groups);
				g_list_free (attribs);
				g_list_free (values);
				xmlFree (name);
				xmlFree (url);
			}
		}
		xmlFreeDoc(xml_doc);
	}
	
	if (parse_error)
	{
		/* Error during parsing */
		gchar *uri = g_file_get_uri (file);

		g_set_error (error, ANJUTA_PROFILE_ERROR,
					 ANJUTA_PROFILE_ERROR_URI_READ_FAILED,
					 _("Failed to read '%s': XML parse error. "
					   "Invalid or corrupted Anjuta plugins profile."),
			 		uri);
		g_free (uri);
		
		g_list_foreach (descs_list, (GFunc)g_list_free, NULL);
		g_list_free (descs_list);
		descs_list = NULL;
	}
	else if (not_found_names)
	{
		/*
	 	* FIXME: Present a nice dialog box to promt the user to download
		* the plugin from corresponding URLs, install them and proceed.
 		*/	
		GList *node_name, *node_url;
		GString *mesg = g_string_new ("");
		gchar *uri = g_file_get_uri (file);
			
		not_found_names = g_list_reverse (not_found_names);
		not_found_urls = g_list_reverse (not_found_urls);
		
		node_name = not_found_names;
		node_url = not_found_urls;
		while (node_name)
		{
			/* <Pluginname>: Install it from <some location on the web> */
			g_string_append_printf (mesg, _("%s: Install it from '%s'\n"),
											(char *)node_name->data,
											(char*)node_url->data);
			node_name = g_list_next (node_name);
			node_url = g_list_next (node_url);
		}
		g_set_error (error, ANJUTA_PROFILE_ERROR,
					 ANJUTA_PROFILE_ERROR_URI_READ_FAILED,
					 _("Failed to read '%s': Following mandatory plugins are missing:\n%s"),
					 uri, mesg->str);
		g_free (uri);
		g_string_free (mesg, TRUE);
		
		g_list_foreach (descs_list, (GFunc)g_list_free, NULL);
		g_list_free (descs_list);
		descs_list = NULL;
	}
	g_list_foreach (not_found_names, (GFunc)g_free, NULL);
	g_list_free (not_found_names);
	g_list_foreach (not_found_urls, (GFunc)g_free, NULL);
	g_list_free (not_found_urls);

	return descs_list;
}
Exemple #13
0
/*
 * EXTERNAL ENTRY POINT
 *
 * Builds the localized fault registry from XML files supplied in
 * various directories.
 *
 * Returns the number of faults successfully loaded into registry. If
 * the registry was previously loaded, returns the number of previously
 * loaded faults as a negative number.
 */
int
init_eucafaults (char *fileprefix)
{
    struct stat dirstat;
    static int faults_loaded = 0;
    char *locale = NULL;
    static char faultdirs[NUM_FAULTDIR_TYPES][PATH_MAX];

    pthread_mutex_lock (&fault_mutex);

    if (faults_loaded) {
        logprintfl (EUCATRACE, "Attempt to reinitialize fault registry? Skipping...\n");
        pthread_mutex_unlock (&fault_mutex);
        return -faults_loaded;  // Negative return because already loaded.
    }

	char *euca_env = getenv (EUCALYPTUS_ENV_VAR_NAME);

	if (euca_env) {
        strncpy (euca_base, euca_env, MAX_PATH - 1);
    }

    initialize_faultlog (fileprefix);
    logprintfl (EUCATRACE, "Initializing fault registry directories.\n");

    if ((locale = getenv (LOCALIZATION_ENV_VAR)) == NULL) {
        logprintfl (EUCAINFO,
                   "$%s not set, using default value of: %s\n",
                    LOCALIZATION_ENV_VAR, DEFAULT_LOCALIZATION);
    }
    LIBXML_TEST_VERSION;

    /* Cycle through list of faultdirs in priority order, noting any missing. */
    if (locale != NULL) {
        snprintf (faultdirs[CUSTOM_LOCALIZED], PATH_MAX,
                  EUCALYPTUS_CUSTOM_FAULT_DIR "/%s/", euca_base, locale);
    } else {
        faultdirs[CUSTOM_LOCALIZED][0] = 0;
    }
    snprintf (faultdirs[CUSTOM_DEFAULT_LOCALIZATION], PATH_MAX,
              EUCALYPTUS_CUSTOM_FAULT_DIR "/%s/", euca_base,
              DEFAULT_LOCALIZATION);
    if (locale != NULL) {
        snprintf (faultdirs[DISTRO_LOCALIZED], PATH_MAX, EUCALYPTUS_FAULT_DIR
                  "/%s/", euca_base, locale);
    } else {
        faultdirs[DISTRO_LOCALIZED][0] = 0;
    }
    snprintf (faultdirs[DISTRO_DEFAULT_LOCALIZATION], PATH_MAX,
              EUCALYPTUS_FAULT_DIR "/%s/", euca_base, DEFAULT_LOCALIZATION);

    for (int i = 0; i < NUM_FAULTDIR_TYPES; i++) {
        if (faultdirs[i][0]) {
            if (stat (faultdirs[i], &dirstat) != 0) {
                logprintfl (EUCAINFO, "stat() problem with %s: %s\n",
                           faultdirs[i], strerror (errno));
            } else if (!S_ISDIR (dirstat.st_mode)) {
                logprintfl (EUCAINFO,
                           "stat() problem with %s: Not a directory\n",
                           faultdirs[i], strerror (errno));
            } else {
                struct dirent **namelist;
                int numfaults = scandir (faultdirs[i], &namelist, &scandir_filter,
                                         alphasort);
                if (numfaults == 0) {
                    logprintfl (EUCADEBUG, "No faults found in %s\n", faultdirs[i]);
                } else {
                    logprintfl (EUCADEBUG, "Found %d %s files in %s\n", numfaults, XML_SUFFIX,
                            faultdirs[i]);
                    while (numfaults--) {
                        xmlDoc *new_fault = read_eucafault (faultdirs[i], str_trim_suffix (namelist[numfaults]->d_name, XML_SUFFIX));
                        free (namelist[numfaults]);

                        if (new_fault) {
                            if (add_eucafault (new_fault)) {
                                faults_loaded++;
                            }
                            xmlFreeDoc (new_fault);
                        } else {
                            logprintfl (EUCATRACE, "Not adding new fault--mismatch or already exists...?\n");
                        }
                    }
                    free (namelist);
                }
            }
        }
    }
    pthread_mutex_unlock (&fault_mutex);
    logprintfl (EUCAINFO, "Loaded %d eucafault descriptions into registry.\n",
               faults_loaded);
    return faults_loaded;
}
Exemple #14
0
int cgiMain (void)
{
	int ret = OK;
	char name[512];
	char cmd[1024];
	char *keyName=NULL;
	char *ErrMsg = NULL;
	char *fileName=NULL;
	char *backName=NULL;
	char *p = NULL;
	char *directory= NULL;
	char *confFile=NULL;
	char *title=NULL;
	struct stat buf	;
	xmlDocPtr doc;
	xmlNodePtr pNode,pRoot;
  	//
	//	认证用户,并且获取用户名
	//
	ret = authentication(NULL,NULL);
	cgiHeaderContent("text/html");
	if (ret)
	{
		//
		//	认证失败
		//
		goto exit;
	}
	//
	//	获取属性文件名
	//
	ErrMsg = "propertyFile";
	ret = cgiGetString(&confFile,2,255,ErrMsg);
	if(ret)
		goto exit;	
	//
	//	获取要使用的属性记录主键
	//
	ErrMsg = "keyName";
	ret = cgiGetString(&keyName,1,255,ErrMsg);
	if (ret)
		goto exit;
	ErrMsg = NULL;
	//
	//	先在属性文件中获取cgi程序
	//
	doc = xmlParseFile(confFile);
	if (NULL == doc)
	{
		ret = NO_MESSAGE;
		ErrMsg="没有打开属性文件<p>或没有属性文件";
		goto exit;
	}
	//
	//	获取根节点
	//
	pRoot = xmlDocGetRootElement(doc);
	if (NULL == pRoot)
	{
		xmlFreeDoc(doc);
		ret = NO_MESSAGE;
		ErrMsg="空的属性文件";
		goto exit;
	}
	pNode = pRoot->xmlChildrenNode;
	//
	//	查找使用的配置树
	//
	while(pNode)
	{
		if (xmlStrcmp(pNode->name,"conf")==0)
		{
			xmlChar * keyValue = NULL;
			//
			//	查找使用的属性记录
			//
			keyValue = xmlGetProp(pNode,"name");
			if (xmlStrcmp(keyValue,(const xmlChar*)keyName)==0)
			{
				break;
			}
			xmlFree(keyValue);
		}
		pNode = pNode->next;
	}
	if (NULL == pNode)
	{
		xmlFreeDoc(doc);
		doc=NULL;
		ret = NO_MESSAGE;
		ErrMsg="没有找到指定的配置项";
		goto exit;
	}
	title = xmlGetProp(pNode,"title");
	if (strcmp(keyName,"systemLog")==0)
	{
		//
		//	系统日志处理部分。
		//
		time_t cur_time;
		struct tm *myTime;
		int i;
	 	cur_time = time(NULL);
		myTime = localtime(&cur_time);
		xmlFreeDoc(doc);
		doc = NULL;
		for(i=1;i<32;i++)
		{
			sprintf(name,"%s.%d",LOG_FILE_NAME,i);
			ret =  stat(name,&buf);
			if ((ret)||(buf.st_mode & S_IFDIR))
				continue;
			break;
		}
		if (i>=32)
		{
			cgiPrintf("<HTML><HEAD><meta http-equiv=\"refresh\" content=\"290;URL=/timeout.html\"></head></HEAD>"
				"<body background=\"/icons/bg01.gif\"><br><center><H2>%s</H2><P></center>"
				"<P><P><HR width=60%><br>"
				"<table align=center><tr><td>没有记录日志</td></tr></TABLE><P><P><HR width=60%><center></BODY></HTML>",title);
			dispOperateInfo(NULL,NO_DISP_MSG,"没有记录日志");
			return 0;		
		}
		//
		// 生成备份文件名
		//
		//snprintf(name,512,"../../htdocs/login/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
		snprintf(name,512,"../download/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
		snprintf(cmd,1024,"cd ./log ; tar -zcf %s sysLog.*",name);

		if (system(cmd)==-1)
			ret = EXEC_FAULT;
		else
		{
			//sprintf(name,"../htdocs/login/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
			sprintf(name,"./download/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
			ret =  stat(name,&buf);
			if (ret)
			{
				ret = BACK_FALSE;	
			}
			else
			{
				//sprintf(name,"/login/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
				sprintf(name,"webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
				//sprintf(cmd,"请 <font size =\"14\" color=blue><a href=%s color=red>下载</a> </font>后,妥善保存。",name);
				sprintf(cmd,"请 <font size =\"14\" color=blue><a href=/cgi-bin/download.cgi?downloadFile=%s color=red>下载</a> </font>后,妥善保存。",name);
				cgiPrintf("<HTML><head><link href=\"/icons/all.css\" >"
					"<meta http-equiv=\"refresh\" content=\"290;URL=/timeout.html\"></head>"
					"<BODY background=\"/icons/bg01.gif\"><br><center><H2>备份%s</H2><P></center>"
					"<P><HR width=60%><br><center>%s",title,cmd);
				cgiPrintf("<br><HR width=60%></body></html>");
				dispOperateInfo(NULL,NO_DISP_OK_MSG,NULL);
				return 0;
			}
		}
		goto exit;
	}	
	fileName = xmlGetProp(pNode,"fileName");
	if (fileName)
	{
		ret =  stat(fileName,&buf);
		if ((ret)||(buf.st_mode & S_IFDIR))
		{
			ret = NO_MESSAGE;
			ErrMsg="日志文件不存在";
			goto exit;
		}
	}
	backName = xmlGetProp(pNode,"backName");
	if ((backName==NULL)||(strlen(backName)==0))
	{
		ret = NO_MESSAGE;
		ErrMsg = "没有给出备份文件名";
		goto exit;	
	}
	directory = xmlGetProp(pNode,"directory");
	xmlFree(doc);
	doc = NULL;
	//
	//	获取日志所在的目录
	//
	strncpy(name,fileName,512);
	p=strrchr(name,'/');
	if (p)
	{
		*p=0;
		//
		// 生成备份文件名
		//
		if (directory)
			snprintf(cmd,1023,"cd %s ; tar -zcf %s.tar.gz %s %s",name,backName,p+1,directory);
		else
			snprintf(cmd,1023,"cd %s ; tar -zcf %s.tar.gz %s",name,backName,p+1);
		
	}
	else
	{
		if (directory)
			snprintf(cmd,1023,"tar -zcf %s.tar.gz %s %s",backName,fileName,directory);
		else
			snprintf(cmd,1023,"tar -zcf %s.tar.gz %s",backName,fileName);
	}
	if (system(cmd)==-1)
		ret = EXEC_FAULT;
	else
	{
		sprintf(name,"%s.tar.gz",backName);
		ret =  stat(name,&buf);
		if (ret)
		{
			ret = BACK_FALSE;
		}
		else
		{
			p=strrchr(backName,'/');
			if (p)
				p++;
			else
				p = backName;
			//snprintf(name,512,"/%s.tar.gz",p);
			snprintf(name,512,"%s.tar.gz",p);
			//snprintf(cmd,1023,"请 <font size =\"14\" color=blue><a href=%s color=red>下载</a> </font>后,妥善保存。",name);
			snprintf(cmd,1023,"请 <font size =\"14\" color=blue><a href=/cgi-bin/download.cgi?downloadFile=%s color=red>下载</a> </font>后,妥善保存。",name);
			cgiPrintf("<HTML><head><link href=\"/icons/all.css\" >"
				"<meta http-equiv=\"refresh\" content=\"290;URL=/timeout.html\"></head>"
				"<BODY background=\"/icons/bg01.gif\"><br><center><H2>备份%s</H2><P></center>"
				"<P><HR width=60%><br><center>%s",title,cmd);
			cgiPrintf("<br><HR width=60%></body></html>");			
			snprintf(cmd,1024,"%s",fileName);
			dispOperateInfo(NULL,NO_DISP_MSG,cmd);
			return 0;
		}
	}
exit:
	if (doc) 	xmlFree(doc);
	if (fileName) free(fileName);
	if (backName) free(backName);
	if (directory) free(directory);
	dispOperateInfo(NULL,ret,ErrMsg);
	return ret;
}
Exemple #15
0
static gboolean xspf_playlist_save (const gchar * filename, VFSFile * file,
 const gchar * title, Index * filenames, Index * tuples)
{
    gint entries = index_count (filenames);
    xmlDocPtr doc;
    xmlNodePtr rootnode, tracklist;
    gint count;

    doc = xmlNewDoc((xmlChar *)"1.0");
    doc->charset = XML_CHAR_ENCODING_UTF8;
    doc->encoding = xmlStrdup((xmlChar *)"UTF-8");

    rootnode = xmlNewNode(NULL, (xmlChar *)XSPF_ROOT_NODE_NAME);
    xmlSetProp(rootnode, (xmlChar *)"version", (xmlChar *)"1");
    xmlSetProp(rootnode, (xmlChar *)"xmlns", (xmlChar *)XSPF_XMLNS);

    /* common */
    xmlDocSetRootElement(doc, rootnode);

    if (title)
        xspf_add_node (rootnode, TUPLE_STRING, FALSE, "title", title, 0);

    tracklist = xmlNewNode(NULL, (xmlChar *)"trackList");
    xmlAddChild(rootnode, tracklist);

    for (count = 0; count < entries; count ++)
    {
        const gchar * filename = index_get (filenames, count);
        const Tuple * tuple = index_get (tuples, count);
        xmlNodePtr track, location;
        gchar *scratch = NULL;
        gint scratchi = 0;

        track = xmlNewNode(NULL, (xmlChar *)"track");
        location = xmlNewNode(NULL, (xmlChar *)"location");

        xmlAddChild(location, xmlNewText((xmlChar *)filename));
        xmlAddChild(track, location);
        xmlAddChild(tracklist, track);

        if (tuple != NULL)
        {
            gint i;
            for (i = 0; i < xspf_nentries; i++) {
                const xspf_entry_t *xs = &xspf_entries[i];
                gboolean isOK = (tuple_get_value_type (tuple, xs->tupleField,
                 NULL) == xs->type);

                switch (xs->type) {
                    case TUPLE_STRING:
                        scratch = tuple_get_str (tuple, xs->tupleField, NULL);
                        if (! scratch)
                            isOK = FALSE;
                        str_unref(scratch);
                        break;
                    case TUPLE_INT:
                        scratchi = tuple_get_int (tuple, xs->tupleField, NULL);
                        break;
                    default:
                        break;
                }

                if (isOK)
                    xspf_add_node(track, xs->type, xs->isMeta, xs->xspfName, scratch, scratchi);
            }
        }
    }

    xmlSaveCtxt * save = xmlSaveToIO (write_cb, close_cb, file, NULL,
     XML_SAVE_FORMAT);
    if (! save)
        goto ERR;

    if (xmlSaveDoc (save, doc) < 0 || xmlSaveClose (save) < 0)
        goto ERR;

    xmlFreeDoc(doc);
    return TRUE;

ERR:
    xmlFreeDoc (doc);
    return FALSE;
}
Exemple #16
0
int presence_offline_body(str* body, str** offline_body)
{
	xmlDocPtr doc= NULL;
	xmlDocPtr new_doc= NULL;
	xmlNodePtr node, tuple_node= NULL, status_node;
	xmlNodePtr root_node, add_node, pres_node;
	xmlErrorPtr	xml_error;
	str* new_body;
	char *err_msg;
	int rc = OFFB_STATUS_ERROR;

	doc= xmlParseMemory(body->s, body->len);
	if(doc==  NULL)
	{
		GET_LAST_XML_ERROR(xml_error, err_msg);
		LM_ERR("xml memory parsing failed: %s\n", err_msg);
		goto done;
	}
	node= xmlDocGetNodeByName(doc, "basic", NULL);
	if(node== NULL)
	{
		LM_ERR("while extracting basic node\n");
		goto done;
	}
	xmlNodeSetContent(node, (const unsigned char*)"closed");

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

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

	new_doc = xmlNewDoc(BAD_CAST "1.0");
	if(new_doc==0)
	{
		GET_LAST_XML_ERROR(xml_error, err_msg);
		LM_ERR("failed to create new XML document: %s\n", err_msg);
		goto done;
	}

	root_node= xmlCopyNode(pres_node, 2);
	if(root_node== NULL)
	{
		GET_LAST_XML_ERROR(xml_error, err_msg);
		LM_ERR("failed to copy root node: %s\n", err_msg);
		goto done;
	}
	xmlNewProp(root_node, BAD_CAST "xmlns",
			BAD_CAST "urn:ietf:params:xml:ns:pidf");
	xmlDocSetRootElement(new_doc, root_node);

	tuple_node= xmlCopyNode(tuple_node, 2);
	if(tuple_node== NULL)
	{
		GET_LAST_XML_ERROR(xml_error, err_msg);
		LM_ERR("failed to copy tuple node: %s\n", err_msg);
		goto done;
	}

	xmlAddChild(root_node, tuple_node);

	add_node= xmlCopyNode(status_node, 1);
	if(add_node== NULL)
	{
		GET_LAST_XML_ERROR(xml_error, err_msg);
		LM_ERR("failed to copy status node: %s\n", err_msg);
		goto done;
	}

	xmlAddChild(tuple_node, add_node);

	new_body = (str*)pkg_malloc(sizeof(str));
	if(new_body == NULL)
	{
		LM_ERR("No more pkg memory");
		goto done;
	}
	memset(new_body, 0, sizeof(str));

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

	*offline_body = new_body;
	rc = OFFB_STATUS_OK;

done:
	if(doc)
		xmlFreeDoc(doc);
	if(new_doc)
		xmlFreeDoc(new_doc);

	return rc;
}
Exemple #17
0
int benthos_dc_manifest_parse(plugin_manifest_t * ptr, const char * path)
{
	int rv;
	struct plugin_manifest_t_ * manifest;
	struct stat finfo;
	xmlDoc * doc;
	xmlNode * root;
	iconv_t conv;

	if (! ptr || ! path)
		return EINVAL;

	/* Create the Encoding Converter */
	conv = iconv_open("ISO-8859-1", "UTF-8");
	if (conv == (iconv_t)(-1))
		return errno;

	/* Create the Manifest Object */
	manifest = new struct plugin_manifest_t_;
	if (! manifest)
	{
		iconv_close(conv);
		return ENOMEM;
	}

	/* Check that the File Exists */
	rv = stat(path, & finfo);
	if (rv != 0)
	{
		delete manifest;
		iconv_close(conv);
		return errno;
	}

	if (! S_ISREG(finfo.st_mode))
	{
		delete manifest;
		iconv_close(conv);
		return ENOENT;
	}

	/* Load the Manifest File */
	doc = xmlReadFile(path, 0, 0);
	if (doc == NULL)
	{
		delete manifest;
		xmlCleanupParser();
		iconv_close(conv);
		return MANFIEST_ERR_MALFORMED;
	}

	/* Load the Root Node */
	root = xmlDocGetRootElement(doc);
	if ((root == NULL) || (root->type != XML_ELEMENT_NODE))
	{
		delete manifest;
		xmlFreeDoc(doc);
		xmlCleanupParser();
		iconv_close(conv);
		return MANIFEST_ERR_NOROOT;
	}

	/* Check the Root Node */
	if (xmlStrcmp(root->name, BAD_CAST("plugin")) != 0)
	{
		delete manifest;
		xmlFreeDoc(doc);
		xmlCleanupParser();
		iconv_close(conv);
		return MANIFEST_ERR_NOTPLUGIN;
	}

	/* Parse the Manifest Entry */
	rv = parse_manifest(manifest, root, conv);
	if (rv != 0)
	{
		delete manifest;
		xmlFreeDoc(doc);
		xmlCleanupParser();
		iconv_close(conv);
		return rv;
	}

	/* Set Manifest Pointer */
	(* ptr) = manifest;

	/* Cleanup */
	xmlFreeDoc(doc);
	xmlCleanupParser();
	iconv_close(conv);

	return 0;
}
Exemple #18
0
str* agregate_xmls(str* pres_user, str* pres_domain, str** body_array, int n,
		char* root_name, char* elem_name)
{
	int i, j= 0, append ;
	xmlNodePtr p_root= NULL, new_p_root= NULL ;
	xmlDocPtr* xml_array ;
	xmlNodePtr node = NULL;
	xmlNodePtr add_node = NULL ;
	str *body= NULL;
	char* id= NULL, *elem_id = NULL;
	xmlDocPtr pidf_manip_doc= NULL;
	str* pidf_doc= NULL;

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

	/* if pidf_manipulation usage is configured */
	if(pidf_manipulation)
	{
		if( get_rules_doc(pres_user, pres_domain, PIDF_MANIPULATION, &pidf_doc)< 0)
		{
			LM_ERR("while getting xcap tree for doc_type PIDF_MANIPULATION\n");
			goto error;
		}
		if(pidf_doc== NULL)
		{
			LM_DBG("No PIDF_MANIPULATION doc for [user]= %.*s [domain]= %.*s\n",
			pres_user->len, pres_user->s, pres_domain->len, pres_domain->s);
		}
		else
		{
			pidf_manip_doc= xmlParseMemory(pidf_doc->s, pidf_doc->len);
			pkg_free(pidf_doc->s);
			pkg_free(pidf_doc);

			if(pidf_manip_doc== NULL)
			{
				LM_ERR("parsing xml memory\n");
				goto error;
			}		
			else
			{	
				xml_array[0]= pidf_manip_doc;
				j++;
			}
		}
	}

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

		xml_array[j] = NULL;
		xml_array[j] = xmlParseMemory( body_array[i]->s, body_array[i]->len );
		LM_DBG("i = [%d] - body: %.*s\n", i,  body_array[i]->len, body_array[i]->s);

		if( xml_array[j]== NULL)
		{
			LM_ERR("while parsing xml body message\n");
			goto error;
		}
		j++;
	}

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

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

	for(i= j-1; i>=0; i--)
	{
		LM_DBG("i = %d\n", i);

		new_p_root= xmlDocGetNodeByName( xml_array[i], root_name, NULL);
		if(new_p_root ==NULL)
		{
			LM_ERR("while geting the xml_tree root\n");
			goto error;
		}
		
		node= xmlNodeGetChildByName(new_p_root, elem_name);
		if(node== NULL)
		{
			LM_DBG("no %s node found\n", elem_name);
			append = 1;
			goto append_label;
		}
		elem_id= xmlNodeGetAttrContentByName(node, "id");
		if(elem_id== NULL)
		{
			LM_ERR("while extracting %s id\n", elem_name);
			goto error;
		}
		append= 1;
		for (node = p_root->children; node!=NULL; node = node->next)
		{
			if( xmlStrcasecmp(node->name,(unsigned char*)"text")==0)
				continue;

			if( xmlStrcasecmp(node->name,(unsigned char*)elem_name)==0)
			{
				id = xmlNodeGetAttrContentByName(node, "id");
				if(id== NULL)
				{
					LM_ERR("while extracting %s id\n", elem_name);
					goto error;
				}

				if(xmlStrcasecmp((unsigned char*)elem_id,
							(unsigned char*)id )== 0)
				{
					append = 0;
					xmlFree(id);
					break;
				}
				xmlFree(id);
			}
		}
		xmlFree(elem_id);
		elem_id= NULL;

append_label:
		if(append)
		{
			LM_DBG("in if\n");
			for(node= new_p_root->children; node; node= node->next)
			{
				LM_DBG("adding node [%s]\n", node->name);
				add_node= xmlCopyNode(node, 1);
				if(add_node== NULL)
				{
					LM_ERR("while copying node [%s]\n", node->name);
					goto error;
				}

				if(xmlAddChild(p_root, add_node)== NULL)
				{
					LM_ERR("while adding child\n");
					goto error;
				}
			}
		}
	}

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

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

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

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

	return body;

error:
	if(xml_array!=NULL)
	{
		for(i=0; i<=j; i++)
		{
			if(xml_array[i]!=NULL)
				xmlFreeDoc( xml_array[i]);
		}
		pkg_free(xml_array);
	}
	if(elem_id)
		xmlFree(elem_id);
	if(body)
		pkg_free(body);
	return NULL;
}
bool Raid::loadFromXml(const std::string& _filename)
{
	if(isLoaded())
		return true;

	xmlDocPtr doc = xmlParseFile(_filename.c_str());
	if(!doc)
	{
		std::cout << "[Error - Raid::loadFromXml] Could not load raid file (" << _filename << ")." << std::endl;
		std::cout << getLastXMLError() << std::endl;
		return false;
	}

	xmlNodePtr root, eventNode;
	root = xmlDocGetRootElement(doc);
	if(xmlStrcmp(root->name,(const xmlChar*)"raid"))
	{
		std::cout << "[Error - Raid::loadFromXml] Malformed raid file (" << _filename << ")." << std::endl;
		xmlFreeDoc(doc);
		return false;
	}

	std::string strValue;
	eventNode = root->children;
	while(eventNode)
	{
		RaidEvent* event;
		if(!xmlStrcmp(eventNode->name, (const xmlChar*)"announce"))
			event = new AnnounceEvent(this, ref);
		else if(!xmlStrcmp(eventNode->name, (const xmlChar*)"effect"))
			event = new EffectEvent(this, ref);
		else if(!xmlStrcmp(eventNode->name, (const xmlChar*)"itemspawn"))
			event = new ItemSpawnEvent(this, ref);
		else if(!xmlStrcmp(eventNode->name, (const xmlChar*)"singlespawn"))
			event = new SingleSpawnEvent(this, ref);
		else if(!xmlStrcmp(eventNode->name, (const xmlChar*)"areaspawn"))
			event = new AreaSpawnEvent(this, ref);
		else if(!xmlStrcmp(eventNode->name, (const xmlChar*)"script"))
			event = new ScriptEvent(this, ref);
		else
		{
			eventNode = eventNode->next;
			continue;
		}

		if(!event->configureRaidEvent(eventNode))
		{
			std::cout << "[Error - Raid::loadFromXml] Could not configure raid in file: " << _filename << ", eventNode: " << eventNode->name << std::endl;
			delete event;
		}
		else
			raidEvents.push_back(event);

		eventNode = eventNode->next;
	}

	//sort by delay time
	std::sort(raidEvents.begin(), raidEvents.end(), RaidEvent::compareEvents);
	xmlFreeDoc(doc);

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

	strcpy(all_name, "all-");

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

				}

				provide_node = provide_node->next;
			}
			
			if(found == 0)
			{
				LM_DBG("delete node: %s\n", doc_node->name);
				dont_provide = doc_node;
				doc_node = doc_node->next;
				xmlUnlinkNode(dont_provide);	
				xmlFreeNode(dont_provide);
			}	
			else
				doc_node = doc_node->next;
	
		}
	}
done:
	xmlDocDumpMemory(doc,(xmlChar**)(void*)&new_body->s,
			&new_body->len);
	LM_DBG("body = \n%.*s\n", new_body->len,
			new_body->s);

    xmlFreeDoc(doc);

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

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

	return NULL;
}
	//	Load colours from the XML file.
	//
	void Colour_Container::load_xml(void)
	{
		char const *error_prefix = __PRETTY_FUNCTION__;
		std::string file_name = "named_colours.xml";

		if (!el_file_exists_anywhere(file_name.c_str()))
			return;

		xmlDocPtr doc;
		xmlNodePtr cur;

		if ((doc = xmlReadFile(file_name.c_str(), NULL, 0)) == NULL)
		{
			LOG_ERROR("%s : Can't open file [%s]\n", error_prefix, file_name.c_str() );
			return;
		}

		if ((cur = xmlDocGetRootElement (doc)) == NULL)
		{
			LOG_ERROR("%s : Empty xml document\n", error_prefix );
			xmlFreeDoc(doc);
			return;
		}

		if (xmlStrcasecmp (cur->name, (const xmlChar *) "named_colours"))
		{
			LOG_ERROR("%s : no named_colours element\n", error_prefix );
			xmlFreeDoc(doc);
			return;
		}

		for (cur = cur->xmlChildrenNode; cur; cur = cur->next)
		{
			if (!xmlStrcasecmp(cur->name, (const xmlChar *)"colour"))
			{
				const int NUM_STR = 5;
				char *read_strings[NUM_STR] = {NULL, NULL, NULL, NULL, NULL};
				const char *names[NUM_STR] = {"name", "r", "g", "b", "a"};
				for (int i=0; i<NUM_STR; i++)
				{
					char *tmp = (char*)xmlGetProp(cur, (xmlChar *)names[i]);
					if (!tmp)
						continue;
					MY_XMLSTRCPY(&read_strings[i], tmp);
					xmlFree(tmp);
				}
				if (read_strings[0])
				{
					GLfloat col_vals[NUM_STR-1] = { -1.0f, -1.0f, -1.0f, 1.0f};
					for (int i=1; i<NUM_STR; i++)
					{
						if (read_strings[i])
						{
							GLfloat tmpcol = -1.0f;
							std::stringstream ss(read_strings[i]);
							if( (ss >> tmpcol).fail() )
								continue;
							col_vals[i-1] = tmpcol;
						}
					}
					bool valid = true;
					for (int i=0; i<NUM_STR-1; i++)
						if (col_vals[i] < 0)
							valid = false;
					if (valid && (NUM_STR == 5))
						add(read_strings[0], Colour_Tuple(col_vals[0],col_vals[1],col_vals[2],col_vals[3]));
				}
				for (int i=0; i<NUM_STR; i++)
					if (read_strings[i])
						free(read_strings[i]);
			}
		}
		xmlFreeDoc(doc);
	}
/**
 * gupnp_didl_lite_parser_parse_didl_recursive:
 * @parser: A #GUPnPDIDLLiteParser
 * @didl: The DIDL-Lite XML string to be parsed
 * @error: The location where to store any error, or %NULL
 *
 * Parses DIDL-Lite XML string @didl, emitting the ::object-available,
 * ::item-available and ::container-available signals appropriately during the
 * process.
 *
 * Return value: TRUE on success.
 **/
gboolean
gupnp_didl_lite_parser_parse_didl_recursive (GUPnPDIDLLiteParser *parser,
                                             const char          *didl,
                                             gboolean             recursive,
                                             GError             **error)
{
        xmlDoc        *doc;
        xmlNode       *element;
        xmlNs         *upnp_ns = NULL;
        xmlNs         *dc_ns   = NULL;
        xmlNs         *dlna_ns = NULL;
        xmlNs         *pv_ns   = NULL;
        GUPnPAVXMLDoc *xml_doc = NULL;
        gboolean       result;

        doc = xmlRecoverMemory (didl, strlen (didl));
        if (doc == NULL) {
                g_set_error (error,
                             G_MARKUP_ERROR,
                             G_MARKUP_ERROR_PARSE,
                             "Could not parse DIDL-Lite XML:\n%s", didl);

                return FALSE;
        }

        /* Get a pointer to root element */
        element = xml_util_get_element ((xmlNode *) doc,
                                        "DIDL-Lite",
                                        NULL);
        if (element == NULL) {
                g_set_error (error,
                             G_MARKUP_ERROR,
                             G_MARKUP_ERROR_PARSE,
                             "No 'DIDL-Lite' node in the DIDL-Lite XML:\n%s",
                             didl);
                xmlFreeDoc (doc);

                return FALSE;
        }

        if (element->children == NULL) {
                g_set_error (error,
                             G_MARKUP_ERROR,
                             G_MARKUP_ERROR_EMPTY,
                             "Empty 'DIDL-Lite' node in the DIDL-Lite XML:\n%s",
                             didl);
                xmlFreeDoc (doc);

                return FALSE;
        }

        /* Create namespaces if they don't exist */
        upnp_ns = xml_util_lookup_namespace (doc, GUPNP_XML_NAMESPACE_UPNP);
        if (! upnp_ns)
                upnp_ns = xml_util_create_namespace (xmlDocGetRootElement (doc),
                                                     GUPNP_XML_NAMESPACE_UPNP);

        dc_ns = xml_util_lookup_namespace (doc, GUPNP_XML_NAMESPACE_DC);
        if (! dc_ns)
                dc_ns = xml_util_create_namespace (xmlDocGetRootElement (doc),
                                                   GUPNP_XML_NAMESPACE_DC);
        dlna_ns = xml_util_lookup_namespace (doc, GUPNP_XML_NAMESPACE_DLNA);
        if (! dlna_ns)
                dlna_ns = xml_util_create_namespace (xmlDocGetRootElement (doc),
                                                   GUPNP_XML_NAMESPACE_DLNA);

        pv_ns = xml_util_lookup_namespace (doc, GUPNP_XML_NAMESPACE_PV);
        if (! pv_ns)
                pv_ns = xml_util_create_namespace (xmlDocGetRootElement (doc),
                                                   GUPNP_XML_NAMESPACE_PV);

        xml_doc = xml_doc_new (doc);

        result = parse_elements (parser,
                                 element,
                                 xml_doc,
                                 upnp_ns,
                                 dc_ns,
                                 dlna_ns,
                                 pv_ns,
                                 recursive,
                                 error);
        xml_doc_unref (xml_doc);

        return result;
}
Exemple #23
0
bool AdminProtocolConfig::loadXMLConfig()
{
	xmlDocPtr doc = xmlParseFile("data/XML/admin.xml");
	if(!doc)
		return false;

	xmlNodePtr root, p, q;
	root = xmlDocGetRootElement(doc);

	if(!xmlStrEqual(root->name,(const xmlChar*)"otadmin"))
	{
		xmlFreeDoc(doc);
		return false;
	}

	int enabled;
	if(readXMLInteger(root, "enabled", enabled))
	{
		if(enabled)
			m_enabled = true;
		else
			m_enabled = false;
	}

	int value;
	p = root->children;
	while(p)
	{
		if(xmlStrEqual(p->name, (const xmlChar*)"security"))
		{
			if(readXMLInteger(p, "onlylocalhost", value))
			{
				if(value)
					m_onlyLocalHost = true;
				else
					m_onlyLocalHost = false;
			}
			if(readXMLInteger(p, "maxconnections", value) && value > 0)
				m_maxConnections = value;
			if(readXMLInteger(p, "loginrequired", value))
			{
				if(value)
					m_requireLogin = true;
				else
					m_requireLogin = false;
			}
			std::string password;
			if(readXMLString(p, "loginpassword", password))
				m_password = password;
			else
			{
				if(m_requireLogin)
					std::cout << "Security warning: require login but use default password." << std::endl;
			}
		}
		else if(xmlStrEqual(p->name, (const xmlChar*)"encryption"))
		{
			if(readXMLInteger(p, "required", value))
			{
				if(value)
					m_requireEncryption = true;
				else
					m_requireEncryption = false;
			}
			q = p->children;
			while(q)
			{
				if(xmlStrEqual(q->name, (const xmlChar*)"key"))
				{
					std::string str;
					if(readXMLString(q, "type", str))
					{
						if(asLowerCaseString(str) == "rsa1024xtea")
						{
							if(readXMLString(q, "file", str))
							{
								m_key_RSA1024XTEA = new RSA();
								if(!m_key_RSA1024XTEA->setKey("data/XML/" + str))
								{
									delete m_key_RSA1024XTEA;
									m_key_RSA1024XTEA = NULL;
									std::cout << "Can not load key from data/XML/" << str << std::endl;
								}
							}
							else
								std::cout << "Missing file for RSA1024XTEA key." << std::endl;
						}
						else
							std::cout << str << " is not a valid key type." << std::endl;
					}
				}
				q = q->next;
			}
		}
		p = p->next;
	}
	xmlFreeDoc(doc);
	return true;
}
bool readEventsFromFile(std::string &epgname, int &ev_count)
{
	xmlDocPtr event_parser = NULL;
	xmlNodePtr service;
	xmlNodePtr event;
	t_original_network_id onid = 0;
	t_transport_stream_id tsid = 0;
	t_service_id sid = 0;

	if (!(event_parser = parseXmlFile(epgname.c_str()))) {
		dprintf("unable to open %s for reading\n", epgname.c_str());
		return false;
	}
	service = xmlDocGetRootElement(event_parser);
	service = xmlChildrenNode(service);

	while (service) {
		onid = xmlGetNumericAttribute(service, "original_network_id", 16);
		tsid = xmlGetNumericAttribute(service, "transport_stream_id", 16);
		sid = xmlGetNumericAttribute(service, "service_id", 16);

		event = xmlChildrenNode(service);

		while (event) {
			SIevent e(onid,tsid,sid,xmlGetNumericAttribute(event, "id", 16));
			uint8_t tid = xmlGetNumericAttribute(event, "tid", 16);
			std::string contentClassification, userClassification;
			if(tid)
				e.table_id = tid;
			e.table_id |= 0x80; /* make sure on-air data has a lower table_id */

			xmlNodePtr node;

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "name"))) {
				const char *s = xmlGetAttribute(node, "string");
				if (s)
					e.setName(ZapitTools::UTF8_to_Latin1(xmlGetAttribute(node, "lang")), s);
				node = xmlNextNode(node);
			}

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "text"))) {
				const char *s = xmlGetAttribute(node, "string");
				if (s)
					e.setText(ZapitTools::UTF8_to_Latin1(xmlGetAttribute(node, "lang")), s);
				node = xmlNextNode(node);
			}
			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "item"))) {
#ifdef USE_ITEM_DESCRIPTION
				const char *s = xmlGetAttribute(node, "string");
				if (s)
					e.item = s;
#endif
				node = xmlNextNode(node);
			}

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "item_description"))) {
#ifdef USE_ITEM_DESCRIPTION
				const char *s = xmlGetAttribute(node, "string");
				if (s)
					e.itemDescription = s;
#endif
				node = xmlNextNode(node);
			}
			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "extended_text"))) {
				const char *l = xmlGetAttribute(node, "lang");
				const char *s = xmlGetAttribute(node, "string");
				if (l && s)
					e.appendExtendedText(ZapitTools::UTF8_to_Latin1(l), s);
				node = xmlNextNode(node);
			}

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "time"))) {
				e.times.insert(SItime(xmlGetNumericAttribute(node, "start_time", 10),
							xmlGetNumericAttribute(node, "duration", 10)));
				node = xmlNextNode(node);
			}

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "content"))) {
				const char cl = xmlGetNumericAttribute(node, "class", 16);
				contentClassification += cl;
				const char cl2 = xmlGetNumericAttribute(node, "user", 16);
				userClassification += cl2;
				node = xmlNextNode(node);
			}

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "component"))) {
				SIcomponent c;
				c.streamContent = xmlGetNumericAttribute(node, "stream_content", 16);
				c.componentType = xmlGetNumericAttribute(node, "type", 16);
				c.componentTag = xmlGetNumericAttribute(node, "tag", 16);
				const char *s = xmlGetAttribute(node, "text");
				if (s)
					c.setComponent(s);
				//e.components.insert(c);
				e.components.push_back(c);
				node = xmlNextNode(node);
			}

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "parental_rating"))) {
				const char *s = xmlGetAttribute(node, "country");
				if (s)
#if 0
					e.ratings.insert(SIparentalRating(ZapitTools::UTF8_to_Latin1(s),
								(unsigned char) xmlGetNumericAttribute(node, "rating", 10)));
#endif
				e.ratings.push_back(SIparentalRating(ZapitTools::UTF8_to_Latin1(s),
							(unsigned char) xmlGetNumericAttribute(node, "rating", 10)));
				node = xmlNextNode(node);
			}

			node = xmlChildrenNode(event);
			while ((node = xmlGetNextOccurence(node, "linkage"))) {
				SIlinkage l;
				l.linkageType = xmlGetNumericAttribute(node, "type", 16);
				l.transportStreamId = xmlGetNumericAttribute(node, "transport_stream_id", 16);
				l.originalNetworkId = xmlGetNumericAttribute(node, "original_network_id", 16);
				l.serviceId = xmlGetNumericAttribute(node, "service_id", 16);
				const char *s = xmlGetAttribute(node, "linkage_descriptor");
				if (s)
					l.name = s;
				e.linkage_descs.insert(e.linkage_descs.end(), l);
				node = xmlNextNode(node);
			}

			if (!contentClassification.empty()) {
#ifdef FULL_CONTENT_CLASSIFICATION
				ssize_t off = e.classifications.reserve(2 * contentClassification.size());
				if (off > -1)
					for (unsigned i = 0; i < contentClassification.size(); i++)
						off = e.classifications.set(off, contentClassification.at(i), userClassification.at(i));
#else
				e.classifications.content = contentClassification.at(0);
				e.classifications.user = userClassification.at(0);
#endif
			}
			addEvent(e, 0);
			ev_count++;

			event = xmlNextNode(event);
		}

		service = xmlNextNode(service);
	}
	xmlFreeDoc(event_parser);
	return true;
}
Exemple #25
0
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;
}
Exemple #26
0
/*
 * Internal handler function
 */
static Datum
handler_internal(Oid function_oid, FunctionCallInfo fcinfo, bool execute)
{
	HeapTuple	proctuple;
	Form_pg_proc pg_proc_entry;
	char	   *sourcecode;
	Datum		prosrcdatum;
	bool		isnull;
	const char **xslt_params;
	int			i;
	Oid		   *argtypes;
	char	  **argnames;
	char	   *argmodes;
	int			numargs;
	xmlDocPtr	ssdoc;
	xmlDocPtr	xmldoc;
	xmlDocPtr	resdoc;
	xsltStylesheetPtr stylesheet;
	int			reslen;
	xmlChar	   *resstr;
	Datum		resdatum;

	if (CALLED_AS_TRIGGER(fcinfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("trigger functions not supported")));

	proctuple = SearchSysCache(PROCOID, ObjectIdGetDatum(function_oid), 0, 0, 0);
	if (!HeapTupleIsValid(proctuple))
		elog(ERROR, "cache lookup failed for function %u", function_oid);

	prosrcdatum = SysCacheGetAttr(PROCOID, proctuple, Anum_pg_proc_prosrc, &isnull);
	if (isnull)
		elog(ERROR, "null prosrc");

	sourcecode = pstrdup(DatumGetCString(DirectFunctionCall1(textout,
															 prosrcdatum)));
	/* allow one blank line at the start */
	if (sourcecode[0] == '\n')
		sourcecode++;

	numargs = get_func_arg_info(proctuple,
								&argtypes, &argnames, &argmodes);

	if (numargs < 1)
		ereport(ERROR,
				(errmsg("XSLT function must have at least one argument")));

				if (argtypes[0] != XMLOID)
		ereport(ERROR,
				(errmsg("first argument of XSLT function must have type XML")));

#if 0
	xsltSetGenericErrorFunc(NULL, xmlGenericError);
#endif

	ssdoc = xmlParseDoc((xmlChar *) sourcecode); /* XXX use backend's xml_parse here() */
	stylesheet = xsltParseStylesheetDoc(ssdoc); /* XXX check error handling */
	if (!stylesheet)
		ereport(ERROR,
				(errmsg("could not parse stylesheet")));

	pg_proc_entry = (Form_pg_proc) GETSTRUCT(proctuple);

	{
		char	   *method;

		method = (char *) stylesheet->method;
		/*
		 * TODO: This is strictly speaking not correct because the
		 * default output method may be "html", but that can only
		 * detected at run time, so punt for now.
		 */
		if (!method)
			method = "xml";

		if (strcmp(method, "xml") == 0 && pg_proc_entry->prorettype != XMLOID)
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
					 errmsg("XSLT stylesheet has output method \"xml\" but return type of function is not xml")));
		else if ((strcmp(method, "html") == 0 || strcmp(method, "text") == 0)
				 && pg_proc_entry->prorettype != TEXTOID && pg_proc_entry->prorettype != VARCHAROID)
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
					 errmsg("XSLT stylesheet has output method \"%s\" but return type of function is not text or varchar", method)));
	}

	/* validation stops here */
	if (!execute)
	{
		ReleaseSysCache(proctuple);
		PG_RETURN_VOID();
	}

	/* execution begins here */

	xslt_params = palloc(((numargs - 1) * 2 + 1) * sizeof(*xslt_params));
	for (i = 0; i < numargs-1; i++)
	{
		xslt_params[i*2] = argnames[i+1];
		xslt_params[i*2+1] = type_to_cstring(PG_GETARG_DATUM(i+1),
											 argtypes[i+1]);
	}
	xslt_params[i*2] = NULL;

	{
		xmltype *arg0 = PG_GETARG_XML_P(0);
		// XXX this ought to use xml_parse()
		xmldoc = xmlParseMemory((char *) VARDATA(arg0), VARSIZE(arg0) - VARHDRSZ);
	}

	resdoc = xsltApplyStylesheet(stylesheet, xmldoc, xslt_params);
	if (!resdoc)
		elog(ERROR, "xsltApplyStylesheet() failed");

	xmlFreeDoc(xmldoc);

	if (xsltSaveResultToString(&resstr, &reslen, resdoc, stylesheet) != 0)
		elog(ERROR, "result serialization failed");

	xsltFreeStylesheet(stylesheet);
	xmlFreeDoc(resdoc);

	xsltCleanupGlobals();
	xmlCleanupParser();

	resdatum = cstring_to_type(resstr ? (char *) resstr : "", pg_proc_entry->prorettype);
	ReleaseSysCache(proctuple);
	PG_RETURN_DATUM(resdatum);
}
Exemple #27
0
void
read_tasks_entries (GUI *appGUI) {

xmlDocPtr doc;
xmlChar *key;
xmlNodePtr node, cnode, category_node, main_node;
GtkTreeIter iter;
gboolean done;
gchar priority[BUFFER_SIZE], category[BUFFER_SIZE];
gchar summary[MAX_SUMMARY_SIZE];
guint32 due_date_julian, start_date_julian, priority_n;


    if (g_file_test (prefs_get_config_filename(TASKS_ENTRIES_FILENAME), G_FILE_TEST_IS_REGULAR) == FALSE) 
        return;

    if((doc = xmlParseFile(prefs_get_config_filename(TASKS_ENTRIES_FILENAME)))) {

        if(!(node = xmlDocGetRootElement(doc))) {
            xmlFreeDoc(doc);
            return;
        }

        if (xmlStrcmp(node->name, (const xmlChar *) TASKS_NAME)) {
            xmlFreeDoc(doc);
            return;
        }

        main_node = node->xmlChildrenNode;

        while (main_node != NULL) {

            if(!xmlStrcmp(main_node->name, (xmlChar *) TASKS_CATEGORY_ENTRIES_NAME)) {

                /* read note */
                category_node = main_node->xmlChildrenNode;

                while (category_node != NULL) {

                    if ((!xmlStrcmp(category_node->name, (const xmlChar *) "name"))) {
                        key = xmlNodeListGetString(doc, category_node->xmlChildrenNode, 1);
                        if (key != NULL) {
                            gtk_list_store_append(appGUI->opt->tasks_category_store, &iter);
                            gtk_list_store_set(appGUI->opt->tasks_category_store, &iter, 0, (gchar *) key, -1);
                        }
                        xmlFree(key);
                    }

                    category_node = category_node->next;
                }
            }

            /*---------------------------------------------------------------------------------------*/

            if(!xmlStrcmp(main_node->name, (xmlChar *) TASKS_ENTRIES_NAME)) {

                /* read note */
                node = main_node->xmlChildrenNode;

                while (node != NULL) {

                    if(!xmlStrcmp(node->name, (xmlChar *) "entry")) {

                        cnode = node->xmlChildrenNode;

                        done = FALSE;
                        due_date_julian = start_date_julian = 0;

                        while (cnode != NULL) {

                            if ((!xmlStrcmp(cnode->name, (const xmlChar *) "status"))) {
                                key = xmlNodeListGetString(doc, cnode->xmlChildrenNode, 1);
                                if (key != NULL) {
                                    sscanf((gchar *) key, "%d", &done);
                                    xmlFree(key);
                                }
                            }
                            if ((!xmlStrcmp(cnode->name, (const xmlChar *) "due_date"))) {
                                key = xmlNodeListGetString(doc, cnode->xmlChildrenNode, 1);
                                if (key != NULL) {
                                    sscanf((gchar *) key, "%d", &due_date_julian);
                                    xmlFree(key);
                                }
                            }
                            if ((!xmlStrcmp(cnode->name, (const xmlChar *) "start_date"))) {
                                key = xmlNodeListGetString(doc, cnode->xmlChildrenNode, 1);
                                if (key != NULL) {
                                    sscanf((gchar *) key, "%d", &start_date_julian);
                                    xmlFree(key);
                                }
                            }
                            if ((!xmlStrcmp(cnode->name, (const xmlChar *) "priority"))) {
                                key = xmlNodeListGetString(doc, cnode->xmlChildrenNode, 1);
                                if (key != NULL) {
                                    strncpy (priority, (gchar *) key, BUFFER_SIZE-1);
                                    if (get_priority_index(gettext(priority)) == -1) {
                                        sscanf((gchar *) key, "%d", &priority_n);
                                        strncpy (priority, get_priority_text(priority_n), BUFFER_SIZE-1);
                                    }
                                    xmlFree(key);
                                }
                            }
                            if ((!xmlStrcmp(cnode->name, (const xmlChar *) "category"))) {
                                key = xmlNodeListGetString(doc, cnode->xmlChildrenNode, 1);
                                if (key != NULL) {
                                    strncpy (category, (gchar *) key, BUFFER_SIZE-1);
                                    xmlFree(key);
                                }
                            }
                            if ((!xmlStrcmp(cnode->name, (const xmlChar *) "summary"))) {
                                key = xmlNodeListGetString(doc, cnode->xmlChildrenNode, 1);
                                if (key != NULL) {
                                    strncpy (summary, (gchar *) key, MAX_SUMMARY_SIZE-1);
                                    xmlFree(key);
                                }
                            }
                            if ((!xmlStrcmp(cnode->name, (const xmlChar *) "description"))) {
                                key = xmlNodeListGetString(doc, cnode->xmlChildrenNode, 1);

                                add_item_to_list(done, due_date_julian, start_date_julian, priority, 
                                                     category, summary, (gchar *) key, appGUI);
                                if (key != NULL) {
                                    xmlFree(key);
                                }
                            }

                            cnode = cnode->next;
                        }

                    }

                    node = node->next;
                }

            }



            /*---------------------------------------------------------------------------------------*/

            main_node = main_node->next;
        }

        xmlFree(node);
        xmlFreeDoc(doc);
    }

}
gboolean
brasero_project_open_project_xml (const gchar *uri,
				  BraseroBurnSession *session,
				  gboolean warn_user)
{
	xmlNodePtr track_node = NULL;
	gchar *label = NULL;
	gchar *cover = NULL;
	xmlDocPtr project;
	xmlNodePtr item;
	gboolean retval;
	GFile *file;
	gchar *path;

	file = g_file_new_for_commandline_arg (uri);
	path = g_file_get_path (file);
	g_object_unref (file);
	if (!path)
		return FALSE;

	/* start parsing xml doc */
	project = xmlParseFile (path);
    	g_free (path);

	if (!project) {
	    	if (warn_user)
			brasero_project_invalid_project_dialog (_("The project could not be opened"));

		return FALSE;
	}

	/* parses the "header" */
	item = xmlDocGetRootElement (project);
	if (!item) {
	    	if (warn_user)
			brasero_project_invalid_project_dialog (_("The file is empty"));

		xmlFreeDoc (project);
		return FALSE;
	}

	if (xmlStrcmp (item->name, (const xmlChar *) "braseroproject")
	||  item->next)
		goto error;

	item = item->children;
	while (item) {
		if (!xmlStrcmp (item->name, (const xmlChar *) "version")) {
			/* simply ignore it */
		}
		else if (!xmlStrcmp (item->name, (const xmlChar *) "label")) {
			label = (gchar *) xmlNodeListGetString (project,
								item->xmlChildrenNode,
								1);
			if (!(label))
				goto error;
		}
		else if (!xmlStrcmp (item->name, (const xmlChar *) "cover")) {
			xmlChar *escaped;

			escaped = xmlNodeListGetString (project,
							item->xmlChildrenNode,
							1);
			if (!escaped)
				goto error;

			cover = g_uri_unescape_string ((char *) escaped, NULL);
			g_free (escaped);
		}
		else if (!xmlStrcmp (item->name, (const xmlChar *) "track")) {
			if (track_node)
				goto error;

			track_node = item;
		}
		else if (item->type == XML_ELEMENT_NODE)
			goto error;

		item = item->next;
	}

	retval = _get_tracks (project, track_node, session);
	if (!retval)
		goto error;

	xmlFreeDoc (project);

        brasero_burn_session_set_label (session, label);
        g_free (label);

        if (cover) {
                GValue *value;

                value = g_new0 (GValue, 1);
                g_value_init (value, G_TYPE_STRING);
                g_value_set_string (value, cover);
                brasero_burn_session_tag_add (session,
                                               BRASERO_COVER_URI,
                                               value);

                g_free (cover);
        }

        return retval;

error:

	if (cover)
		g_free (cover);
	if (label)
		g_free (label);

	xmlFreeDoc (project);
    	if (warn_user)
		brasero_project_invalid_project_dialog (_("It does not seem to be a valid Brasero project"));

	return FALSE;
}
Exemple #29
0
bool BaseEvents::loadFromXml(const std::string& datadir)
{
	if(m_loaded){
		std::cout << "Error: [BaseEvents::loadFromXml] loaded == true" << std::endl;
		return false;
	}
	m_datadir = datadir;
	Event* event = NULL;


	std::string scriptsName = getScriptBaseName();

	if(getScriptInterface().loadFile(std::string(m_datadir + scriptsName + "/lib/" + scriptsName + ".lua")) == -1){
		std::cout << "Warning: [BaseEvents::loadFromXml] Can not load " << scriptsName << " lib/" << scriptsName << ".lua" << std::endl;
	}

	std::string filename = m_datadir + scriptsName + "/" + scriptsName + ".xml";
	xmlDocPtr doc = xmlParseFile(filename.c_str());

	if(doc){
		m_loaded = true;
		xmlNodePtr root, p;
		root = xmlDocGetRootElement(doc);

		if(xmlStrcmp(root->name,(const xmlChar*)scriptsName.c_str()) != 0){
			xmlFreeDoc(doc);
			return false;
		}

		p = root->children;
		while(p){
			if(p->name){
				std::string nodeName = (const char*)p->name;
				if((event = getEvent(nodeName))){
					if(event->configureEvent(p)){
						bool success = true;
						std::string scriptfile;
						if(readXMLString(p, "script", scriptfile)){
							/*if(!event->checkScript(m_datadir, scriptsName, "/scripts/" + scriptfile)){
								success = false;
							}
							else*/
							if(!event->loadScript(m_datadir + scriptsName + "/scripts/" + scriptfile)){
								success = false;
							}
						}
						else if(readXMLString(p, "function", scriptfile)){
							if(!event->loadFunction(scriptfile)){
								success = false;
							}
						}
						else{
							success = false;
						}

						if(success){
							if(!registerEvent(event, p)){
								success = false;
								delete event;
							}
						}
						else{
							delete event;
						}
					}
					else{
						std::cout << "Warning: [BaseEvents::loadFromXml] Can not configure event" << std::endl;
						delete event;
					}
					event = NULL;
				}
			}
			p = p->next;
		}

		xmlFreeDoc(doc);
	}
	else{
		std::cout << "Warning: [BaseEvents::loadFromXml] Can not open " << scriptsName << ".xml" << std::endl;
	}

	return m_loaded;
}
Exemple #30
0
gJobPtr parseGjobFile(char *filename) {
    xmlDocPtr doc;
    gJobPtr ret;
    jobPtr job;
    xmlNsPtr ns;
    xmlNodePtr cur;

    /*
     * build an XML tree from a the file;
     */
    doc = xmlParseFile(filename);
    if (doc == NULL) return(NULL);

    /*
     * Check the document is of the right kind
     */
    
    //    cur = doc->root;
    //    cur = doc->children;
    cur = xmlDocGetRootElement(doc);
    if (cur == NULL) {
        fprintf(stderr,"empty document\n");
	xmlFreeDoc(doc);
	return(NULL);
    }
    ns = xmlSearchNsByHref(doc, cur, "http://www.gnome.org/some-location");
    if (ns == NULL) {
        fprintf(stderr,
	        "document of the wrong type, GJob Namespace not found\n");
	xmlFreeDoc(doc);
	return(NULL);
    }
    if (strcmp(cur->name, "Helping")) {
        fprintf(stderr,"document of the wrong type, root node != Helping");
	xmlFreeDoc(doc);
	return(NULL);
    }

    /*
     * Allocate the structure to be returned.
     */
    ret = (gJobPtr) malloc(sizeof(gJob));
    if (ret == NULL) {
        fprintf(stderr,"out of memory\n");
	xmlFreeDoc(doc);
	return(NULL);
    }
    memset(ret, 0, sizeof(gJob));

    /*
     * Now, walk the tree.
     */
    /* First level we expect just Jobs */
    //    cur = cur->children;
    cur = cur -> children;
    while ( cur && xmlIsBlankNode ( cur ) )
      {
	cur = cur -> next;
      }
    if ( cur == 0 )
      return ( NULL );
    if ((strcmp(cur->name, "Jobs")) || (cur->ns != ns)) {
        fprintf(stderr,"document of the wrong type, was '%s', Jobs expected",
		cur->name);
	fprintf(stderr,"xmlDocDump follows\n");
	xmlDocDump ( stderr, doc );
	fprintf(stderr,"xmlDocDump finished\n");
	xmlFreeDoc(doc);
	free(ret);
	return(NULL);
    }

    /* Second level is a list of Job, but be laxist */
    cur = cur->children;
    while (cur != NULL) {
        if ((!strcmp(cur->name, "Job")) && (cur->ns == ns)) {
	    job = parseJob(doc, ns, cur);
	    if (job != NULL)
	        ret->jobs[ret->nbJobs++] = job;
            if (ret->nbJobs >= 500) break;
	}
	cur = cur->next;
    }

    return(ret);
}