コード例 #1
0
ファイル: zidCache.c プロジェクト: ayham-hassan/bzrtp
/**
 * @brief Parse the cache to find secrets associated to the given ZID, set them and their length in the context if they are found 
 *
 * @param[in/out]	context		the current context, used to get the negotiated Hash algorithm and cache access functions and store result
 * @param[in]		peerZID		a byte array of the peer ZID
 *
 * return 	0 on succes, error code otherwise 
 */
int bzrtp_getPeerAssociatedSecretsHash(bzrtpContext_t *context, uint8_t peerZID[12]) {
	if (context == NULL) {
		return ZRTP_ZIDCACHE_INVALID_CONTEXT;
	}

	/* resert cached secret buffer */
	free(context->cachedSecret.rs1);
	free(context->cachedSecret.rs2);
	free(context->cachedSecret.pbxsecret);
	free(context->cachedSecret.auxsecret);
	context->cachedSecret.rs1 = NULL;
	context->cachedSecret.rs1Length = 0;
	context->cachedSecret.rs2 = NULL;
	context->cachedSecret.rs2Length = 0;
	context->cachedSecret.pbxsecret = NULL;
	context->cachedSecret.pbxsecretLength = 0;
	context->cachedSecret.auxsecret = NULL;
	context->cachedSecret.auxsecretLength = 0;
	context->cachedSecret.previouslyVerifiedSas = 0;

	/* parse the cache to find the peer element matching the given ZID */
	if (context->cacheBuffer != NULL ) { /* there is a cache, try to find our peer element */
		uint8_t peerZidHex[24];
		xmlNodePtr cur;

		bzrtp_int8ToStr(peerZidHex, peerZID, 12); /* compute the peerZID as an Hexa string */

		cur = xmlDocGetRootElement(context->cacheBuffer);
		/* if we found a root element, parse its children node */
		if (cur!=NULL) 
		{
			cur = cur->xmlChildrenNode;
		}
		while (cur!=NULL) {
			if ((!xmlStrcmp(cur->name, (const xmlChar *)"peer"))){ /* found a peer, check his ZID element */
				xmlChar *currentZidHex = xmlNodeListGetString(context->cacheBuffer, cur->xmlChildrenNode->xmlChildrenNode, 1); /* ZID is the first element of peer */
				if (memcmp(currentZidHex, peerZidHex, 24) == 0) { /* we found the peer element we are looking for */
					xmlNodePtr peerNode = cur->xmlChildrenNode->next; /* no need to parse the first child as it is the ZID node */
					while (peerNode != NULL) { /* get all the needed information : rs1, rs2, pbx and aux if we found them */
						xmlChar *nodeContent = NULL;
						if (!xmlStrcmp(peerNode->name, (const xmlChar *)"rs1")) {
							nodeContent = xmlNodeListGetString(context->cacheBuffer, peerNode->xmlChildrenNode, 1);
							context->cachedSecret.rs1 = (uint8_t *)malloc(RETAINED_SECRET_LENGTH);
							context->cachedSecret.rs1Length = RETAINED_SECRET_LENGTH;
							bzrtp_strToUint8(context->cachedSecret.rs1, nodeContent, 2*RETAINED_SECRET_LENGTH); /* RETAINED_SECRET_LENGTH is in byte, the nodeContent buffer is in hexa string so twice the length of byte string */
						}
						if (!xmlStrcmp(peerNode->name, (const xmlChar *)"rs2")) {
							nodeContent = xmlNodeListGetString(context->cacheBuffer, peerNode->xmlChildrenNode, 1);
							context->cachedSecret.rs2 = (uint8_t *)malloc(RETAINED_SECRET_LENGTH);
							context->cachedSecret.rs2Length = RETAINED_SECRET_LENGTH;
							bzrtp_strToUint8(context->cachedSecret.rs2, nodeContent, 2*RETAINED_SECRET_LENGTH); /* RETAINED_SECRET_LENGTH is in byte, the nodeContent buffer is in hexa string so twice the length of byte string */
						}
						if (!xmlStrcmp(peerNode->name, (const xmlChar *)"aux")) {
							nodeContent = xmlNodeListGetString(context->cacheBuffer, peerNode->xmlChildrenNode, 1);
							context->cachedSecret.auxsecretLength = strlen((const char *)nodeContent)/2;
							context->cachedSecret.auxsecret = (uint8_t *)malloc(context->cachedSecret.auxsecretLength); /* aux secret is of user defined length, node Content is an hexa string */
							bzrtp_strToUint8(context->cachedSecret.auxsecret, nodeContent, 2*context->cachedSecret.auxsecretLength); 
						}
						if (!xmlStrcmp(peerNode->name, (const xmlChar *)"pbx")) {
							nodeContent = xmlNodeListGetString(context->cacheBuffer, peerNode->xmlChildrenNode, 1);
							context->cachedSecret.pbxsecret = (uint8_t *)malloc(RETAINED_SECRET_LENGTH);
							context->cachedSecret.pbxsecretLength = RETAINED_SECRET_LENGTH;
							bzrtp_strToUint8(context->cachedSecret.pbxsecret, nodeContent, 2*RETAINED_SECRET_LENGTH); /* RETAINED_SECRET_LENGTH is in byte, the nodeContent buffer is in hexa string so twice the length of byte string */
						}
						if (!xmlStrcmp(peerNode->name, (const xmlChar *)"pvs")) { /* this one is the previously verified sas flag */
							nodeContent = xmlNodeListGetString(context->cacheBuffer, peerNode->xmlChildrenNode, 1);
							if (nodeContent[1] == *"1") { /* pvs is a boolean but is stored as a byte, on 2 hex chars */
								context->cachedSecret.previouslyVerifiedSas = 1;
							}
						}
						xmlFree(nodeContent);
						peerNode = peerNode->next;
					}
					xmlFree(currentZidHex);
					currentZidHex=NULL;
					break;
				}
				xmlFree(currentZidHex);
				currentZidHex=NULL;
			}
			cur = cur->next;
		}
	}

	return 0;
}
コード例 #2
0
/** 
 * verify_request:
 * @mng:                the keys manager
 *
 * Verifies XML signature in the request (stdin).
 *
 * Returns 0 on success or a negative value if an error occurs.
 */
int 
verify_request(xmlSecKeysMngrPtr mngr) {
    xmlBufferPtr buffer = NULL;
    char buf[256];
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlSecDSigCtxPtr dsigCtx = NULL;
    int ret;
    int res = -1;
    
    assert(mngr);

    /* load request in the buffer */    
    buffer = xmlBufferCreate();
    if(buffer == NULL) {
        fprintf(stdout,"Error: failed to create buffer\n");
        goto done;      
    }
    
    while(!feof(stdin)) {
        ret = fread(buf, 1, sizeof(buf), stdin);
        if(ret < 0) {
            fprintf(stdout,"Error: read failed\n");
            goto done;  
        }
        xmlBufferAdd(buffer, buf, ret);
    }

    /* is the document subbmitted from the form? */
    if(strncmp((char*)xmlBufferContent(buffer), "_xmldoc=", 8) == 0) {
        xmlBufferShrink(buffer, 8);
        buffer->use = url_decode((char*)xmlBufferContent(buffer), xmlBufferLength(buffer)); 
    }
        
    /** 
     * Load doc 
     */
    doc = xmlReadMemory(xmlBufferContent(buffer), xmlBufferLength(buffer),
                        NULL, NULL,
                        XML_PARSE_NOENT | XML_PARSE_NOCDATA | 
                        XML_PARSE_PEDANTIC | XML_PARSE_NOCDATA);
    if (doc == NULL) {
        fprintf(stdout, "Error: unable to parse xml document (syntax error)\n");
        goto done;
    }
    
    /*
     * Check the document is of the right kind
     */    
    if(xmlDocGetRootElement(doc) == NULL) {
        fprintf(stdout,"Error: empty document\n");
        goto done;
    }
    
    /* find start node */
    node = xmlSecFindNode(xmlDocGetRootElement(doc), xmlSecNodeSignature, xmlSecDSigNs);
    if(node == NULL) {
        fprintf(stdout, "Error: start <dsig:Signature/> node not found\n");
        goto done;      
    }

    /* create signature context */
    dsigCtx = xmlSecDSigCtxCreate(mngr);
    if(dsigCtx == NULL) {
        fprintf(stdout,"Error: failed to create signature context\n");
        goto done;
    }
    
    /* we would like to store and print out everything */
    /* actually we would not because it opens a security hole
    dsigCtx->flags = XMLSEC_DSIG_FLAGS_STORE_SIGNEDINFO_REFERENCES |
                     XMLSEC_DSIG_FLAGS_STORE_MANIFEST_REFERENCES |
                     XMLSEC_DSIG_FLAGS_STORE_SIGNATURE;
    */

    /* Verify signature */
    if(xmlSecDSigCtxVerify(dsigCtx, node) < 0) {
        fprintf(stdout,"Error: signature verification failed\n");
        goto done;
    }
        
    /* print verification result to stdout */
    if(dsigCtx->status == xmlSecDSigStatusSucceeded) {
        fprintf(stdout, "RESULT: Signature is OK\n");
    } else {
        fprintf(stdout, "RESULT: Signature is INVALID\n");
    }    
    fprintf(stdout, "---------------------------------------------------\n");
    xmlSecDSigCtxDebugDump(dsigCtx, stdout);

    /* success */
    res = 0;

done:    
    /* cleanup */
    if(dsigCtx != NULL) {
        xmlSecDSigCtxDestroy(dsigCtx);
    }
    
    if(doc != NULL) {
        xmlFreeDoc(doc); 
    }
    
    if(buffer != NULL) {
        xmlBufferFree(buffer);
    }
    return(res);
}
コード例 #3
0
ファイル: rs-profile-camera.c プロジェクト: bgromov/rawstudio
gchar *
rs_profile_camera_find(const gchar *make, const gchar *model)
{
	static gchar *last_make = NULL;
	static gchar *last_model = NULL;
	static gchar *last_id = NULL;

	if (NULL == make ||  NULL == model)
		return NULL;

	if (last_make && last_model)
	{
		if (g_str_equal(make, last_make) && g_str_equal(model, last_model))
			return last_id ? g_strdup(last_id) : NULL;

		g_free(last_make);
		g_free(last_model);
		if (last_id)
			g_free(last_id);

		last_make = g_strdup(make);
		last_model = g_strdup(model);
		last_id = NULL;
	}
	static gchar *filename = NULL;
	xmlDocPtr doc;
	xmlNodePtr cur;
	xmlNodePtr camera = NULL;
	xmlNodePtr exif = NULL;
	xmlChar *xml_unique_id, *xml_make, *xml_model;

	if (!filename)
		filename = g_build_filename(rs_confdir_get(), G_DIR_SEPARATOR_S, "profiles" G_DIR_SEPARATOR_S "rawstudio-cameras.xml", NULL);

	if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
	{
		g_free(filename);
		filename = NULL;
	}

	if (!filename)
		filename = g_build_filename(PACKAGE_DATA_DIR, PACKAGE, "profiles" G_DIR_SEPARATOR_S "rawstudio-cameras.xml", NULL);

	if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
		return NULL;

	doc = xmlParseFile(filename);
	if (!doc)
		return NULL;

	cur = xmlDocGetRootElement(doc);

	camera = cur->xmlChildrenNode;
	while(camera)
	{
		if (!xmlStrcmp(camera->name, BAD_CAST "camera"))
		{
			xml_unique_id = xmlGetProp(camera, BAD_CAST "unique_id");

			exif = camera->xmlChildrenNode;
			while(exif)
			{
				if (!xmlStrcmp(exif->name, BAD_CAST "exif"))
				{
					xml_make = xmlGetProp(exif, BAD_CAST "make");
					if (g_strcmp0((gchar *) xml_make, make) == 0)
					{
						xml_model = xmlGetProp(exif, BAD_CAST "model");
						if (g_strcmp0((gchar *) xml_model, model) == 0)
						{
							xmlFree(xml_make);
							xmlFree(xml_model);
							gchar *unique_id = g_strdup((gchar *) xml_unique_id);
							xmlFree(xml_unique_id);
							xmlFree(doc);
							last_id = g_strdup(unique_id);
							return  unique_id;
						}
						xmlFree(xml_model);
					}
					xmlFree(xml_make);
				}
				exif = exif->next;

			}
			xmlFree(xml_unique_id);
		}
		camera = camera->next;
	}
	xmlFree(doc);
	g_warning("Could not find unique camera: Make:'%s'. Model:'%s'", make, model);
	return NULL;
}
コード例 #4
0
ファイル: xpath.c プロジェクト: AmesianX/php-src
static void php_xpath_eval(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
	zval *id, retval, *context = NULL;
	xmlXPathContextPtr ctxp;
	xmlNodePtr nodep = NULL;
	xmlXPathObjectPtr xpathobjp;
	size_t expr_len, nsnbr = 0, xpath_type;
	dom_xpath_object *intern;
	dom_object *nodeobj;
	char *expr;
	xmlDoc *docp = NULL;
	xmlNsPtr *ns = NULL;
	zend_bool register_node_ns = 1;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Os|O!b", &id, dom_xpath_class_entry, &expr, &expr_len, &context, dom_node_class_entry, &register_node_ns) == FAILURE) {
		return;
	}

	intern = Z_XPATHOBJ_P(id);

	ctxp = (xmlXPathContextPtr) intern->dom.ptr;
	if (ctxp == NULL) {
		php_error_docref(NULL, E_WARNING, "Invalid XPath Context");
		RETURN_FALSE;
	}

	docp = (xmlDocPtr) ctxp->doc;
	if (docp == NULL) {
		php_error_docref(NULL, E_WARNING, "Invalid XPath Document Pointer");
		RETURN_FALSE;
	}

	if (context != NULL) {
		DOM_GET_OBJ(nodep, context, xmlNodePtr, nodeobj);
	}

	if (!nodep) {
		nodep = xmlDocGetRootElement(docp);
	}

	if (nodep && docp != nodep->doc) {
		php_error_docref(NULL, E_WARNING, "Node From Wrong Document");
		RETURN_FALSE;
	}

	ctxp->node = nodep;

	if (register_node_ns) {
		/* Register namespaces in the node */
		ns = xmlGetNsList(docp, nodep);

		if (ns != NULL) {
			while (ns[nsnbr] != NULL)
			nsnbr++;
		}
	}


    ctxp->namespaces = ns;
    ctxp->nsNr = nsnbr;

	xpathobjp = xmlXPathEvalExpression((xmlChar *) expr, ctxp);
	ctxp->node = NULL;

	if (ns != NULL) {
		xmlFree(ns);
		ctxp->namespaces = NULL;
		ctxp->nsNr = 0;
	}

	if (! xpathobjp) {
		RETURN_FALSE;
	}

	if (type == PHP_DOM_XPATH_QUERY) {
		xpath_type = XPATH_NODESET;
	} else {
		xpath_type = xpathobjp->type;
	}

	switch (xpath_type) {

		case  XPATH_NODESET:
		{
			int i;
			xmlNodeSetPtr nodesetp;

			array_init(&retval);

			if (xpathobjp->type == XPATH_NODESET && NULL != (nodesetp = xpathobjp->nodesetval)) {

				for (i = 0; i < nodesetp->nodeNr; i++) {
					xmlNodePtr node = nodesetp->nodeTab[i];
					zval child;
					
					if (node->type == XML_NAMESPACE_DECL) {
						xmlNsPtr curns;
						xmlNodePtr nsparent;

						nsparent = node->_private;
						curns = xmlNewNs(NULL, node->name, NULL);
						if (node->children) {
							curns->prefix = xmlStrdup((xmlChar *) node->children);
						}
						if (node->children) {
							node = xmlNewDocNode(docp, NULL, (xmlChar *) node->children, node->name);
						} else {
							node = xmlNewDocNode(docp, NULL, (xmlChar *) "xmlns", node->name);
						}
						node->type = XML_NAMESPACE_DECL;
						node->parent = nsparent;
						node->ns = curns;
					}
					php_dom_create_object(node, &child, &intern->dom);
					add_next_index_zval(&retval, &child);
				}
			}
			php_dom_create_interator(return_value, DOM_NODELIST);
			nodeobj = Z_DOMOBJ_P(return_value);
			dom_xpath_iter(&retval, nodeobj);
			break;
		}

		case XPATH_BOOLEAN:
			RETVAL_BOOL(xpathobjp->boolval);
			break;

		case XPATH_NUMBER:
			RETVAL_DOUBLE(xpathobjp->floatval)
			break;

		case XPATH_STRING:
			RETVAL_STRING((char *) xpathobjp->stringval);
			break;

		default:
			RETVAL_NULL();
			break;
	}

	xmlXPathFreeObject(xpathobjp);
}
コード例 #5
0
ファイル: xmlpars.c プロジェクト: eleckis/fmtbenchmarks
/**
 * Parse incoming message, send all data to msg
 * @param msg domain model msg
 * @param ibuf input buffer
 * @param ilen input buffer len
 * @return SUCCEED/FAIL
 */
int parse_msg(Message_t *msg, char *ibuf, long ilen)
{
    int ret = SUCCEED;
    msgbuilder_t *descr;
    char *buf;
    
    short *p_short;
    long *p_long;
    
    char *cp;
    
    void *fld_ptr;
    char *p_string_el;
    xmlDocPtr   doc;
    xmlNodePtr  rootNode;
    xmlNode *currentNode = NULL;
    short item;
    
    /* start libxml2 XML doc */
    
    doc = xmlReadMemory( ibuf, strlen(ibuf), NULL, NULL, 0 );
	
    if ( NULL == doc )
    {
        TP_LOG(log_error, "Failed to read XML document!");
        return FAIL;
    }

    rootNode = xmlDocGetRootElement( doc );
    
    currentNode = rootNode->children;
            
    /* loop over all tags */
    for (; currentNode;
                    currentNode = currentNode->next )
    {
        /* find tag descriptor */
        if (NULL==(descr = get_tag((char *)currentNode->name)))
        {
            TP_LOG(log_error, "Failed to get tag descr for [%s]", 
                    currentNode->name);
            ret = FAIL;
            goto out;
        }
        
        /* get the content of the tag */
        if (NULL==(buf = (char *)xmlNodeGetContent(currentNode)))
        {
            TP_LOG(log_error, "NULL tag: [%s]", currentNode->name);
            ret = FAIL;
            goto out;
        }
        
        TP_LOG(log_debug, "got tag [%s] value [%s]", currentNode->name, 
                buf?buf:"(null)");
        
        /* load the field into struct accordingly */
        fld_ptr = (char *)msg + descr->msgoffs + descr->elmoffs;
        
        switch (descr->elmtyp)
        {
            case MSG_SHORT:
                p_short =  (short *)fld_ptr;
                *p_short = atoi(buf);
                break;
            case MSG_LONG:
                p_long =  (long *)fld_ptr;
                *p_long = atol(buf);
                break;
            case MSG_STRING:
                strcpy((char *)fld_ptr, buf);
                break;
            case MSG_ARRAY_SHORT:
                
                /* get item number from tag */
                cp = strchr(currentNode->name, '_');
                cp++;
                
                item = atoi(cp);
                p_short = (short *)( (char *)fld_ptr + item*sizeof(short));
                *p_short = atoi(buf);
                
                break;
            case MSG_ARRAY_STRING:
                
                /* get item number from tag */
                cp = strchr(currentNode->name, '_');
                cp++;
                
                item = atoi(cp);
                p_string_el = ( (char *)fld_ptr + item*MAX_STR);
                strcpy(p_string_el, buf);
                
                break;
            default:
                TP_LOG(log_error, "Unknown element type %d!", descr->elmtyp);
                ret=FAIL;
                goto out;
                break;
        }
        
         xmlFree(buf);
         
    }
    
out:
    if(doc)
    {
        xmlFreeDoc(doc);
    }

    return ret;
}
コード例 #6
0
ファイル: monitor_db.c プロジェクト: Whisprin/ddccontrol
/* recursionlevel: Protection against looping includes
 * default_caps: CAPS passed to ddcci_create_db (read from the monitor)
 * prof_caps: CAPS read from one of the profile (NULL if none has been read yet)
 */
int ddcci_create_db_protected(
	struct monitor_db* mon_db, const char* pnpname, struct caps* caps, int recursionlevel,
	char* defined, int faulttolerance)
{
	xmlDocPtr mon_doc;
	xmlNodePtr root, mon_child, mon_control;
	xmlChar *tmp;
	char buffer[256];
	
	if (options_doc == NULL) {
		fprintf(stderr, _("Database must be inited before reading a monitor file.\n"));
		return 0;
	}
	
	snprintf(buffer, 256, "%s/monitor/%s.xml", datadir, pnpname);
	mon_doc = xmlParseFile(buffer);
	if (mon_doc == NULL) {
		fprintf(stderr, _("Document not parsed successfully.\n"));
		return 0;
	}
	
	root = xmlDocGetRootElement(mon_doc);
	
	if (root == NULL) {
		fprintf(stderr,  _("empty monitor/%s.xml\n"), pnpname);
		xmlFreeDoc(mon_doc);
		return 0;
	}
	
	if (xmlStrcmp(root->name, (const xmlChar *) "monitor")) {
		fprintf(stderr,  _("monitor/%s.xml of the wrong type, root node %s != monitor"), pnpname, root->name);
		xmlFreeDoc(mon_doc);
		return 0;
	}
		
	if (!mon_db->name) {
		mon_db->name = xmlGetProp(root, BAD_CAST "name");
		DDCCI_DB_RETURN_IF(mon_db->name == NULL, 0,  _("Can't find name property."), root);
	}
	
	if ((mon_db->init == unknown) && (tmp = xmlGetProp(root, BAD_CAST "init"))) {
		if (!(xmlStrcmp(tmp, (const xmlChar *)"standard"))) {
			mon_db->init = standard;
		}
		else if (!(xmlStrcmp(tmp, (const xmlChar *)"samsung"))) {
			mon_db->init = samsung;
		}
		else {
			DDCCI_DB_RETURN_IF(1, 0,  _("Invalid type."), root);
		}
		xmlFree(tmp);
	}
	
	if ((tmp = xmlGetProp(root, BAD_CAST "caps"))) {
		if (faulttolerance)
			fprintf(stderr, "Warning: caps property is deprecated.\n");
		else {
			fprintf(stderr, "Error: caps property is deprecated.\n");
			return 0;
		}
	}
	
	if ((tmp = xmlGetProp(root, BAD_CAST "include"))) {
		if (faulttolerance)
			fprintf(stderr, "Warning: include property is deprecated.\n");
		else {
			fprintf(stderr, "Error: include property is deprecated.\n");
			return 0;
		}
	}
	
	/* Create group-subgroup structure (we'll clean it up later) */
	if (!recursionlevel) {
		/*printf("Creating struct...\n");*/
		xmlNodePtr group, subgroup;
		xmlChar *options_groupname, *options_subgroupname;
		
		struct group_db *current_group;
		struct group_db **last_group_ref = &mon_db->group_list;
		
		/* List groups (options.xml) */
		for (group = xmlDocGetRootElement(options_doc)->xmlChildrenNode; group != NULL; group = group->next)
		{
			options_groupname = NULL;
			if (xmlStrcmp(group->name, (const xmlChar *) "group")) { // Not a group
				continue;
			}
			*last_group_ref = current_group = malloc(sizeof(struct group_db));
			memset(current_group, 0, sizeof(struct group_db));
			last_group_ref = &current_group->next;
			/*printf("On group %p\n", current_group);*/
			
			options_groupname = xmlGetProp(group, BAD_CAST "name");
			DDCCI_DB_RETURN_IF(options_groupname == NULL, 0,  _("Can't find name property."), group);
			current_group->name = _D((char*)options_groupname); /* Note: copy string, so we can free options_groupname */
			xmlFree(options_groupname);
			
			struct subgroup_db *current_subgroup;
			struct subgroup_db **last_subgroup_ref = &current_group->subgroup_list;
			
			/* List subgroups (options.xml) */
			for (subgroup = group->xmlChildrenNode; subgroup != NULL; subgroup = subgroup->next)
			{
				options_subgroupname = NULL;
				if (xmlStrcmp(subgroup->name, (const xmlChar *) "subgroup")) { // Not a subgroup
					continue;
				}
				*last_subgroup_ref = current_subgroup = malloc(sizeof(struct subgroup_db));
				memset(current_subgroup, 0, sizeof(struct subgroup_db));
				last_subgroup_ref = &current_subgroup->next;
				
				/*printf("On subgroup %p\n", current_subgroup);*/
				
				options_subgroupname = xmlGetProp(subgroup, BAD_CAST "name");
				DDCCI_DB_RETURN_IF(options_subgroupname == NULL, 0,  _("Can't find name property."), subgroup);
				
				current_subgroup->name = _D((char*)options_subgroupname); /* Note: copy string, so we can free options_subgroupname */
				xmlFree(options_subgroupname);
				current_subgroup->pattern = xmlGetProp(subgroup, BAD_CAST "pattern");
			}
		}
	}
	
	mon_child = root->xmlChildrenNode;
	mon_control = NULL;
	
	int controls_or_include = 0;
	while (mon_child != NULL) {
		if (!xmlStrcmp(mon_child->name, (const xmlChar *) "caps")) {
			xmlChar* remove = xmlGetProp(mon_child, BAD_CAST "remove");
			xmlChar* add = xmlGetProp(mon_child, BAD_CAST "add");
			DDCCI_DB_RETURN_IF(!remove && !add, 0,  _("Can't find add or remove property in caps."), mon_child);
			if (remove)
				DDCCI_DB_RETURN_IF(ddcci_parse_caps((char*)remove, caps, 0) <= 0, 0,  _("Invalid remove caps."), mon_child);
			if (add)
				DDCCI_DB_RETURN_IF(ddcci_parse_caps((char*)add, caps, 1) <= 0, 0,  _("Invalid add caps."), mon_child);
		}
		else if (!xmlStrcmp(mon_child->name, (const xmlChar *) "include")) {
			controls_or_include = 1;
			if (recursionlevel > 15) {
				fprintf(stderr,  _("Error, include recursion level > 15 (file: %s).\n"), pnpname);
				mon_db = NULL;
				return 0;
			}
			
			xmlChar* file = xmlGetProp(mon_child, BAD_CAST "file");
			DDCCI_DB_RETURN_IF(file == NULL, 0,  _("Can't find file property."), mon_child);
			if (!ddcci_create_db_protected(mon_db, (char*)file, caps, recursionlevel+1, defined, faulttolerance)) {
				xmlFree(file);
				return 0;
			}
			xmlFree(file);
		}
		else if (!xmlStrcmp(mon_child->name, (const xmlChar *) "controls")) {
			DDCCI_DB_RETURN_IF(mon_control != NULL, 0,  _("Two controls part in XML file."), root);
			controls_or_include = 1;
			mon_control = mon_child;
			/* Find, if possible, each element of options_doc in mon_doc. */
			xmlNodePtr mon_control_child, group, subgroup, control;
			
			struct group_db *current_group = mon_db->group_list;
			
			int ncontrols = 0; /* Number of controls in monitor file */
			char *matchedcontrols; /* Array of monitor controls with (=1) or without (=0) corresponding global control */
			
			/* Compute nvalues */
			mon_control_child = mon_control->xmlChildrenNode;
			while (mon_control_child) {
				if (mon_control_child->type == XML_ELEMENT_NODE) {
					ncontrols++;
				}
				mon_control_child = mon_control_child->next;
			}
			
			matchedcontrols = malloc((ncontrols+1)*sizeof(char)); /* Will not be freed on error, no problem */
			memset(matchedcontrols, 0, ncontrols*sizeof(char));
			
			/*printf("Filling struct...\n");*/
			
			/* List groups (options.xml) */
			for (group = xmlDocGetRootElement(options_doc)->xmlChildrenNode; group != NULL; group = group->next)
			{
				if (xmlStrcmp(group->name, (const xmlChar *) "group")) { // Not a group
					continue;
				}
				/*printf("On group %p\n", current_group);*/
				
				struct subgroup_db *current_subgroup = current_group->subgroup_list;
				
				/* List subgroups (options.xml) */
				for (subgroup = group->xmlChildrenNode; subgroup != NULL; subgroup = subgroup->next)
				{
					if (xmlStrcmp(subgroup->name, (const xmlChar *) "subgroup")) { // Not a subgroup
						continue;
					}
					/*printf("On subgroup %p\n", current_subgroup);*/
					
					control = subgroup->xmlChildrenNode;
					
					DDCCI_DB_RETURN_IF(
						!ddcci_add_controls_to_subgroup(control, mon_control, current_subgroup, caps->vcp,
							defined, matchedcontrols, faulttolerance), 0,  _("Error enumerating controls in subgroup."), control);
					current_subgroup = current_subgroup->next;
				}
				current_group = current_group->next;
			}
			
			int i = 0;
			mon_control_child = mon_control->xmlChildrenNode;
			while (mon_control_child) {
				if (mon_control_child->type == XML_ELEMENT_NODE) {
					if (!matchedcontrols[i]) {
						tmp = xmlGetProp(mon_control_child, BAD_CAST "id");
						fprintf(stderr, _("Element %s (id=%s) has not been found (line %ld).\n"), mon_control_child->name, tmp, XML_GET_LINE(mon_control_child));
						xmlFree(tmp);
						if (!faulttolerance)
							return 0;
					}
					i++;
				}
				mon_control_child = mon_control_child->next;
			}
			
			free(matchedcontrols);
		} /* mon_child->name == "controls" */
		
		mon_child = mon_child->next;
	}
	
	if (!recursionlevel) {
		struct group_db** group;
		struct subgroup_db** subgroup;
		
		/* loop through groups */
		group = &mon_db->group_list;
		while (*group != NULL)
		{
			/* loop through subgroups inside group */
			subgroup = &((*group)->subgroup_list);
			while (*subgroup != NULL)
			{
				if (!(*subgroup)->control_list) {
					*subgroup = (*subgroup)->next;
					continue;
				}
				subgroup = &(*subgroup)->next;
			}
			if (!(*group)->subgroup_list) {
				*group = (*group)->next;
				continue;
			}
			group = &(*group)->next;
		}
	}
	
	if (!controls_or_include) {
		fprintf(stderr,  _("document of the wrong type, can't find controls or include.\n"));
		xmlFreeDoc(mon_doc);
		return 0;
	}
	
	xmlFreeDoc(mon_doc);
	
	return 1;
}
コード例 #7
0
ファイル: vocation.cpp プロジェクト: Ablankzin/server
bool Vocations::loadFromXml(const std::string& datadir)
{
	std::string filename = datadir + "vocations.xml";

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

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

		p = root->children;

		while(p){
			if(xmlStrcmp(p->name, (const xmlChar*)"vocation") == 0){
				std::string str;
				int intVal;
				float floatVal;
				Vocation* voc = NULL;
				xmlNodePtr skillNode;
				if(readXMLInteger(p, "id", intVal)){
					voc = new Vocation(intVal);
					if(readXMLString(p, "name", str)){
						voc->name = str;
					}
					if(readXMLString(p, "description", str)){
						voc->description = str;
					}
					if(readXMLInteger(p, "gaincap", intVal)){
						voc->gainCap = intVal;
					}
					if(readXMLInteger(p, "gainhp", intVal)){
						voc->gainHP = intVal;
					}
					if(readXMLInteger(p, "gainmana", intVal)){
						voc->gainMana = intVal;
					}
					if(readXMLInteger(p, "gainhpticks", intVal)){
						voc->gainHealthTicks = intVal;
					}
					if(readXMLInteger(p, "gainhpamount", intVal)){
						voc->gainHealthAmount = intVal;
					}
					if(readXMLInteger(p, "gainmanaticks", intVal)){
						voc->gainManaTicks = intVal;
					}
					if(readXMLInteger(p, "gainmanaamount", intVal)){
						voc->gainManaAmount = intVal;
					}
					if(readXMLInteger(p, "maxsoul", intVal)){
						voc->maxSoul = intVal;
					}
					if(readXMLInteger(p, "gainsoulticks", intVal)){
						voc->gainSoulTicks = intVal;
					}
					if(readXMLFloat(p, "manamultiplier", floatVal)){
						voc->manaMultiplier = floatVal;
					}
					skillNode = p->children;
					while(skillNode){
						if(xmlStrcmp(skillNode->name, (const xmlChar*)"skill") == 0){
							SkillType skill_id;
							try {
								if(readXMLInteger(skillNode, "id", intVal)){
									skill_id = SkillType::fromInteger(intVal);
								} else if(readXMLString(skillNode, "name", str)){
									skill_id = SkillType::fromString(str);
								}
								if(readXMLInteger(skillNode, "base", intVal)){
									voc->skillBases[skill_id.value()] = intVal;
								}
								if(readXMLFloat(skillNode, "multiplier", floatVal)){
									voc->skillMultipliers[skill_id.value()] = floatVal;
								}
							} catch(enum_conversion_error&){
								std::cout << "Missing skill id ." << std::endl;
							}
						}
						else if(xmlStrcmp(skillNode->name, (const xmlChar*)"damage") == 0){
							if(readXMLFloat(skillNode, "magicDamage", floatVal)){
								voc->magicBaseDamage = floatVal;
							}
							if(readXMLFloat(skillNode, "wandDamage", floatVal)){
								voc->wandBaseDamage = floatVal;
							}
							if(readXMLFloat(skillNode, "healingDamage", floatVal)){
								voc->healingBaseDamage = floatVal;
							}
						}
						else if(xmlStrcmp(skillNode->name, (const xmlChar*)"meleeDamage") == 0){
							if(readXMLFloat(skillNode, "sword", floatVal)){
								voc->swordBaseDamage = floatVal;
							}
							if(readXMLFloat(skillNode, "axe", floatVal)){
								voc->axeBaseDamage = floatVal;
							}
							if(readXMLFloat(skillNode, "club", floatVal)){
								voc->clubBaseDamage = floatVal;
							}
							if(readXMLFloat(skillNode, "dist", floatVal)){
								voc->distBaseDamage = floatVal;
							}
							if(readXMLFloat(skillNode, "fist", floatVal)){
								voc->fistBaseDamage = floatVal;
							}
						}
						else if(xmlStrcmp(skillNode->name, (const xmlChar*)"defense") == 0){
							if(readXMLFloat(skillNode, "baseDefense", floatVal)){
								voc->baseDefense = floatVal;
							}
							if(readXMLFloat(skillNode, "armorDefense", floatVal)){
								voc->armorDefense = floatVal;
							}
						}
						skillNode = skillNode->next;
					}

					//std::cout << "Voc id: " << voc_id << std::endl;
					//voc->debugVocation();
					vocationsMap[voc->getID()] = voc;

				}
				else{
					std::cout << "Missing vocation id." << std::endl;
				}
			}
			p = p->next;
		}
		xmlFreeDoc(doc);
	}
	return true;
}
コード例 #8
0
ファイル: parser.c プロジェクト: BackupTheBerlios/grootevent
/* parser for the complete xml file */
GList *parseDoc (char *docname)
{
  xmlDocPtr doc;
  xmlNodePtr cur;
    
  xmlParserCtxtPtr ctxt;
  
  eventlist = g_list_alloc ();		 /* allocates memory for new list */

  if (getValidate() == TRUE)
  {
    ctxt = xmlCreateFileParserCtxt(docname);

    if (ctxt == NULL)
    {    
      exit (1);
    }
 
    ctxt->validate = 1;			 /* check the XML's DTD */
    xmlParseDocument(ctxt);

    if (!ctxt->valid)
    {
      g_print ("Please correct this problem or grootevent isn't able to run.\n"
	       "Hint: You could also disable validating (--help for more infos)\n");
      exit (1);
    }
  } 

  doc = xmlParseFile (docname);
  
  if (doc == NULL)
  {
    fprintf (stderr, "Document not parsed successfully. \n");
    return NULL;
  }

  cur = xmlDocGetRootElement (doc);

  if (cur == NULL)
  {
    fprintf (stderr, "empty document\n");
    xmlFreeDoc (doc);
    return NULL;
  }

  if (xmlStrcmp (cur->name, (const xmlChar *) "grootevent"))
  {
    fprintf (stderr, "document of the wrong type, root node != grootevent\n");
    xmlFreeDoc (doc);
    return NULL;
  }

  cur = cur->xmlChildrenNode;
  while (cur != NULL)
  {
    if ((!xmlStrcmp (cur->name, (const xmlChar *) "eventinfo")))
    {
      parseEventInfo (doc, cur);
    }

    cur = cur->next;
  }

  xmlFreeDoc (doc);
  return eventlist;
}
コード例 #9
0
ファイル: vocation.cpp プロジェクト: CkyLua/tfs
bool Vocations::loadFromXml()
{
	std::string filename = "data/XML/vocations.xml";

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

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

		p = root->children;

		while(p)
		{
			std::string str;
			int32_t intVal;
			if(xmlStrcmp(p->name, (const xmlChar*)"vocation") == 0)
			{
				Vocation* voc = new Vocation();
				uint32_t voc_id;
				xmlNodePtr configNode;
				if(readXMLInteger(p, "id", intVal))
				{
					float floatVal;

					voc_id = intVal;
					if(readXMLString(p, "name", str))
						voc->name = str;

					if(readXMLInteger(p, "clientid", intVal))
						voc->clientId = intVal;

					if(readXMLString(p, "description", str))
						voc->description = str;

					if(readXMLInteger(p, "gaincap", intVal))
						voc->gainCap = intVal;

					if(readXMLInteger(p, "gainhp", intVal))
						voc->gainHP = intVal;

					if(readXMLInteger(p, "gainmana", intVal))
						voc->gainMana = intVal;

					if(readXMLInteger(p, "gainhpticks", intVal))
						voc->gainHealthTicks = intVal;

					if(readXMLInteger(p, "gainhpamount", intVal))
						voc->gainHealthAmount = intVal;

					if(readXMLInteger(p, "gainmanaticks", intVal))
						voc->gainManaTicks = intVal;

					if(readXMLInteger(p, "gainmanaamount", intVal))
						voc->gainManaAmount = intVal;

					if(readXMLFloat(p, "manamultiplier", floatVal))
						voc->manaMultiplier = floatVal;

					if(readXMLInteger(p, "attackspeed", intVal))
						voc->attackSpeed = intVal;

					if(readXMLInteger(p, "basespeed", intVal))
						voc->baseSpeed = intVal;

					if(readXMLInteger(p, "soulmax", intVal))
						voc->soulMax = intVal;

					if(readXMLInteger(p, "gainsoulticks", intVal))
						voc->gainSoulTicks = intVal;

					if(readXMLInteger(p, "fromvoc", intVal))
						voc->fromVocation = intVal;

					configNode = p->children;
					while(configNode)
					{
						if(xmlStrcmp(configNode->name, (const xmlChar*)"skill") == 0)
						{
							uint32_t skill_id;
							if(readXMLInteger(configNode, "id", intVal))
							{
								skill_id = intVal;
								if(skill_id > SKILL_LAST)
									std::cout << "No valid skill id. " << skill_id << std::endl;
								else
								{
									if(readXMLFloat(configNode, "multiplier", floatVal))
										voc->skillMultipliers[skill_id] = floatVal;
								}
							}
							else
								std::cout << "Missing skill id." << std::endl;
						}
						else if(xmlStrcmp(configNode->name, (const xmlChar*)"formula") == 0)
						{
							if(readXMLFloat(configNode, "meleeDamage", floatVal))
								voc->meleeDamageMultipler = floatVal;

							if(readXMLFloat(configNode, "distDamage", floatVal))
								voc->distDamageMultipler = floatVal;

							if(readXMLFloat(configNode, "defense", floatVal))
								voc->defenseMultipler = floatVal;

							if(readXMLFloat(configNode, "armor", floatVal))
								voc->armorMultipler = floatVal;
						}
						configNode = configNode->next;
					}
					vocationsMap[voc_id] = voc;
				}
				else
					std::cout << "Missing vocation id." << std::endl;
			}
			p = p->next;
		}
		xmlFreeDoc(doc);
	}
	return true;
}
コード例 #10
0
ファイル: validate.c プロジェクト: unizeto/bmd
/**
 * Funkcja dokonuje weryfikacji poprawności złożonego podpisu pod formularzem.
 * \param[in] mngr Zainicjalizowany menedżer kluczy.
 * \param[in] buffer Formularz do zweryfikowania.
 * \param[in] buffer_len Długość weryfikowanego formularza.
 *
 * \retval 0 Podpis poprawny.
 * \retval 1 Podpis niepoprawny.
 * \retval -1 Nie można przeparsować dokumentu.
 * \retval -2 Nie znaleziono startowego węzła.
 * \retval -3 Nie dało się utworzyć kontekstu podpisu.
 * \retval -4 Nie dało rady zweryfikować podpisu.
 * */
static long verify_memory(xmlSecKeysMngrPtr mngr, const char* buffer, const long buffer_len) {
	xmlDocPtr doc = NULL;
	xmlNodePtr node = NULL;
	xmlSecDSigCtxPtr dsigCtx = NULL;
	long ret = -99;

	assert(mngr);

	/* load file */
	doc = xmlParseMemory(buffer,buffer_len);
	if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
		PRINT_DEBUG("UNABLE TO PARSE DOCUMENT\n");
		ret = -1;
		goto done;
	}

	/* find start node */
	node = xmlSecFindNode(xmlDocGetRootElement(doc), xmlSecNodeSignature, xmlSecDSigNs);
	if(node == NULL) {
		PRINT_DEBUG("Start node %s not found\n",xmlSecNodeSignature);
		ret = -2;
		goto done;
	}

	/* create signature context */
	dsigCtx = xmlSecDSigCtxCreate(mngr);
	if(dsigCtx == NULL) {
		PRINT_DEBUG("Failed to create signature context\n");
		ret = -3;
		goto done;
	}

	/* Verify signature */
	if(xmlSecDSigCtxVerify(dsigCtx, node) < 0) {
		PRINT_DEBUG("Error: signature verify failed\n");
		ret = -4;
		goto done;
	}


	/* print verification result to stdout */
	if(dsigCtx->status == xmlSecDSigStatusSucceeded) {
		ret = 0;
		PRINT_DEBUG("XAdES: Signature is OK\n");
	} else {
		ret = 1;
		PRINT_DEBUG("XAdES: Signature is INVALID\n");
	}


done:
			/* cleanup */
			if(dsigCtx != NULL) {
	xmlSecDSigCtxDestroy(dsigCtx);
			}

			if(doc != NULL) {
				xmlFreeDoc(doc);
			}
			return(ret);
}
コード例 #11
0
ファイル: arfeed.cpp プロジェクト: gardess/ISA
/**
 * Funkce, která zpracuje xml získané ze zadané stránky
 * @param	char*	uložení obsahu stránky
 * @param	int		velikost obsahu stránky
 * @param	Param*	struktura se zadanými parametry
 */
static void zpracujXML(char *docname, int xmlVelikost, Param* parametr)
{
	xmlDocPtr doc;
	xmlNodePtr cur;
	xmlNodePtr temp;
	xmlNodePtr pocitadlo;

	doc = xmlParseMemory(docname, xmlVelikost);
	if (doc == NULL )
	{
		cerr << "Chyba, nepodarilo se zpracovat xml" << endl;
		return;
	}
	
	cur = xmlDocGetRootElement(doc);
	
	if (cur == NULL)
	{
		cerr << "Chyba, prazdne xml" << endl;
		xmlFreeDoc(doc);
		return;
	}
	
	if (xmlStrcmp(cur->name, (const xmlChar *) "feed"))
	{
		cerr << "Chyba, korenovy element xml se nejmenuje feed" << endl;
		xmlFreeDoc(doc);
		return;
	}

	if ((!xmlStrcmp(cur->name, (const xmlChar *)"feed")))
	{
		obsahElementu(doc, cur, (xmlChar *)"title", NAZEV);
	}
	cur = cur->xmlChildrenNode;
	pocitadlo = cur;
	int s = 0;
	// Zjištění počtu feedů v xml pro pozdější výpis mezer
	while(pocitadlo != NULL)
	{
		if ((!xmlStrcmp(pocitadlo->name, (const xmlChar *)"entry")))
		{
			s++;
		}
		pocitadlo = pocitadlo->next;
	}

	int iterace = 0;
	int nalezlA = 0;
	//int nalezlU = 0, nalezlT = 0;
	while(cur != NULL)
	{
		// Vyhledani elementu "entry" v kořenovém elementu
		if ((!xmlStrcmp(cur->name, (const xmlChar *)"entry")))
		{
			iterace++;
			// Volani funkce pro vypis nazvu clanku
			obsahElementu(doc, cur, (xmlChar *)"title", NAZEVNOVINKY);
			if (parametr->aParam == 1)
			{
				temp = cur->xmlChildrenNode;
				while(temp != NULL)
				{
					// Vyhledani elementu author v elementu entry
					if ((!xmlStrcmp(temp->name, (const xmlChar *)"author")))
					{
						// Volani funkce pro vypis autora, pouze pokud je zadan parametr -a
						obsahElementu(doc, temp, (xmlChar *)"name", AUTOR); // Parametr -a
						nalezlA = 1;
					}
					temp = temp->next; 
				}
				if (nalezlA == 0)
				{
				cout << "Autor: " << "No author" << endl;
				nalezlA = 1;
				}
			}
			// Volani funkce pro vypis datumu aktualizace, pouze pokud je zadan parametr -T
			if (parametr->TParam == 1)
			{
				obsahElementu(doc, cur, (xmlChar *)"updated", AKTUALIZACE); // Parametr -T
				//nalezlT = 1;
			}
			// Volani funkce pro ziskani parametru z xml tagu a jeho nasledne vypsani, pouze pokud je zadan parametr -u
			if (parametr->uParam == 1)
			{
				odkaz(cur); // Parametr -u
				//nalezlU = 1;
			}
			if (parametr->lParam == 1) // Nevypisuji mezeru protoze je pouze jeden zaznam
			{
				;
			}
			else if (iterace == s) // Posledni zaznam nevypisovat mezeru
			{
				; 
			}
			else if ((parametr->aParam == 1) || (parametr->uParam == 1) || (parametr->TParam == 1))
			{
				cout << "" << endl;
			}
		}
		// Pro zobrazeni pouze prvni novinky ("feedu")
		if ((parametr->lParam == 1) && (iterace == 1))
		{
			break;
		}
		nalezlA = 0;
		//nalezlU = 0;
		//nalezlT = 0;	 
		cur = cur->next;
	}
	xmlFreeDoc(doc);
	return;
}
コード例 #12
0
ファイル: validate.c プロジェクト: unizeto/bmd
/**
 * Funkcja porównuje zawartość pól X509IssuerName, X509SerialNumber i CertDigest
 * w certyfikacie i w formularzu.
 * \retval -1 Nie można przeparsować dokumentu.
 * \retval -2 Nie można pobrać info certyfikatu z formularza.
 * \retval -3 Nie można pobrać info z formularza.
 * \retval -4 Niezgodne numery seryjne.
 * \retval -5 Niezgodne nazwy wystawców.
 * \retval -6 Nie można utworzyć skrótu z certyfikatu.
 * \retval -7 Nie można pobrać skrótu certyfikatu z formularza.
 * \retval -8 Niezgodne skróty z certyfikatów.
 * \retval -9 Certyfikat przeterminowany.
 * */
long verify_fields(const char *buffer, const long buffer_len, GenBuf_t *timestamp)
{
	xmlDocPtr document 		= NULL;
	char *CertSerialNumber	= NULL;	/*serial sczytany z certyfikatu*/
	char *FormSerialNumber	= NULL;	/*serial sczytany z formularza*/
	char *CertIssuerName		= NULL; 	/*wystawca sczytany z certyfikatu*/
	char *FormIssuerName		= NULL; 	/*wystawca sczytany z formularza*/
	char *CertDigest			= NULL;	/*digest w base64 do porównania*/
	char *FormDigest			= NULL;	/*digest z formularza*/
	GenBuf_t *certyfikat		= NULL;	/*genbuf z certyfikatem*/
	LIBBMDXADES_DIGEST_METHOD_t metoda;
	long status;

	/*kontrola poprawnosci parametrow*/
	if (buffer == NULL)
	{
		PRINT_DEBUG("Wrong argument 1\n");
		return ERR_arg+1;
	}

	if (buffer_len == 0)
	{
		PRINT_DEBUG("Wrong argument 2 (too short!)\n");
		return ERR_arg+2;
	}

	/* load file */
	document = xmlParseMemory(buffer,buffer_len);
	if ((document == NULL) || (xmlDocGetRootElement(document) == NULL))
	{
		PRINT_DEBUG("UNABLE TO PARSE DOCUMENT\n");
		return -1;
	}

	/* pobieramy certyfikat*/
	status = _getCertificateFromXML(&document, &certyfikat);
	if (status < 0)
	{
		PRINT_DEBUG("Error while getting certificate.\n");
		return -2;
	}

	/*pobieramy date waznosci*/
	status = isCertificateValid(&certyfikat, timestamp);
	if (status < 0)
	{
		PRINT_DEBUG("Error - certificate not valid!\n");
		return -9;
	}

	/* get Serial and IssuerName from certificate in the form*/
	status = _getInfoFromCertificate(&certyfikat, &CertSerialNumber, &CertIssuerName);
	if (status < 0)
	{
		PRINT_DEBUG("Error while getting info from X509 Certificate.\n");
		return -2;
	}
	PRINT_VDEBUG("Form signed by certificate issued by %s, serial: %s\n",
					 CertIssuerName, CertSerialNumber);

	/* get Serial and IssuerName from the form*/
	_getInfoFromXML(&document, &FormSerialNumber, &FormIssuerName);
	if (status < 0)
	{
		PRINT_DEBUG("Error while getting info from the form.\n");
		return -3;
	}

	/*porównujemy seriale*/
	status = _compareSerials(&CertSerialNumber, &FormSerialNumber);
	if (status != 0)
	{
		PRINT_DEBUG("Bad serial number.\n");
		return -4;
	}

	/*porównujemy wystawcow*/
	status = _compareIssuerNames(&CertIssuerName, &FormIssuerName);
	if (status != 0)
	{
		PRINT_DEBUG("Bad issuer name.\n");
		return -5;
	}

	/*sprawdzamy digest*/
	status = _getDigestAndMethod(&document, &FormDigest, &metoda);
	if (status < 0)
	{
		PRINT_DEBUG("Cannot get digests from XML!\n");
		return -7;
	}
	_getCertificateDigest(&certyfikat, metoda, &CertDigest);
	if (status < 0)
	{
		PRINT_DEBUG("Error while digesting certificate!\n");
		return -6;
	}
	if (strcmp(FormDigest, CertDigest)!= 0)
	{
		PRINT_DEBUG("Digests in cert and XML vary!\n");
		return -8;
	}

	/*sprzatamy*/
	free(CertIssuerName);
	free(CertSerialNumber);
	free(FormIssuerName);
	free(FormSerialNumber);
	free(CertDigest);
	free(FormDigest);
	free_gen_buf(&certyfikat);
	xmlFreeDoc(document);
	return 0;
}
コード例 #13
0
ファイル: zidCache.c プロジェクト: ayham-hassan/bzrtp
int bzrtp_getSelfZID(bzrtpContext_t *context, uint8_t selfZID[12]) {
	uint8_t *selfZidHex = NULL;

	if (context == NULL) {
		return ZRTP_ZIDCACHE_INVALID_CONTEXT; 
	}
	/* load the cache buffer and parse it to an xml doc. TODO: lock it as we may write it */
	if (context->zrtpCallbacks.bzrtp_loadCache != NULL) {
		uint8_t *cacheStringBuffer;
		uint32_t cacheStringLength;
		zrtpFreeBuffer_callback cb=NULL;
		context->zrtpCallbacks.bzrtp_loadCache(context->ZIDCacheData, &cacheStringBuffer, &cacheStringLength, &cb);
		context->cacheBuffer = xmlParseDoc(cacheStringBuffer);
		if (cb!=NULL) cb(cacheStringBuffer);
	} else {
		/* we are running cacheless, return a random number */
		bctbx_rng_get(context->RNGContext, selfZID, 12);
		return 0; 
	}

	if (context->cacheBuffer != NULL ) { /* there is a cache, try to find our ZID */
		xmlNodePtr cur = xmlDocGetRootElement(context->cacheBuffer);
		/* if we found a root element, parse its children node */
		if (cur!=NULL) 
		{
			cur = cur->xmlChildrenNode;
		}
		while (cur!=NULL) {
			if ((!xmlStrcmp(cur->name, (const xmlChar *)"selfZID"))){ /* self ZID found, extract it */
				selfZidHex = xmlNodeListGetString(context->cacheBuffer, cur->xmlChildrenNode, 1);		
				/* convert it from hexa string to bytes string */
				bzrtp_strToUint8(selfZID, selfZidHex, strlen((char *)selfZidHex));
				break;
			}
			cur = cur->next;
		}
	}


	/* if we didn't found anything in cache, or we have no cache at all: generate ZID, cache string and write it to file */
	if (selfZidHex==NULL) {
		uint8_t newZidHex[25];
		xmlNodePtr rootNode;

		/* generate a random ZID */
		bctbx_rng_get(context->RNGContext, selfZID, 12);
		/* convert it to an Hexa String */
		bzrtp_int8ToStr(newZidHex, selfZID, 12);
		newZidHex[24] = '\0'; /* the string must be null terminated for libxml2 to add it correctly in the element */
		xmlFree(context->cacheBuffer);
		/* Create a new xml doc */
		context->cacheBuffer = xmlNewDoc((const xmlChar *)"1.0");
		/* root tag is "cache" */
		rootNode = xmlNewDocNode(context->cacheBuffer, NULL, (const xmlChar *)"cache", NULL);
	    xmlDocSetRootElement(context->cacheBuffer, rootNode);
		/* add the ZID child */
		xmlNewTextChild(rootNode, NULL, (const xmlChar *)"selfZID", newZidHex);
		
		/* write the cache file and unlock it(TODO)*/
		bzrtp_writeCache(context);
	}
	/* TODO unlock the cache */
	xmlFree(selfZidHex);

	return 0;
}
コード例 #14
0
ファイル: zidCache.c プロジェクト: ayham-hassan/bzrtp
/**
 * @brief Write the given taf into peer Node, if the tag exists, content is replaced
 * Cache file is locked(TODO), read and updated during this call
 *
 * @param[in/out]	context				the current context, used to get the negotiated Hash algorithm and cache access functions and store result
 * @param[in]		peerZID				a byte array of the peer ZID
 * @param[in]		tagName				the tagname of node to be written, it MUST be null terminated
 * @param[in]		tagNameLength		the length of tagname (not including the null termination char)
 * @param[in]		tagContent			the content of the node(a byte buffer which will be converted to hexa string)
 * @param[in]		tagContentLength	the length of the content to be written(not including the null termination)
 * @param[in]		nodeFlag			Flag, if the ISSTRING bit is set write directly the value into the tag, otherwise convert the byte buffer to hexa string
 * 										if the MULTIPLETAGS bit is set, allow multiple tags with the same name inside the peer node(only if their value differs)
 * @param[in]		fileFlag			Flag, if LOADFILE bit is set, reload the cache buffer from file before updatin.
 * 										if WRITEFILE bit is set, update the cache file
 * 
 * Note : multiple tags mode manage string content only
 *
 * return 0 on success, error code otherwise
 */
int bzrtp_writePeerNode(bzrtpContext_t *context, uint8_t peerZID[12], uint8_t *tagName, uint8_t tagNameLength, uint8_t *tagContent, uint32_t tagContentLength, uint8_t nodeFlag, uint8_t fileFlag) {
	uint8_t *tagContentHex; /* this one will store the actual value to be written in cache */

	if ((context == NULL) || (context->zrtpCallbacks.bzrtp_loadCache == NULL)) {
		return ZRTP_ZIDCACHE_INVALID_CONTEXT;
	}

	if ((nodeFlag&BZRTP_CACHE_ISSTRINGBIT) == BZRTP_CACHE_TAGISBYTE) { /* tag content is a byte buffer, convert it to hexa string */
		/* turn the tagContent to an hexa string null terminated */
		tagContentHex = (uint8_t *)malloc(2*tagContentLength+1);
		bzrtp_int8ToStr(tagContentHex, tagContent, tagContentLength);
		tagContentHex[2*tagContentLength] = '\0';
	} else { /* tag content is a string, write it directly */
		tagContentHex = (uint8_t *)malloc(tagContentLength+1);
		memcpy(tagContentHex, tagContent, tagContentLength+1); /* duplicate the string to have it in the same variable in both case and be able to free it at the end */
	}

	if ((fileFlag&BZRTP_CACHE_LOADFILEBIT) == BZRTP_CACHE_LOADFILE) { /* we must reload the cache from file */
		uint8_t *cacheStringBuffer;
		uint32_t cacheStringLength;
		zrtpFreeBuffer_callback cb=NULL;

		/* reload cache from file locking it (TODO: lock) */
		xmlFreeDoc(context->cacheBuffer);
		context->cacheBuffer = NULL;
		context->zrtpCallbacks.bzrtp_loadCache(context->ZIDCacheData, &cacheStringBuffer, &cacheStringLength,&cb);
		context->cacheBuffer = xmlParseDoc(cacheStringBuffer);
		if (cb) cb(cacheStringBuffer);
	}

	/* parse the cache to find the peer element matching the given ZID */
	if (context->cacheBuffer != NULL ) { /* there is a cache, try to find our peer element */
		uint8_t peerZidHex[25];
		xmlNodePtr rootNode;
		xmlNodePtr cur = NULL;
		uint8_t nodeUpdated = 0; /* a boolean flag set if node is updated */

		bzrtp_int8ToStr(peerZidHex, peerZID, 12); /* compute the peerZID as an Hexa string */
		peerZidHex[24]='\0';

		rootNode = xmlDocGetRootElement(context->cacheBuffer);
		/* if we found a root element, parse its children node */
		if (rootNode!=NULL) 
		{
			cur = rootNode->xmlChildrenNode->next; /* first node is selfZID, don't parse it */
		}
		while (cur!=NULL) {
			if ((!xmlStrcmp(cur->name, (const xmlChar *)"peer"))){ /* found a peer, check his ZID element */
				xmlChar *currentZidHex = xmlNodeListGetString(context->cacheBuffer, cur->xmlChildrenNode->xmlChildrenNode, 1); /* ZID is the first element of peer */
				if (!xmlStrcmp(currentZidHex, (const xmlChar *)peerZidHex)) { /* we found the peer element we are looking for */
					xmlNodePtr peerNodeChildren = cur->xmlChildrenNode->next;
					while (peerNodeChildren != NULL && nodeUpdated==0) { /* look for the tag we want to write */
						if ((!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)tagName))){ /* check if we already have the tag we want to write */
							if ((nodeFlag&BZRTP_CACHE_MULTIPLETAGSBIT) == BZRTP_CACHE_ALLOWMULTIPLETAGS) { /* multiple nodes with the same name are allowed, check the current one have a different value */
								/* check if the node found have the same content than the one we want to add */
								xmlChar *currentNodeContent = xmlNodeListGetString(context->cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
								if (!xmlStrcmp((const xmlChar *)currentNodeContent, (const xmlChar *)tagContent)) { /* contents are the same, do nothing and get out */
									nodeUpdated = 1;
								} else { /* tagname is the same but content differs, keep on parsing this peer node */
									peerNodeChildren = peerNodeChildren->next;
								}
								xmlFree(currentNodeContent);
							} else { /* no multiple tags with the same name allowed, overwrite the content in any case */
								xmlNodeSetContent(peerNodeChildren, (const xmlChar *)tagContentHex);
								nodeUpdated = 1;
							}
						} else {
							peerNodeChildren = peerNodeChildren->next;
						}
					}
					if (nodeUpdated == 0) { /* if we didn't found our node, add it at the end of peer node */
						xmlNewTextChild(cur, NULL, (const xmlChar *)tagName, tagContentHex);
						nodeUpdated = 1;
					}
					xmlFree(currentZidHex);
					currentZidHex=NULL;
					break;
				}
				xmlFree(currentZidHex);
				currentZidHex=NULL;
			}
			cur = cur->next;
		}

		/* we didn't find the peer element, create it with nodes ZID and tagName */
		if (nodeUpdated == 0) {
			xmlNodePtr peerNode = xmlNewNode(NULL, (const xmlChar *)"peer");
			xmlNewTextChild(peerNode, NULL, (const xmlChar *)"ZID", peerZidHex);
			xmlNewTextChild(peerNode, NULL, (const xmlChar *)tagName, tagContentHex);
			xmlAddChild(rootNode, peerNode);
		}


		/* write the cache file if requested and unlock it(TODO)*/
		if ((fileFlag&BZRTP_CACHE_WRITEFILEBIT) == BZRTP_CACHE_WRITEFILE) {
			bzrtp_writeCache(context);
		}
	}

	free(tagContentHex);

	return 0;
}
コード例 #15
0
ファイル: repository.cpp プロジェクト: BackupTheBerlios/mops
int ProcessPackage(const char *filename, const struct stat *file_status, int filetype)
{
	//XMLNode tmpX;
	unsigned short x=0, y=0;

	if (file_status->st_ino!=0) x=y;

	mDebug("processing package "+ (string) filename);
       	string ext = getExtension(filename);

	if (filetype==FTW_F)
	{
		if (ext!="tgz" && ext!="spkg") return 0;

		pkgcounter++;
		printf("[%d/%d] indexing file %s\n",pkgcounter,pkgcount_ftw, filename);
//		cout<< "indexing file " << filename << "..."<<endl;
		FILE *log=fopen("index.log", "a");
		LocalPackage lp(filename);
		mDebug("PP 0-0");
		int errCode = lp.injectFile(true);
		//printf("injectFile returned %d\n", errCode);
		mDebug("PP 00-1");
		if (log)
		{
			if (errCode==0)
			{
				fprintf(log, "indexing package %s: OK\n", filename);
				fclose(log);
			}
			else 
			{
				fprintf(log, "indexing file %s FAILED: error code %d\n", filename, errCode);
				fclose(log);
			//	printf("Returning FAILURE\n");
				return 0;
			}

		}
		else mError("unable to open log file");

		mDebug("PP 0-2");
		if (_rootNode == NULL) {
			mDebug("[3]_rootNode == NULL");
		} else {
			mDebug("[3]_rootNode != NULL");
		}
		if (__doc == NULL) {
			mDebug("[2] _root == NULL");
		} else {
			mDebug("[2] _root != NULL");
		}

		int bufsize;
		xmlChar * membuf = lp.getPackageXMLNodeXPtr(&bufsize);
		xmlDocPtr __tmpXmlDoc = xmlParseMemory((const char *) membuf, bufsize);//"UTF-8", 0);
		xmlFree(membuf);
		xmlNodePtr __packagesRootNode = xmlDocGetRootElement(__tmpXmlDoc);

		if (__tmpXmlDoc == 0) {
			mDebug("Temp xml doc error");
		} else {
			mDebug("temp xml doc ok");
		}

		if (__packagesRootNode == NULL) {
			mDebug("package xml root node error");
		} else {
			mDebug("package xml root node ok");
			const xmlChar * __root_node_name = __packagesRootNode->name;
			mDebug(" __packagesRootNode->name = " + (string) (const char *)__root_node_name);
		}

		xmlNodePtr __node  = xmlAddChild(_rootNode, __packagesRootNode);
		if (__node == NULL) {
			mDebug("new package xml node error");
		} else {
			mDebug("new package xml node ok");
			const xmlChar * __st = __node->name;
			mDebug("new package xml node name = " + (string) (const char *)__st);
		}

		if (__packagesRootNode == NULL) {
			mDebug("root package xml after apped error");
		} else {
			mDebug("root package xml after apped ok");
			const xmlChar * __st = __packagesRootNode->name;
			mDebug("root package xml node name = " + (string) (const char *)__st);
		}

		/*mDebug("Saving temp repo xml dump ");
		FILE *__xmlDump = fopen("/tmp/xmldump-repo.xml", "w");
		if (xmlDocDump(__xmlDump, __doc) != -1) {
			fclose(__xmlDump);
			mDebug("temp Xml dump saved");
		} else {
			fclose(__xmlDump);
			mDebug("temp Xml dump failed");
		}*/

		mDebug("PP 0-3");
		
		// Dupe check
		for (unsigned int i=0; i<pkgDupeNames.size(); i++)
		{
			if (*lp.data.get_name()==pkgDupeNames[i])
			{
				// Dupe found, notify!
				say("%sWarning!%s duplicate package found for %s\n", CL_RED, CL_WHITE, lp.data.get_name()->c_str());
				FILE *duplog = fopen("dupes.log", "a");
				if (duplog)
				{
					fprintf(duplog, "%s%s\n", lp.data.get_locations()->at(0).get_full_url().c_str(), filename);
					fclose(duplog);
				}
			}
		}
		pkgDupeNames.push_back(*lp.data.get_name());
	}
	//printf("Normal return\n");
	return 0;
}
コード例 #16
0
gboolean
_gtk_source_language_file_parse_version1 (GtkSourceLanguage    *language,
        GtkSourceContextData *ctx_data)
{
    xmlDocPtr doc;
    xmlNodePtr cur;
    GMappedFile *mf;
    gunichar esc_char = 0;
    xmlChar *lang_version = NULL;

    xmlKeepBlanksDefault (0);

    mf = g_mapped_file_new (language->priv->lang_file_name, FALSE, NULL);

    if (mf == NULL)
    {
        doc = NULL;
    }
    else
    {
        doc = xmlParseMemory (g_mapped_file_get_contents (mf),
                              g_mapped_file_get_length (mf));

        g_mapped_file_unref (mf);
    }

    if (doc == NULL)
    {
        g_warning ("Impossible to parse file '%s'",
                   language->priv->lang_file_name);
        return FALSE;
    }

    cur = xmlDocGetRootElement (doc);

    if (cur == NULL)
    {
        g_warning ("The lang file '%s' is empty",
                   language->priv->lang_file_name);
        goto error;
    }

    if (xmlStrcmp (cur->name, (const xmlChar *) "language") != 0)
    {
        g_warning ("File '%s' is of the wrong type",
                   language->priv->lang_file_name);
        goto error;
    }

    lang_version = xmlGetProp (cur, BAD_CAST "version");

    if (lang_version == NULL || strcmp ("1.0", (char*) lang_version) != 0)
    {
        if (lang_version != NULL)
            g_warning ("Wrong language version '%s' in file '%s', expected '%s'",
                       (char*) lang_version, language->priv->lang_file_name, "1.0");
        else
            g_warning ("Language version missing in file '%s'",
                       language->priv->lang_file_name);
        goto error;
    }

    if (!define_root_context (ctx_data, language))
    {
        g_warning ("Could not create root context for file '%s'",
                   language->priv->lang_file_name);
        goto error;
    }

    /* FIXME: check that the language name, version, etc. are the
     * right ones - Paolo */

    cur = xmlDocGetRootElement (doc);
    cur = cur->xmlChildrenNode;
    g_return_val_if_fail (cur != NULL, FALSE);

    while (cur != NULL)
    {
        if (!xmlStrcmp (cur->name, (const xmlChar *)"escape-char"))
        {
            xmlChar *escape;

            escape = xmlNodeListGetString (doc, cur->xmlChildrenNode, 1);
            esc_char = g_utf8_get_char_validated ((gchar*) escape, -1);

            if (esc_char == (gunichar) -1 || esc_char == (gunichar) -2)
            {
                g_warning ("Invalid (non UTF8) escape character in file '%s'",
                           language->priv->lang_file_name);
                esc_char = 0;
            }

            xmlFree (escape);
        }
        else
        {
            parseTag (language, cur, ctx_data);
        }

        cur = cur->next;
    }

    if (esc_char != 0)
        _gtk_source_context_data_set_escape_char (ctx_data, esc_char);

    _gtk_source_context_data_finish_parse (ctx_data, NULL, NULL);
    _gtk_source_language_define_language_styles (language);

    xmlFreeDoc (doc);
    xmlFree (lang_version);
    return TRUE;

error:
    if (doc)
        xmlFreeDoc (doc);
    xmlFree (lang_version);
    return FALSE;
}
コード例 #17
0
ファイル: repository.cpp プロジェクト: BackupTheBerlios/mops
// Add other such functions for other repository types.
int Repository::get_index(string server_url, PACKAGE_LIST *packages, unsigned int type)
{
	if (actionBus._abortActions)
	{
		actionBus._abortComplete=true;
		actionBus.setActionState(ACTIONID_DBUPDATE, ITEMSTATE_ABORTED);
		return MPKGERROR_ABORTED;
	}

	currentStatus = "Updating data from "+ server_url+"...";
	mDebug("get_index!");
	// First: detecting repository type
	// Trying to download in this order (if successful, we have detected a repository type):
	// 1. packages.xml.gz 	(Native MOPSLinux)
	// 2. PACKAGES.TXT	(Legacy Slackware)
	// 3. Packages.gz	(Debian)
	// (and something else for RPM, in future)
	string index_filename = get_tmp_file();
	string md5sums_filename = get_tmp_file();
	if (!dialogMode) say("[%s] ...\r",server_url.c_str());
	string cm = "gunzip -f "+index_filename+".gz 2>/dev/null";
	if (type == TYPE_MPKG || type == TYPE_AUTO)
	{
		actionBus.getActionState(0);
		mDebug("trying MPKG, type = "+ IntToStr(type));
	       if (CommonGetFile(server_url + "packages.xml.gz", index_filename+".gz")==DOWNLOAD_OK)
		{
			actionBus.getActionState(0);
			mDebug("download ok, validating contents...");
			if (system(cm.c_str())==0 && \
					ReadFile(index_filename).find("<?xml version=\"1.0\"")!=std::string::npos && ReadFile(index_filename).find("<repository")!=std::string::npos)
			{
				currentStatus = "Detected native MPKG repository";
				type = TYPE_MPKG;
			}
		}
	}
	if (actionBus._abortActions)
	{
		actionBus._abortComplete=true;
		actionBus.setActionState(ACTIONID_DBUPDATE, ITEMSTATE_ABORTED);
		return MPKGERROR_ABORTED;
	}

	if (type == TYPE_SLACK || type == TYPE_AUTO)
	{
		
		mDebug("trying SLACK, type = "+ IntToStr(type));
		if (CommonGetFile(server_url + "PACKAGES.TXT", index_filename)==DOWNLOAD_OK)
		{
			mDebug("download ok, validating contents...");
			if (ReadFile(index_filename).find("PACKAGE NAME:  ")!=std::string::npos)
			{
				currentStatus = _("Detected legacy Slackware repository");
				if (CommonGetFile(server_url + "CHECKSUMS.md5", md5sums_filename) == DOWNLOAD_OK)
				{
					type = TYPE_SLACK;
				}
				else 
				{
					mError(_("Error downloading checksums"));
					return -1; // Download failed: no checksums or checksums download error
				}
			}
		}
	}
	if (actionBus._abortActions)
	{
		actionBus._abortComplete=true;
		actionBus.setActionState(ACTIONID_DBUPDATE, ITEMSTATE_ABORTED);
		return MPKGERROR_ABORTED;
	}

	if (type == TYPE_DEBIAN || type == TYPE_AUTO)
	{
		if(CommonGetFile(server_url + "Packages.gz", index_filename+".gz")==DOWNLOAD_OK)
		{
			type = TYPE_DEBIAN;
		}
	}

	if (type != TYPE_MPKG && type != TYPE_SLACK && type!=TYPE_DEBIAN)
	{
		currentStatus = _("Error updating data from ") +server_url+_(": download error or unsupported type");
		mError(_("Error downloading package index: download error, or unsupported repository type"));
		return -1;
	}
	mDebug("Starting to parse index");
	PACKAGE *pkg = new PACKAGE;
	string xml_name=index_filename;
//	XMLNode *repository_root = new XMLNode;
	
	xmlDocPtr indexDoc;
	xmlNodePtr indexRootNode;
	
//	int pkg_count;
	int ret=0;
	currentStatus = "["+server_url+"] Importing data...";
	if (actionBus._abortActions)
	{
		actionBus._abortComplete=true;
		actionBus.setActionState(ACTIONID_DBUPDATE, ITEMSTATE_ABORTED);
		return MPKGERROR_ABORTED;
	}
	string *pList = new string;
	string *mList = new string;
	//XMLNode *tmp = new XMLNode;
	//xmlDocPtr indexDoc;
	//xmlNodePtr indexRootNode;
	switch(type)
	{
		case TYPE_MPKG:
			indexDoc = xmlReadFile(xml_name.c_str(), "UTF-8", 0);
			if (indexDoc == NULL) {
				xmlFreeDoc(indexDoc);
				mError("ппц...");
				return -1;
			}
			else mDebug("indexDoc read successfully");
			
			indexRootNode = xmlDocGetRootElement(indexDoc);
			if (indexRootNode == NULL) {
				mError(_("Failed to get index"));
				xmlFreeDoc(indexDoc);
			}
			else mDebug("indexRootNode read successfully");
			
			if (xmlStrcmp(indexRootNode->name, (const xmlChar *) "repository") ) {
				mError(_("Invalid index file"));
				xmlFreeDoc(indexDoc);
			}
			else mDebug("Found valid repository index");
			
			xmlXPathContextPtr xContext;
			xmlXPathObjectPtr xResult;
			
			xContext = xmlXPathNewContext(indexDoc);
			if (xContext == NULL) {
				mError("ппц");
			}
			
			xResult = xmlXPathEvalExpression((const xmlChar *)"/repository/package", xContext);
			if (xResult == NULL) {
				mError("XPath expression error");
			}
			
			if (xmlXPathNodeSetIsEmpty(xResult->nodesetval)) {
				xmlXPathFreeObject(xResult);

				printf(_("[%s] ... Nothing found\n"), server_url.c_str());
				//mError("No packages found");
				return 0;
			}
			
			xmlNodeSetPtr xNodeSet;
			int xi;
			
			actionBus.setActionProgress(ACTIONID_DBUPDATE, 0);
			
			xNodeSet = xResult->nodesetval;
			xmlXPathFreeContext(xContext);

			actionBus.setActionProgressMaximum(ACTIONID_DBUPDATE, xNodeSet->nodeNr);
			if (xNodeSet->nodeNr==0) printf("[%s] ... Nothing found", server_url.c_str());
			for (xi = 0; xi < xNodeSet->nodeNr; xi++) {
				printf("[%s] ... Importing received data: %d/%d\r",server_url.c_str(), xi+1, xNodeSet->nodeNr);
				actionBus.setActionProgress(ACTIONID_DBUPDATE, xi);
				mDebug("Processing " + IntToStr(xi) + " node");
				if (actionBus._abortActions) {
					actionBus._abortComplete = true;
					actionBus.setActionState(ACTIONID_DBUPDATE, ITEMSTATE_ABORTED);
					
					return MPKGERROR_ABORTED;
				}
				
				actionBus.setActionProgress(ACTIONID_DBUPDATE, xi);
				pkg->clear();
				mDebug("Calling xml2Package");
				if (xml2package(xNodeSet->nodeTab[xi], pkg)<0) {
					mError("Failed to parse");
					abort();
				}
				else mDebug("xml2package OK");
				// Adding location data
				pkg->get_locations()->at(0).set_server_url(&server_url);
				packages->add(pkg);
			}
			printf("\n");
			xmlCleanupMemory();
			xmlCleanupParser();
			/*
			
 				*repository_root=XMLNode::openFileHelper(xml_name.c_str(), "repository");
				pkg_count=repository_root->nChildNode("package");
				if (pkg_count==0)
				{
					mError("Repository has no packages\n");
					delete pkg;
					return 0;
				}
				
				actionBus.setActionProgress(ACTIONID_DBUPDATE, 0);
				for (int i=0; i<pkg_count; i++)
				{
					if (actionBus._abortActions)
					{
						actionBus._abortComplete=true;
						actionBus.setActionState(ACTIONID_DBUPDATE, ITEMSTATE_ABORTED);
						return MPKGERROR_ABORTED;
					}

					actionBus.setActionProgress(ACTIONID_DBUPDATE, i);
					pkg->clear();
					*tmp = repository_root->getChildNode("package", i);
					xml2package(tmp, pkg);
					// Adding location data
					pkg->get_locations()->at(0).set_server_url(&server_url);
					packages->add(pkg);
				}*/
				//delete tmp;
			break;
		case TYPE_SLACK:
			*pList = ReadFile(index_filename);
			*mList = ReadFile(md5sums_filename);

			ret = slackpackages2list(pList, mList, packages, server_url);
			if (pList!=NULL) delete pList;
			if (mList!=NULL) delete mList;
			break;

		case TYPE_DEBIAN:
			break;
		default:
			break;
	}
	delete pkg;
	return ret;
}
コード例 #18
0
ファイル: ofconfig-datastore.c プロジェクト: JimBrv/of-config
int
ofcds_editconfig(void *UNUSED(data), const nc_rpc * UNUSED(rpc),
                 NC_DATASTORE target, const char *config,
                 NC_EDIT_DEFOP_TYPE defop,
                 NC_EDIT_ERROPT_TYPE UNUSED(errop), struct nc_err **error)
{
    int ret = EXIT_FAILURE, running = 0;
    char *aux;
    int cfgds_new = 0;
    xmlDocPtr cfgds = NULL, cfg = NULL, cfg_clone = NULL;
    xmlNodePtr rootcfg;

    if (defop == NC_EDIT_DEFOP_NOTSET) {
        defop = NC_EDIT_DEFOP_MERGE;
    }

    cfg = xmlReadMemory(config, strlen(config), NULL, NULL, XML_READ_OPT);
    rootcfg = xmlDocGetRootElement(cfg);
    if (!cfg
        || (rootcfg
            && !xmlStrEqual(rootcfg->name, BAD_CAST "capable-switch"))) {
        nc_verb_error("Invalid <edit-config> configuration data.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "config");
        return EXIT_FAILURE;
    }

    switch (target) {
    case NC_DATASTORE_RUNNING:
        /* Make a copy of parsed config - we will find port/configuration in
         * it.  It is used after txn_commit(). */
        cfg_clone = xmlCopyDoc(cfg, 1);

        aux = ofc_get_config_data();
        if (!aux) {
            *error = nc_err_new(NC_ERR_OP_FAILED);
            goto error_cleanup;
        }
        cfgds = xmlReadMemory(aux, strlen(aux), NULL, NULL, XML_READ_OPT);
        free(aux);

        running = 1;
        break;
    case NC_DATASTORE_STARTUP:
        cfgds = gds_startup;
        break;
    case NC_DATASTORE_CANDIDATE:
        cfgds = gds_cand;
        break;
    default:
        nc_verb_error("Invalid <edit-config> target.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "target");
        goto error_cleanup;
    }
    store_rollback(xmlCopyDoc(cfgds, 1), target);

    /* check keys in config's lists */
    ret = check_keys(cfg, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }

    /* check operations */
    ret = check_edit_ops(NC_EDIT_OP_DELETE, defop, cfgds, cfg, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }
    ret = check_edit_ops(NC_EDIT_OP_CREATE, defop, cfgds, cfg, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }

    if (target == NC_DATASTORE_RUNNING) {
        txn_init();
    }

    ret = compact_edit_operations(cfg, defop);
    if (ret != EXIT_SUCCESS) {
        nc_verb_error("Compacting edit-config operations failed.");
        if (error != NULL) {
            *error = nc_err_new(NC_ERR_OP_FAILED);
        }
        goto error_cleanup;
    }

    /* perform operations */
    if (!cfgds) {
        cfgds_new = 1;
        cfgds = xmlNewDoc(BAD_CAST "1.0");
    }
    ret = edit_operations(cfgds, cfg, defop, running, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }

    /* with defaults capability */
    if (ncdflt_get_basic_mode() == NCWD_MODE_TRIM) {
        /* server work in trim basic mode and therefore all default values
         * must be removed from the datastore. */
        /* TODO */
    }

    if (target == NC_DATASTORE_RUNNING) {
        ret = txn_commit(error);

        if (ret == EXIT_SUCCESS) {
            /* modify port/configuration of ports that were created */
            ret = of_post_ports(xmlDocGetRootElement(cfg_clone), error);
        }
        /* config clone was used and it is not needed by now */
        xmlFreeDoc(cfg_clone);

        xmlFreeDoc(cfgds);
    } else if (cfgds_new){
        if (cfgds->children) {
            /* document changed, because we started with empty document */
            if (target == NC_DATASTORE_STARTUP) {
                gds_startup = cfgds;
                cfgds = NULL;
            } else if (target == NC_DATASTORE_CANDIDATE) {
                gds_cand = cfgds;
                cfgds = NULL;
            }
        }
        xmlFreeDoc(cfgds);
    }
    xmlFreeDoc(cfg);

    return ret;

error_cleanup:

    if (target == NC_DATASTORE_RUNNING) {
        txn_abort();
        xmlFreeDoc(cfg_clone);
        xmlFreeDoc(cfgds);
    }
    xmlFreeDoc(cfg);

    return ret;
}
コード例 #19
0
ファイル: monitor_db.c プロジェクト: Whisprin/ddccontrol
/* usedatadir : data directory to use (if NULL, uses DATADIR preprocessor symbol) */
int ddcci_init_db(char* usedatadir) {
	xmlChar *version;
	xmlChar *date;
	char buffer[256];
	xmlNodePtr cur;
	char* endptr;
	int iversion;
	
	if (usedatadir) {
		datadir = malloc(strlen(usedatadir)+1);
		strcpy(datadir, usedatadir);
	}
	else {
		datadir = malloc(strlen(DATADIR)+1);
		strcpy(datadir, DATADIR);
	}
	
	snprintf(buffer, 256, "%s/options.xml", datadir);
	options_doc = xmlParseFile(buffer);
	if (options_doc == NULL) {
		fprintf(stderr,  _("Document not parsed successfully.\n"));
		return 0;
	}

	// Version check
	cur = xmlDocGetRootElement(options_doc);
	if (cur == NULL) {
		fprintf(stderr,  _("empty options.xml\n"));
		xmlFreeDoc(options_doc);
		free(datadir);
		return 0;
	}
	
	if (xmlStrcmp(cur->name, (const xmlChar *) "options")) {
		fprintf(stderr,  _("options.xml of the wrong type, root node %s != options"), cur->name);
		xmlFreeDoc(options_doc);
		free(datadir);
		return 0;
	}
	
	version = xmlGetProp(cur, BAD_CAST "dbversion");
	date = xmlGetProp(cur, BAD_CAST "date");
	
	if (!version) {
		fprintf(stderr,  _("options.xml dbversion attribute missing, please update your database.\n"));
		xmlFreeDoc(options_doc);
		free(datadir);
		return 0;
	}
	
	if (!date) {
		fprintf(stderr,  _("options.xml date attribute missing, please update your database.\n"));
		xmlFreeDoc(options_doc);
		free(datadir);
		return 0;
	}
	
	iversion = strtol((char*)version, &endptr, 0);
	DDCCI_DB_RETURN_IF(*endptr != 0, 0, _("Can't convert version to int."), cur);
	
	if (iversion > DBVERSION) {
		fprintf(stderr,  _("options.xml dbversion (%d) is greater than the supported version (%d).\n"), iversion, DBVERSION);
		fprintf(stderr,  _("Please update ddccontrol program.\n"));
		xmlFreeDoc(options_doc);
		free(datadir);
		return 0;
	}
	
	if (iversion < DBVERSION) {
		fprintf(stderr,  _("options.xml dbversion (%d) is less than the supported version (%d).\n"), iversion, DBVERSION);
		fprintf(stderr,  _("Please update ddccontrol database.\n"));
		xmlFreeDoc(options_doc);
		free(datadir);
		return 0;
	}
	
	/* TODO: do something with the date */

	xmlFree(version);
	xmlFree(date);
	
	return 1;
}
コード例 #20
0
ファイル: ofconfig-datastore.c プロジェクト: JimBrv/of-config
int
ofcds_copyconfig(void *UNUSED(data), NC_DATASTORE target,
                 NC_DATASTORE source, char *config, struct nc_err **error)
{
    int ret = EXIT_FAILURE;
    char *s;
    xmlDocPtr src_doc = NULL;
    xmlDocPtr dst_doc = NULL;
    xmlNodePtr root;
    static const char *ds[] = {"error", "<config>", "URL", "running",
                               "startup", "candidate"};

    nc_verb_verbose("OFC COPY-CONFIG (from %s to %s)", ds[source], ds[target]);

    switch (source) {
    case NC_DATASTORE_RUNNING:
        s = ofcds_getconfig(NULL, NC_DATASTORE_RUNNING, error);
        if (!s) {
            nc_verb_error
                ("copy-config: unable to get running source repository");
            return EXIT_FAILURE;
        }
        src_doc = xmlReadMemory(s, strlen(s), NULL, NULL, XML_READ_OPT);
        free(s);
        if (!src_doc) {
            nc_verb_error("copy-config: invalid running source data");
            *error = nc_err_new(NC_ERR_OP_FAILED);
            nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM,
                       "invalid running source data");
            return EXIT_FAILURE;
        }
        break;
    case NC_DATASTORE_STARTUP:
        src_doc = xmlCopyDoc(gds_startup, 1);
        break;
    case NC_DATASTORE_CANDIDATE:
        src_doc = xmlCopyDoc(gds_cand, 1);
        break;
    case NC_DATASTORE_CONFIG:
        if (config && strlen(config) > 0) {
            src_doc = xmlReadMemory(config, strlen(config), NULL, NULL,
                                    XML_READ_OPT);
        }
        if (!config || (strlen(config) > 0 && !src_doc)) {
            nc_verb_error("Invalid source configuration data.");
            *error = nc_err_new(NC_ERR_BAD_ELEM);
            nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "config");
            return EXIT_FAILURE;
        }

        break;
    default:
        nc_verb_error("Invalid <get-config> source.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "source");
        return EXIT_FAILURE;
    }

    switch (target) {
    case NC_DATASTORE_RUNNING:
        /* apply source to OVSDB */

        s = ofcds_getconfig(NULL, NC_DATASTORE_RUNNING, error);
        if (!s) {
            nc_verb_error("copy-config: unable to get running source data");
            goto cleanup;
        }
        dst_doc = xmlReadMemory(s, strlen(s), NULL, NULL, XML_READ_OPT);
        free(s);

        root = xmlDocGetRootElement(src_doc);
        if (!dst_doc) {
            /* create envelope */
            dst_doc = xmlNewDoc(BAD_CAST "1.0");
        }
        if (!rollbacking) {
            store_rollback(xmlCopyDoc(dst_doc, 1), target);
        }

        txn_init();
        if (edit_replace(dst_doc, root, 1, error)) {
            txn_abort();
        } else {
            ret = txn_commit(error);
        }
        xmlFreeDoc(dst_doc);
        goto cleanup;
        break;
    case NC_DATASTORE_STARTUP:
    case NC_DATASTORE_CANDIDATE:
        /* create copy */
        if (src_doc) {
            dst_doc = src_doc;
            src_doc = NULL;
        }

        /* store the copy */
        if (target == NC_DATASTORE_STARTUP) {
            if (!rollbacking) {
                store_rollback(gds_startup, target);
            } else {
                xmlFreeDoc(gds_startup);
            }
            gds_startup = dst_doc;
        } else {                /* NC_DATASTORE_CANDIDATE */
            if (!rollbacking) {
                store_rollback(gds_cand, target);
            } else {
                xmlFreeDoc(gds_cand);
            }
            gds_cand = dst_doc;
        }

        break;
    default:
        nc_verb_error("Invalid <get-config> source.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "source");
        goto cleanup;
    }

    ret = EXIT_SUCCESS;

cleanup:
    xmlFreeDoc(src_doc);

    return ret;
}
コード例 #21
0
void GamesXmlParser::parse(const std::string& fname) {

    xmlDocPtr m_doc = xmlParseFile(fname.c_str());
    if (m_doc == NULL) {
        ERRORMSG("File " << fname << " is invalid")
        xmlFreeDoc(m_doc);
        return;
    }
    xmlNodePtr cur = xmlDocGetRootElement(m_doc);
    if(!xmlStrEqual(cur->name,(const xmlChar*)"GAMESS")) {
        ERRORMSG("File " << fname << " does not have GAMESS as its root. Invalid")
        xmlFreeDoc(m_doc);
        return;
    }

    //xmlNodePtr for atoms
    vector<xmlNodePtr> aPtrList;
    //xmlNodePtr for eigvectors
    vector<xmlNodePtr> ePtrList;
    //xmlNodePtr for gaussian basis
    vector<xmlNodePtr> bPtrList;

    cur=cur->children;
    while(cur != NULL) {
        string cname((const char*)cur->name);
        if(cname == "IN") {
            xmlNodePtr cur1=cur->children;
            while(cur1 != NULL) {
                string cname1((const char*)cur1->name);
                if(cname1 == "RUN_TITLE") {
                    string atitle;
                    putContent(atitle,cur1);
                    string::size_type wh=atitle.find("...");
                    if(wh<atitle.size()) atitle.erase(wh,atitle.size()-wh);
                    Title = atitle;
                } else if(cname1 == "CONTRL") {
                    getControlParameters(cur1);
                }
                cur1=cur1->next;
            }//everything within IN
        } else if(cname == "OUT") {
            xmlNodePtr cur1=cur->children;
            while(cur1 != NULL) {
                string cname1((const char*)cur1->name);
                if(cname1 == "SYSTEM_STATE") {
                    //Unit needs to be generalized!!
                    string unitL((const char*)xmlGetProp(cur1,(const xmlChar*)"UNITS"));
                    if(unitL == "ANGS") BohrUnit=false;

                    xmlNodePtr cur2 = cur1->children;
                    while(cur2 != NULL) {
                        string cname2((const char*)cur2->name);
                        if(cname2 == "ATOM") {
                            aPtrList.push_back(cur2);
                        } else if(cname2 == "VEC") {
                            ePtrList.push_back(cur2);
                        }
                        cur2=cur2->next;
                    }
                } else if(cname1 == "PDATA") {
                    xmlNodePtr cur2 = cur1->children;
                    while(cur2 != NULL) {
                        string cname2((const char*)cur2->name);
                        if(cname2 == "PATOMIC_BASIS_SET") {
                            bPtrList.push_back(cur2);
                        }
                        cur2=cur2->next;
                    }
                }
                cur1=cur1->next;
            }//everything within OUT
        }
        cur=cur->next;
    }

    //xmlXPathContextPtr m_context = xmlXPathNewContext(m_doc);

    getGeometry(aPtrList);
    getGaussianCenters(bPtrList);
    getEigVectors(ePtrList);

    //xmlXPathFreeContext(m_context);
    xmlFreeDoc(m_doc);
}
コード例 #22
0
RheiaPluginManifest* RheiaPluginManager::ReadManifestFile(
        const wxString& pluginFilename )
{
    RheiaLoggerManager::sdLog( wxT("RheiaPluginManager::Reading plugin manifest file : ") + pluginFilename + wxT(" ...") , RheiaLogging::info );

    wxString pluginFname = pluginFilename;

    // first check if the plugin can be found
    if (pluginFname.IsEmpty())
    {
        RheiaLoggerManager::sdLog( wxT("RheiaPluginManager::Plugin manifest file : ") + pluginFilename + wxT(" is empty...") , RheiaLogging::error );
        return NULL;
    }

    wxFileName fname(pluginFilename);
    fname.SetExt(wxT("zip"));
    wxString actual = fname.GetFullName();

    // remove dynamic library prefix from plugin name (if any)
    if ( !FileExt::DYNAMIC_LIBRARY_PREFIX.IsEmpty() && !platform::windows && actual.StartsWith(FileExt::DYNAMIC_LIBRARY_PREFIX))
        actual.Remove(0, FileExt::DYNAMIC_LIBRARY_PREFIX.Length());

    actual = RheiaFileFinder::FindFile( actual, rspfPluginsUser | rspfDataUser | rspfPluginsGlobal | rspfDataGlobal );

    // check if the plugin resource exists
    if (actual.IsEmpty())
    {
        RheiaLoggerManager::sdLog( wxT("RheiaPluginManager::Plugin manifest file : ") + pluginFilename + wxT(" not found...") , RheiaLogging::error );
        return false;
    }

    // load XML from ZIP
    wxString contents;
    wxFileSystem* fs = new wxFileSystem;
    wxFSFile* f = fs->OpenFile(actual + _T("#zip:manifest.xml") );

    if (f)
    {
        wxInputStream* is = f->GetStream();
        char tmp[1024] = {};
        while (!is->Eof() && is->CanRead())
        {
            memset(tmp, 0, sizeof(tmp));
            is->Read(tmp, sizeof(tmp) - 1);
            contents <<  RheiaC2U(tmp);
        }
        delete f;
    }
    else
    {
        RheiaLoggerManager::sdLog( wxT("RheiaPluginManager::Cannot extract plugin manifest file : ") + actual + wxT("#zip:manifest.xml...") , RheiaLogging::error );
        delete fs;
        return false;
    }
    delete fs;

    xmlDoc* doc = xmlParseMemory( rcU2C(contents) , contents.size() );

    if (!doc)
    {
        RheiaLoggerManager::sdLog( wxT("RheiaPluginManager::Cannot load xml document from memory : ") + actual + wxT("#zip:manifest.xml...") , RheiaLogging::error );
        return NULL;
    }

    xmlNode* root = xmlDocGetRootElement( doc );
    wxString rname = RheiaC2U( (const char*) root->name );

    if( !rname.IsSameAs( wxT("RheiaPluginManifest") ) )
    {
        RheiaLoggerManager::sdLog( wxT("RheiaPluginManager::Root node for xml document : ") + actual + wxT("#zip:manifest.xml is not RheiaPluginManifest...") + rname , RheiaLogging::error );
        xmlFreeDoc( doc );
        return NULL;
    }

    RheiaPluginManifest* manifest = new RheiaPluginManifest;

    xmlNode* child = root->children;

    while( child != NULL )
    {
        wxString cname = RheiaC2U( (const char*) child->name );

        if( cname.IsSameAs(wxT("Plugin")) )
        {
            if( !manifest->DoReadFromNode(child) )
            {
                RheiaLoggerManager::sdLog( wxT("RheiaPluginManager::Problem reading the xml document content from memory (manifest->DoReadFromNode(root) returns false) : ") + actual + wxT("#zip:manifest.xml is not RheiaPluginManifest...") , RheiaLogging::error );
                delete manifest;
                xmlFreeDoc( doc );
                return NULL;
            }
            break;
        }

        child = child->next;
    }

    xmlFreeDoc( doc );
    return manifest;
}
コード例 #23
0
ファイル: plugin.c プロジェクト: emillon/gmpc-plugins
static void wp_query_callback(const GEADAsyncHandler *handle, GEADStatus status, gpointer ignored)
{
	xmlDocPtr doc;
	goffset size;
	xmlNodePtr root, sect, desc, url, c1, query;
	const gchar *data;
	gchar *targeturl, *txt;



    g_log(wikipedia_logdomain, G_LOG_LEVEL_DEBUG, "query returned %i\n",status);
	if(status != GEAD_DONE)
		return;
    g_log(wikipedia_logdomain, G_LOG_LEVEL_DEBUG, "query returned done\n");
    data = gmpc_easy_handler_get_data(handle, &size);

	doc = xmlParseMemory(data, size);
	if(!doc)
		return;
	root = xmlDocGetRootElement(doc);
	if(!root)
		return;
	sect = get_first_node_by_name(root,"Section");
	if (!sect)
		goto out_doc;

	for(c1 = sect->xmlChildrenNode; c1; c1 = c1->next)
	{
		desc = get_first_node_by_name(c1, "Text");
		url = get_first_node_by_name(c1, "Url");
		if (!desc || !url)
			continue;
		txt = xmlNodeListGetString(doc, desc->xmlChildrenNode, 1);
		if (!txt)
			continue;
		if (g_regex_match_full(page_guess_re, txt, strlen(txt), 0, 0, NULL, NULL) &&
				xmlNodeListGetString(doc, url->xmlChildrenNode, 1))
		{
			wp_set_url(xmlNodeListGetString(doc, url->xmlChildrenNode, 1));
			break;
		}

	}
	/* nothing was found by regex, use first entry */
	if (!c1) {
		c1 = sect->xmlChildrenNode;
		if (c1) {
			url = get_first_node_by_name(c1, "Url");
			if (url && xmlNodeListGetString(doc, url->xmlChildrenNode, 1))
				wp_set_url(xmlNodeListGetString(doc,url->xmlChildrenNode,1));
		} else {
			/* nothing is found, if we are localized, grab our search string back and do some magic */
			query = get_first_node_by_name(root, "Query");
			if (!query)
				goto out_doc;
			txt = xmlNodeListGetString(doc, query->xmlChildrenNode, 1);
			if (!txt)
				goto out_doc;

			/* fist try english wikipedia, it's the biggest after all */
			const gchar *oldurl = gmpc_easy_handler_get_uri(handle);
			if (!g_str_has_prefix(oldurl, "http://en.")) {
				gchar *newurl = g_strdup_printf("http://en.wikipedia.org/w/api.php?action=opensearch&search=%s&format=xml", txt);
				g_log(wikipedia_logdomain, G_LOG_LEVEL_DEBUG, "Trying to fetch: %s\n", newurl);
				gmpc_easy_async_downloader(newurl, wp_query_callback, NULL);
				g_free(newurl);
				goto out_doc;
			}
			/* nothing is found, display localized wikipedia
			 * "unknown article" page. Not loading anything is
			 * confusing */
			targeturl = g_strdup_printf("http://%s.wikipedia.org/wiki/%s", locale, txt);
			wp_set_url(targeturl);
			g_free(targeturl);
		}
	}
out_doc:
	xmlFreeDoc(doc);
}
コード例 #24
0
static int SetFriendlyName(char *file, char *newname, int status) {

	if(!newname)
		return ZERROR;

	if(!(strlen(newname)>0))
		return ZERROR;

	xmlDocPtr doc;
	xmlNodePtr cur;
	char *tempXmlStr;

	doc = xmlParseFile(file);
	
	if (doc == NULL )
	{
		fprintf(stderr, "Document not parsed successfully.");
		return -1;
	}
	
	cur = xmlDocGetRootElement(doc);
	
	if (cur == NULL)
	{
		fprintf(stderr, "empty document");
		xmlFreeDoc(doc);
		return -1;
	}
	
	if (xmlStrcmp(cur->name, (const xmlChar *) "root"))
	{
		fprintf(stderr, "document of the wrong type, root node name!=root");
		xmlFreeDoc(doc);
		return -1;
	}
	cur = cur->xmlChildrenNode;
	while(cur != NULL)
	{
		if (!xmlStrcmp(cur->name, (const xmlChar *)"device"))
		{
			//find the device element
			cur = cur->xmlChildrenNode;
			while (cur != NULL)
			{
				if ((!xmlStrcmp(cur->name, (const xmlChar *)"friendlyName")))
				{
					//find friendlyName
					//then we will change it value to new
					if(status) //setDMS
					{
						// fix XML issue: MUST escape value before xmlNodeSetContent
						tempXmlStr = EscapXMLChar(newname);
						xmlNodeSetContent(cur, BAD_CAST tempXmlStr);
						free(tempXmlStr);
						xmlSaveFile(file, doc);
						xmlFreeDoc(doc);
					}
					else  //getDMS
					{
						strcpy(newname,(char *)xmlNodeGetContent(cur));
						xmlFreeDoc(doc);
					}
					return 0;
				}
		 
				cur = cur->next;
			}
			xmlFreeDoc(doc);
			return -1;
		}
		cur = cur->next;
	}
	fprintf(stderr, "Not find the element<device>");
    
	xmlFreeDoc(doc);

	return ZERROR;
}
コード例 #25
0
static int
hwloc_libxml_import_diff(const char *xmlpath, const char *xmlbuffer, int xmlbuflen, hwloc_topology_diff_t *firstdiffp, char **refnamep)
{
  struct hwloc__xml_import_state_s state;
  hwloc__libxml_import_state_data_t lstate = (void*) state.data;
  char *refname = NULL;
  xmlDoc *doc = NULL;
  xmlNode* root_node;
  xmlDtd *dtd;
  int ret;

  assert(sizeof(*lstate) <= sizeof(state.data));

  LIBXML_TEST_VERSION;
  hwloc_libxml2_disable_stderrwarnings();

  errno = 0; /* set to 0 so that we know if libxml2 changed it */

  if (xmlpath)
    doc = xmlReadFile(xmlpath, NULL, 0);
  else if (xmlbuffer)
    doc = xmlReadMemory(xmlbuffer, xmlbuflen, "", NULL, 0);

  if (!doc) {
    if (!errno)
      /* libxml2 read the file fine, but it got an error during parsing */
    errno = EINVAL;
    goto out;
  }

  dtd = xmlGetIntSubset(doc);
  if (!dtd) {
    if (hwloc__xml_verbose())
      fprintf(stderr, "Loading XML topologydiff without DTD\n");
  } else if (strcmp((char *) dtd->SystemID, "hwloc.dtd")) {
    if (hwloc__xml_verbose())
      fprintf(stderr, "Loading XML topologydiff with wrong DTD SystemID (%s instead of %s)\n",
	      (char *) dtd->SystemID, "hwloc.dtd");
  }

  root_node = xmlDocGetRootElement(doc);

  if (strcmp((const char *) root_node->name, "topologydiff")) {
    /* root node should be in "topologydiff" class */
    if (hwloc__xml_verbose())
      fprintf(stderr, "ignoring object of class `%s' not at the top the xml hierarchy\n", (const char *) root_node->name);
    goto out_with_doc;
  }

  state.next_attr = hwloc__libxml_import_next_attr;
  state.find_child = hwloc__libxml_import_find_child;
  state.close_tag = hwloc__libxml_import_close_tag;
  state.close_child = hwloc__libxml_import_close_child;
  state.get_content = hwloc__libxml_import_get_content;
  state.close_content = hwloc__libxml_import_close_content;
  state.parent = NULL;
  lstate->node = root_node;
  lstate->child = root_node->children;
  lstate->attr = NULL;

  while (1) {
    char *attrname, *attrvalue;
    if (state.next_attr(&state, &attrname, &attrvalue) < 0)
      break;
    if (!strcmp(attrname, "refname")) {
      free(refname);
      refname = strdup(attrvalue);
    } else
      goto out_with_doc;
  }

  ret = hwloc__xml_import_diff(&state, firstdiffp);
  if (refnamep && !ret)
    *refnamep = refname;
  else
    free(refname);

  xmlFreeDoc(doc);
  return ret;

out_with_doc:
  xmlFreeDoc(doc);
out:
  return -1; /* failed */
}
コード例 #26
0
ファイル: analyze.c プロジェクト: maksverver/Pillars
int main(int argc, char *argv[])
{
    char *descr;
    Board board;
    xmlDocPtr doc;
    xmlNodePtr gameNode, boardNode, analysisNode, node;

    if (argc != 2)
    {
        printf("usage: analyze <game.xml>\n");
        exit(1);
    }

    LIBXML_TEST_VERSION

    /* Parse input file */
    xmlInitParser();
    doc = xmlReadFile(argv[1], NULL, 0);
    if (doc == NULL)
    {
        fprintf(stderr, "Could not read/parse input file.\n");
        exit(1);
    }
    xmlCleanupParser();

    /* Process input data */
    gameNode = xmlDocGetRootElement(doc);
    if (strcmp((char*)gameNode->name, "game") != 0)
    {
        fprintf(stderr, "Root element should be <game>\n");
        exit(1);
    }
    boardNode = NULL;
    for (node = gameNode->children; node != NULL; node = node->next)
    {
        if (node->type == XML_ELEMENT_NODE)
        {
            if (strcmp((char*)node->name, "board") == 0)
            {
                if (boardNode != NULL)
                {
                    fprintf(stderr, "Multiple Mboard> elements found.\n");
                    exit(1);
                }
                boardNode = node;
            }
            if (strcmp((char*)node->name, "analysis") == 0)
            {
                xmlUnlinkNode(node);
                xmlFreeNode(node);
            }
        }
    }
    if (boardNode == NULL)
    {
        fprintf(stderr, "No <board> element found.\n");
        exit(1);
    }
    if ( boardNode->children == NULL ||
         boardNode->children != boardNode->last ||
         boardNode->children->type != XML_TEXT_NODE )
    {
        fprintf(stderr, "<board> should contain only text.\n");
        exit(1);
    }
    descr = (char*)xmlNodeGetContent(boardNode->children);

    /* Decode board */
    if (!board_decode_full(&board, descr))
    {
        fprintf(stderr, "Cannot decode full board description: %s\n", descr);
        exit(1);
    }

    /* Add analysis to data */
    analysisNode = analyze_board(&board);
    xmlAddChild(gameNode, analysisNode);

    /* Write output document */
    xmlDocDump(stdout, doc);
    xmlFreeDoc(doc);

    return 0;
}
コード例 #27
0
/*******************************************************************************
**
** Function:        import
**
** Description:     Import data from an XML file.  Fill the databases.
**
** Returns:         True if ok.
**
*******************************************************************************/
bool RouteDataSet::import ()
{
    static const char fn [] = "RouteDataSet::import";
    ALOGD ("%s: enter", fn);
    bool retval = false;
#if 0
    xmlDocPtr doc;
    xmlNodePtr node1;
    std::string strFilename(bcm_nfc_location);
    strFilename += sConfigFile;

    deleteDatabase ();

    doc = xmlParseFile (strFilename.c_str());
    if (doc == NULL)
    {
        ALOGD ("%s: fail parse", fn);
        goto TheEnd;
    }

    node1 = xmlDocGetRootElement (doc);
    if (node1 == NULL)
    {
        ALOGE ("%s: fail root element", fn);
        goto TheEnd;
    }
    ALOGD ("%s: root=%s", fn, node1->name);

    node1 = node1->xmlChildrenNode;
    while (node1) //loop through all elements in <Routes ...
    {
        if (xmlStrcmp(node1->name, (const xmlChar*) "Route")==0)
        {
            xmlChar* value = xmlGetProp (node1, (const xmlChar*) "Type");
            if (value && (xmlStrcmp (value, (const xmlChar*) "SecElemSelectedRoutes") == 0))
            {
                ALOGD ("%s: found SecElemSelectedRoutes", fn);
                xmlNodePtr node2 = node1->xmlChildrenNode;
                while (node2) //loop all elements in <Route Type="SecElemSelectedRoutes" ...
                {
                    if (xmlStrcmp(node2->name, (const xmlChar*) "Proto")==0)
                        importProtocolRoute (node2, mSecElemRouteDatabase);
                    else if (xmlStrcmp(node2->name, (const xmlChar*) "Tech")==0)
                        importTechnologyRoute (node2, mSecElemRouteDatabase);
                    node2 = node2->next;
                } //loop all elements in <Route Type="SecElemSelectedRoutes" ...
            }
            else if (value && (xmlStrcmp (value, (const xmlChar*) "DefaultRoutes") == 0))
            {
                ALOGD ("%s: found DefaultRoutes", fn);
                xmlNodePtr node2 = node1->xmlChildrenNode;
                while (node2) //loop all elements in <Route Type="DefaultRoutes" ...
                {
                    if (xmlStrcmp(node2->name, (const xmlChar*) "Proto")==0)
                        importProtocolRoute (node2, mDefaultRouteDatabase);
                    else if (xmlStrcmp(node2->name, (const xmlChar*) "Tech")==0)
                        importTechnologyRoute (node2, mDefaultRouteDatabase);
                    node2 = node2->next;
                } //loop all elements in <Route Type="DefaultRoutes" ...
            }
            if (value)
                xmlFree (value);
        } //check <Route ...
        node1 = node1->next;
    } //loop through all elements in <Routes ...
    retval = true;

TheEnd:
    xmlFreeDoc (doc);
    xmlCleanupParser ();
    ALOGD ("%s: exit; return=%u", fn, retval);
#endif
    return retval;
}
コード例 #28
0
ファイル: sign3.c プロジェクト: esproul/xmlsec
/** 
 * sign_file:
 * @xml_file:           the XML file name.
 * @key_file:           the PEM private key file name.
 * @cert_file:          the x509 certificate PEM file.
 *
 * Signs the @xml_file using private key from @key_file and dynamicaly
 * created enveloped signature template. The certificate from @cert_file
 * is placed in the <dsig:X509Data/> node.
 *
 * Returns 0 on success or a negative value if an error occurs.
 */
int 
sign_file(const char* xml_file, const char* key_file, const char* cert_file) {
    xmlDocPtr doc = NULL;
    xmlNodePtr signNode = NULL;
    xmlNodePtr refNode = NULL;
    xmlNodePtr keyInfoNode = NULL;
    xmlNodePtr x509DataNode = NULL;
    xmlSecDSigCtxPtr dsigCtx = NULL;
    int res = -1;
    
    assert(xml_file);
    assert(key_file);
    assert(cert_file);

    /* load doc file */
    doc = xmlParseFile(xml_file);
    if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
        fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
        goto done;      
    }
    
    /* create signature template for RSA-SHA1 enveloped signature */
    signNode = xmlSecTmplSignatureCreate(doc, xmlSecTransformExclC14NId,
                                         xmlSecTransformRsaSha1Id, NULL);
    if(signNode == NULL) {
        fprintf(stderr, "Error: failed to create signature template\n");
        goto done;              
    }

    /* add <dsig:Signature/> node to the doc */
    xmlAddChild(xmlDocGetRootElement(doc), signNode);
    
    /* add reference */
    refNode = xmlSecTmplSignatureAddReference(signNode, xmlSecTransformSha1Id,
                                        NULL, NULL, NULL);
    if(refNode == NULL) {
        fprintf(stderr, "Error: failed to add reference to signature template\n");
        goto done;              
    }

    /* add enveloped transform */
    if(xmlSecTmplReferenceAddTransform(refNode, xmlSecTransformEnvelopedId) == NULL) {
        fprintf(stderr, "Error: failed to add enveloped transform to reference\n");
        goto done;              
    }
    
    /* add <dsig:KeyInfo/> and <dsig:X509Data/> */
    keyInfoNode = xmlSecTmplSignatureEnsureKeyInfo(signNode, NULL);
    if(keyInfoNode == NULL) {
        fprintf(stderr, "Error: failed to add key info\n");
        goto done;              
    }
    
    x509DataNode = xmlSecTmplKeyInfoAddX509Data(keyInfoNode);
    if(x509DataNode == NULL) {
        fprintf(stderr, "Error: failed to add X509Data node\n");
        goto done;              
    }

    if(xmlSecTmplX509DataAddSubjectName(x509DataNode) == NULL) {
        fprintf(stderr, "Error: failed to add X509SubjectName node\n");
        goto done;
    }

    if(xmlSecTmplX509DataAddCertificate(x509DataNode) == NULL) {
        fprintf(stderr, "Error: failed to add X509Certificate node\n");
        goto done;
    }

    /* create signature context, we don't need keys manager in this example */
    dsigCtx = xmlSecDSigCtxCreate(NULL);
    if(dsigCtx == NULL) {
        fprintf(stderr,"Error: failed to create signature context\n");
        goto done;
    }

    /* load private key, assuming that there is not password */
    dsigCtx->signKey = xmlSecCryptoAppKeyLoad(key_file, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
    if(dsigCtx->signKey == NULL) {
        fprintf(stderr,"Error: failed to load private pem key from \"%s\"\n", key_file);
        goto done;
    }
    
    /* load certificate and add to the key */
    if(xmlSecCryptoAppKeyCertLoad(dsigCtx->signKey, cert_file, xmlSecKeyDataFormatPem) < 0) {
        fprintf(stderr,"Error: failed to load pem certificate \"%s\"\n", cert_file);
        goto done;
    }

    /* set key name to the file name, this is just an example! */
    if(xmlSecKeySetName(dsigCtx->signKey, key_file) < 0) {
        fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n", key_file);
        goto done;
    }

    /* sign the template */
    if(xmlSecDSigCtxSign(dsigCtx, signNode) < 0) {
        fprintf(stderr,"Error: signature failed\n");
        goto done;
    }
        
    /* print signed document to stdout */
    xmlDocDump(stdout, doc);
    
    /* success */
    res = 0;

done:    
    /* cleanup */
    if(dsigCtx != NULL) {
        xmlSecDSigCtxDestroy(dsigCtx);
    }
    
    if(doc != NULL) {
        xmlFreeDoc(doc); 
    }
    return(res);
}
コード例 #29
0
ファイル: derivationmapping.c プロジェクト: vizanto/disnix
GArray *create_derivation_array(const gchar *distributed_derivation_file)
{
    /* Declarations */
    xmlDocPtr doc;
    xmlNodePtr node_root;
    xmlXPathObjectPtr result;
    GArray *derivation_array = NULL;
    
    /* Parse the XML document */
    
    if((doc = xmlParseFile(distributed_derivation_file)) == NULL)
    {
	g_printerr("Error with parsing the distributed derivation XML file!\n");
	xmlCleanupParser();
	return NULL;
    }
    
    /* Retrieve root element */
    node_root = xmlDocGetRootElement(doc);
    
    if(node_root == NULL)
    {
        g_printerr("The distributed derivation XML file is empty!\n");
	xmlFreeDoc(doc);
	xmlCleanupParser();
	return NULL;
    }

    /* Query the mapping elements */
    result = executeXPathQuery(doc, "/distributedderivation/mapping");
    
    /* Iterate over all the mapping elements and add them to the array */
    
    if(result)
    {
	xmlNodeSetPtr nodeset = result->nodesetval;
	unsigned int i;
	
	/* Create a derivation array */
        derivation_array = g_array_new(FALSE, FALSE, sizeof(DerivationItem*));
	
	/* Iterate over all the mapping elements */
	for(i = 0; i < nodeset->nodeNr; i++)
        {
	    xmlNodePtr mapping_children = nodeset->nodeTab[i]->children;
	    DerivationItem *item = (DerivationItem*)g_malloc(sizeof(DerivationItem));
	    gchar *derivation = NULL, *target = NULL;
	    
	    /* Iterate over all the mapping item children (derivation and target elements) */
	    
	    while(mapping_children != NULL)
	    {
		if(xmlStrcmp(mapping_children->name, (xmlChar*) "derivation") == 0)
		    derivation = g_strdup(mapping_children->children->content);
		else if(xmlStrcmp(mapping_children->name, (xmlChar*) "target") == 0)
		    target = g_strdup(mapping_children->children->content);
		
		mapping_children = mapping_children->next;
	    }
	    
	    /* Added the mapping to the array */
	    item->derivation = derivation;
	    item->target = target;
	    g_array_append_val(derivation_array, item);
        }
    }
    
    /* Cleanup */    
    xmlXPathFreeObject(result);
    xmlFreeDoc(doc);
    xmlCleanupParser();

    /* Return the derivation array */
    return derivation_array;
}
コード例 #30
0
ファイル: rf_xml.c プロジェクト: selecli/squid
int rf_xml_parse(rf_cli_session *sess,const char *buffer,int size){
	int ret = RF_OK;
	if(NULL == (doc = xmlParseMemory(buffer,size))){
		cclog(3,"Document not parsed successfully.[%s]", buffer);
		return RF_ERR_XML_PARSE;
	}

	if(NULL == (cur = xmlDocGetRootElement(doc))){
		cclog(1,"empty document.");
		ret = RF_ERR_XML_PARSE;
		goto OUT;
	}

	if (xmlStrcmp(cur->name, (const xmlChar *) "method")) {
		cclog(1,"document of the wrong type, root node != method.");
		ret = RF_ERR_XML_PARSE;
		goto OUT;
	}

	xmlChar *method_name , *sessid;
	if(NULL == (method_name = xmlGetProp(cur,(const xmlChar *)"name"))){
		cclog(1,"get method name error!");
		ret = RF_ERR_XML_PARSE;
		goto OUT;
	}

	if(NULL == (sessid = xmlGetProp(cur,(const xmlChar *)"sessionid"))){
		cclog(1,"get sessionid error!");
		xmlFree(method_name);
		ret = RF_ERR_XML_PARSE;
		goto OUT;
	}

	cclog(4,"method name : %s,session id : %s",method_name,sessid);

	sess->method = action_atoi((char *)method_name);
	strcpy(sess->sessionid,(char *)sessid);

	xmlFree(method_name);
	xmlFree(sessid);

	cur = cur->xmlChildrenNode;
	switch (sess->method){
		case RF_FC_ACTION_URL_PURGE :
		case RF_FC_ACTION_URL_EXPIRE:
			ret = rf_parse_url(cur,sess);
			break;
		case RF_FC_ACTION_DIR_PURGE:
			if(!config.enable_dir_purge)
			{
				cclog(1,"Do not support dir purge!");
				ret = RF_ERR_XML_PARSE;
				break;
			}
		case RF_FC_ACTION_DIR_EXPIRE:
			ret = rf_parse_dir(cur,sess);
			break;
		default:
			cclog(1,"can not process method : %s",action_itoa(sess->method));
			break;
	};

OUT:
	xmlFreeDoc(doc);
	doc = NULL;
	return ret;
}