Exemplo n.º 1
0
static void xsl_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
{
	xsltTransformContextPtr tctxt;
	zval *args;
	zval retval;
	int result, i;
	int error = 0;
	zend_fcall_info fci;
	zval handler;
	xmlXPathObjectPtr obj;
	char *str;
	xsl_object *intern;
	zend_string *callable = NULL;


	if (! zend_is_executing()) {
		xsltGenericError(xsltGenericErrorContext,
		"xsltExtFunctionTest: Function called from outside of PHP\n");
		error = 1;
	} else {
		tctxt = xsltXPathGetTransformContext(ctxt);
		if (tctxt == NULL) {
			xsltGenericError(xsltGenericErrorContext,
			"xsltExtFunctionTest: failed to get the transformation context\n");
			error = 1;
		} else {
			intern = (xsl_object*)tctxt->_private;
			if (intern == NULL) {
				xsltGenericError(xsltGenericErrorContext,
				"xsltExtFunctionTest: failed to get the internal object\n");
				error = 1;
			}
			else if (intern->registerPhpFunctions == 0) {
				xsltGenericError(xsltGenericErrorContext,
				"xsltExtFunctionTest: PHP Object did not register PHP functions\n");
				error = 1;
			}
		}
	}

	if (error == 1) {
		for (i = nargs - 1; i >= 0; i--) {
			obj = valuePop(ctxt);
			xmlXPathFreeObject(obj);
		}
		return;
	}

	fci.param_count = nargs - 1;
	if (fci.param_count > 0) {
		args = safe_emalloc(fci.param_count, sizeof(zval), 0);
	}
	/* Reverse order to pop values off ctxt stack */
	for (i = nargs - 2; i >= 0; i--) {
		obj = valuePop(ctxt);
		switch (obj->type) {
			case XPATH_STRING:
				ZVAL_STRING(&args[i], (char *)obj->stringval);
				break;
			case XPATH_BOOLEAN:
				ZVAL_BOOL(&args[i],  obj->boolval);
				break;
			case XPATH_NUMBER:
				ZVAL_DOUBLE(&args[i], obj->floatval);
				break;
			case XPATH_NODESET:
				if (type == 1) {
					str = (char*)xmlXPathCastToString(obj);
					ZVAL_STRING(&args[i], str);
					xmlFree(str);
				} else if (type == 2) {
					int j;
					dom_object *domintern = (dom_object *)intern->doc;
					array_init(&args[i]);
					if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
						for (j = 0; j < obj->nodesetval->nodeNr; j++) {
							xmlNodePtr node = obj->nodesetval->nodeTab[j];
							zval child;
							/* not sure, if we need this... it's copied from xpath.c */
							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((char *)node->children);
								}
								if (node->children) {
									node = xmlNewDocNode(node->doc, NULL, (char *) node->children, node->name);
								} else {
									node = xmlNewDocNode(node->doc, NULL, "xmlns", node->name);
								}
								node->type = XML_NAMESPACE_DECL;
								node->parent = nsparent;
								node->ns = curns;
							} else {
								node = xmlDocCopyNodeList(domintern->document->ptr, node);
							}

							php_dom_create_object(node, &child, domintern);
							add_next_index_zval(&args[i], &child);
						}
					}
				}
				break;
			default:
				str = xmlXPathCastToString(obj);
				ZVAL_STRING(&args[i], str);
				xmlFree(str);
		}
		xmlXPathFreeObject(obj);
	}

	fci.size = sizeof(fci);
	fci.function_table = EG(function_table);
	if (fci.param_count > 0) {
		fci.params = args;
	} else {
		fci.params = NULL;
	}


	obj = valuePop(ctxt);
	if (obj->stringval == NULL) {
		php_error_docref(NULL, E_WARNING, "Handler name must be a string");
		xmlXPathFreeObject(obj);
		valuePush(ctxt, xmlXPathNewString(""));
		if (fci.param_count > 0) {
			for (i = 0; i < nargs - 1; i++) {
				zval_ptr_dtor(&args[i]);
			}
			efree(args);
		}
		return;
	}
	ZVAL_STRING(&handler, obj->stringval);
	xmlXPathFreeObject(obj);

	ZVAL_COPY_VALUE(&fci.function_name, &handler);
	fci.symbol_table = NULL;
	fci.object = NULL;
	fci.retval = &retval;
	fci.no_separation = 0;
	/*fci.function_handler_cache = &function_ptr;*/
	if (!zend_make_callable(&handler, &callable)) {
		php_error_docref(NULL, E_WARNING, "Unable to call handler %s()", callable->val);
		valuePush(ctxt, xmlXPathNewString(""));
	} else if ( intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable) == 0) {
		php_error_docref(NULL, E_WARNING, "Not allowed to call handler '%s()'", callable->val);
		/* Push an empty string, so that we at least have an xslt result... */
		valuePush(ctxt, xmlXPathNewString(""));
	} else {
		result = zend_call_function(&fci, NULL);
		if (result == FAILURE) {
			if (Z_TYPE(handler) == IS_STRING) {
				php_error_docref(NULL, E_WARNING, "Unable to call handler %s()", Z_STRVAL(handler));
				valuePush(ctxt, xmlXPathNewString(""));
			}
		/* retval is == NULL, when an exception occurred, don't report anything, because PHP itself will handle that */
		} else if (Z_ISUNDEF(retval)) {
		} else {
			if (Z_TYPE(retval) == IS_OBJECT && instanceof_function(Z_OBJCE(retval), dom_node_class_entry)) {
				xmlNode *nodep;
				dom_object *obj;
				if (intern->node_list == NULL) {
					ALLOC_HASHTABLE(intern->node_list);
					zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
				}
				Z_ADDREF(retval);
				zend_hash_next_index_insert(intern->node_list, &retval);
				obj = Z_DOMOBJ_P(&retval);
				nodep = dom_object_get_node(obj);
				valuePush(ctxt, xmlXPathNewNodeSet(nodep));
			} else if (Z_TYPE(retval) == IS_TRUE || Z_TYPE(retval) == IS_FALSE) {
				valuePush(ctxt, xmlXPathNewBoolean(Z_LVAL(retval)));
			} else if (Z_TYPE(retval) == IS_OBJECT) {
				php_error_docref(NULL, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
				valuePush(ctxt, xmlXPathNewString(""));
			} else {
				convert_to_string_ex(&retval);
				valuePush(ctxt, xmlXPathNewString(Z_STRVAL(retval)));
			}
			zval_ptr_dtor(&retval);
		}
	}
	zend_string_release(callable);
	zval_ptr_dtor(&handler);
	if (fci.param_count > 0) {
		for (i = 0; i < nargs - 1; i++) {
			zval_ptr_dtor(&args[i]);
		}
		efree(args);
	}
}
Exemplo n.º 2
0
static void dom_xpath_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
{
	zval **args;
	zval *retval;
	int result, i, ret;
	int error = 0;
	zend_fcall_info fci;
	zval handler;
	xmlXPathObjectPtr obj;
	char *str;
	char *callable = NULL;
	dom_xpath_object *intern;
	
	TSRMLS_FETCH();

	if (! zend_is_executing(TSRMLS_C)) {
		xmlGenericError(xmlGenericErrorContext,
		"xmlExtFunctionTest: Function called from outside of PHP\n");
		error = 1;
	} else {
		intern = (dom_xpath_object *) ctxt->context->userData;
		if (intern == NULL) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: failed to get the internal object\n");
			error = 1;
		}
		else if (intern->registerPhpFunctions == 0) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: PHP Object did not register PHP functions\n");
			error = 1;
		}
	}
	
	if (error == 1) {
		for (i = nargs - 1; i >= 0; i--) {
			obj = valuePop(ctxt);
			xmlXPathFreeObject(obj);
		}
		return;
	}
		
	fci.param_count = nargs - 1;
	if (fci.param_count > 0) {
		fci.params = safe_emalloc(fci.param_count, sizeof(zval**), 0);
		args = safe_emalloc(fci.param_count, sizeof(zval *), 0);
	}
	/* Reverse order to pop values off ctxt stack */
	for (i = nargs - 2; i >= 0; i--) {
		obj = valuePop(ctxt);
		MAKE_STD_ZVAL(args[i]);
		switch (obj->type) {
			case XPATH_STRING:
				ZVAL_STRING(args[i],  (char *)obj->stringval, 1);
				break;
			case XPATH_BOOLEAN:
				ZVAL_BOOL(args[i],  obj->boolval);
				break;
			case XPATH_NUMBER:
				ZVAL_DOUBLE(args[i], obj->floatval);
				break;
			case XPATH_NODESET:
				if (type == 1) {
					str = (char *)xmlXPathCastToString(obj);
					ZVAL_STRING(args[i], str, 1);
					xmlFree(str);
				} else if (type == 2) {
					int j;
					array_init(args[i]);
					if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
						for (j = 0; j < obj->nodesetval->nodeNr; j++) {
							xmlNodePtr node = obj->nodesetval->nodeTab[j];
							zval *child;
							MAKE_STD_ZVAL(child);
							/* not sure, if we need this... it's copied from xpath.c */
							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(node->doc, NULL, (xmlChar *) node->children, node->name);
								} else {
									node = xmlNewDocNode(node->doc, NULL, (xmlChar *) "xmlns", node->name);
								}
								node->type = XML_NAMESPACE_DECL;
								node->parent = nsparent;
								node->ns = curns;
							}
							child = php_dom_create_object(node, &ret, NULL, child, (dom_object *)intern TSRMLS_CC);
							add_next_index_zval(args[i], child);
						}
					}
				}
				break;
			default:
			ZVAL_STRING(args[i], (char *)xmlXPathCastToString(obj), 1);
		}
		xmlXPathFreeObject(obj);
		fci.params[i] = &args[i];
	}
	
	fci.size = sizeof(fci);
	fci.function_table = EG(function_table);
	
	obj = valuePop(ctxt);
	if (obj->stringval == NULL) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Handler name must be a string");
		xmlXPathFreeObject(obj);
		if (fci.param_count > 0) {
			for (i = 0; i < nargs - 1; i++) {
				zval_ptr_dtor(&args[i]);
			}
			efree(args);
			efree(fci.params);
		}
		return; 
	}
	INIT_PZVAL(&handler);
	ZVAL_STRING(&handler, obj->stringval, 1);
	xmlXPathFreeObject(obj);

	fci.function_name = &handler;
	fci.symbol_table = NULL;
	fci.object_ptr = NULL;
	fci.retval_ptr_ptr = &retval;
	fci.no_separation = 0;

	if (!zend_make_callable(&handler, &callable TSRMLS_CC)) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", callable);
		
	} else if ( intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable, strlen(callable) + 1) == 0) { 
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not allowed to call handler '%s()'.", callable);
		/* Push an empty string, so that we at least have an xslt result... */
		valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
	} else {
		result = zend_call_function(&fci, NULL TSRMLS_CC);
		if (result == FAILURE) {
			if (Z_TYPE(handler) == IS_STRING) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(&handler));
			}
		/* retval is == NULL, when an exception occured, don't report anything, because PHP itself will handle that */
		} else if (retval == NULL) {
		} else {
			if (retval->type == IS_OBJECT && instanceof_function( Z_OBJCE_P(retval), dom_node_class_entry TSRMLS_CC)) {
				xmlNode *nodep;
				dom_object *obj;
				if (intern->node_list == NULL) {
					ALLOC_HASHTABLE(intern->node_list);
					zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
				}
				zval_add_ref(&retval);
				zend_hash_next_index_insert(intern->node_list, &retval, sizeof(zval *), NULL);
				obj = (dom_object *)zend_object_store_get_object(retval TSRMLS_CC);
				nodep = dom_object_get_node(obj);
				valuePush(ctxt, xmlXPathNewNodeSet(nodep));
			} else if (retval->type == IS_BOOL) {
				valuePush(ctxt, xmlXPathNewBoolean(retval->value.lval));
			} else if (retval->type == IS_OBJECT) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
				valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
			} else {
				convert_to_string_ex(&retval);
				valuePush(ctxt, xmlXPathNewString( Z_STRVAL_P(retval)));
			}
			zval_ptr_dtor(&retval);
		}
	}
	efree(callable);
	zval_dtor(&handler);
	if (fci.param_count > 0) {
		for (i = 0; i < nargs - 1; i++) {
			zval_ptr_dtor(&args[i]);
		}
		efree(args);
		efree(fci.params);
	}
}
Exemplo n.º 3
0
static int cx_handle_instance_xpath(xmlXPathContextPtr xpath_ctx, /* {{{ */
                                    cx_xpath_t *xpath, value_list_t *vl,
                                    _Bool is_table) {
  xmlXPathObjectPtr instance_node_obj = NULL;
  xmlNodeSetPtr instance_node = NULL;

  memset(vl->type_instance, 0, sizeof(vl->type_instance));

  /* If the base xpath returns more than one block, the result is assumed to be
   * a table. The `Instance' option is not optional in this case. Check for the
   * condition and inform the user. */
  if (is_table && (xpath->instance == NULL)) {
    WARNING("curl_xml plugin: "
            "Base-XPath %s is a table (more than one result was returned), "
            "but no instance-XPath has been defined.",
            xpath->path);
    return -1;
  }

  /* instance has to be an xpath expression */
  if (xpath->instance != NULL) {
    int tmp_size;

    instance_node_obj = cx_evaluate_xpath(xpath_ctx, BAD_CAST xpath->instance);
    if (instance_node_obj == NULL)
      return -1; /* error is logged already */

    instance_node = instance_node_obj->nodesetval;
    tmp_size = (instance_node) ? instance_node->nodeNr : 0;

    if (tmp_size <= 0) {
      WARNING(
          "curl_xml plugin: "
          "relative xpath expression for 'InstanceFrom' \"%s\" doesn't match "
          "any of the nodes. Skipping the node.",
          xpath->instance);
      xmlXPathFreeObject(instance_node_obj);
      return -1;
    }

    if (tmp_size > 1) {
      WARNING("curl_xml plugin: "
              "relative xpath expression for 'InstanceFrom' \"%s\" is expected "
              "to return only one text node. Skipping the node.",
              xpath->instance);
      xmlXPathFreeObject(instance_node_obj);
      return -1;
    }

    /* ignoring the element if other than textnode/attribute */
    if (cx_if_not_text_node(instance_node->nodeTab[0])) {
      WARNING("curl_xml plugin: "
              "relative xpath expression \"%s\" is expected to return only "
              "text node "
              "which is not the case. Skipping the node.",
              xpath->instance);
      xmlXPathFreeObject(instance_node_obj);
      return -1;
    }
  } /* if (xpath->instance != NULL) */

  if (xpath->instance_prefix != NULL) {
    if (instance_node != NULL) {
      char *node_value = (char *)xmlNodeGetContent(instance_node->nodeTab[0]);
      snprintf(vl->type_instance, sizeof(vl->type_instance), "%s%s",
               xpath->instance_prefix, node_value);
      sfree(node_value);
    } else
      sstrncpy(vl->type_instance, xpath->instance_prefix,
               sizeof(vl->type_instance));
  } else {
    /* If instance_prefix and instance_node are NULL, then
     * don't set the type_instance */
    if (instance_node != NULL) {
      char *node_value = (char *)xmlNodeGetContent(instance_node->nodeTab[0]);
      sstrncpy(vl->type_instance, node_value, sizeof(vl->type_instance));
      sfree(node_value);
    }
  }

  /* Free `instance_node_obj' this late, because `instance_node' points to
   * somewhere inside this structure. */
  xmlXPathFreeObject(instance_node_obj);

  return 0;
} /* }}} int cx_handle_instance_xpath */
Exemplo n.º 4
0
int parseLibFile(const std::wstring& _wstXML, MacroInfoList& info, std::wstring& libname)
{
    info.clear();

    char* pstFile = wide_string_to_UTF8(_wstXML.data());

    if (FileExist(pstFile) == FALSE)
    {
        FREE(pstFile);
        return 1;
    }
    std::string s(_wstXML.begin(),_wstXML.end());
    std::ifstream file(s);
    if (file)
    {
        const std::string XMLDecl("<?xml");
        std::string readXMLDecl;
        readXMLDecl.resize(XMLDecl.length(),' ');//reserve space
        file.read(&*readXMLDecl.begin(),XMLDecl.length());
        if (XMLDecl != readXMLDecl)
        {
          return 4;
        }
    }

    char *encoding = GetXmlFileEncoding(pstFile);

    /* Don't care about line return / empty line */
    xmlKeepBlanksDefault(0);
    /* check if the XML file has been encoded with utf8 (unicode) or not */
    if (stricmp("utf-8", encoding))
    {
        FREE(pstFile);
        free(encoding);
        return 3;
    }

    xmlDocPtr doc;
    xmlXPathContextPtr xpathCtxt = NULL;
    xmlXPathObjectPtr xpathObj = NULL;
    wchar_t* pstName = NULL;
    wchar_t* pstLibName = NULL;
    wchar_t* pstFileName = NULL;
    wchar_t* pstMd5 = NULL;

    free(encoding);

    doc = xmlParseFile(pstFile);

    if (doc == NULL)
    {
        FREE(pstFile);
        return 3;
    }

    FREE(pstFile);

    xpathCtxt = xmlXPathNewContext(doc);
    xpathObj = xmlXPathEval((const xmlChar*)"//scilablib", xpathCtxt);
    if (xpathObj && xpathObj->nodesetval->nodeMax)
    {
        xmlAttrPtr attrib = xpathObj->nodesetval->nodeTab[0]->properties;
        if (xmlStrEqual(attrib->name, (const xmlChar*)"name"))
        {
            /* we found the tag name */
            const char *str = (const char*)attrib->children->content;
            pstLibName = to_wide_string(str);
            libname = pstLibName;
            FREE(pstLibName);
            xmlXPathFreeObject(xpathObj);
        }
        else
        {
            if (xpathCtxt)
            {
                xmlXPathFreeContext(xpathCtxt);
            }
            xmlXPathFreeObject(xpathObj);
            return 1;
        }
    }

    xpathObj = xmlXPathEval((const xmlChar*)"//scilablib/macro", xpathCtxt);
    if (xpathObj && xpathObj->nodesetval->nodeMax)
    {
        /* the Xpath has been understood and there are node */
        for (int i = 0; i < xpathObj->nodesetval->nodeNr; i++)
        {
            xmlAttrPtr attrib = xpathObj->nodesetval->nodeTab[i]->properties;
            /* Get the properties of <module>  */
            while (attrib != NULL)
            {
                /* loop until when have read all the attributes */
                if (xmlStrEqual(attrib->name, (const xmlChar*)"name"))
                {
                    /* we found the tag name */
                    const char *str = (const char*)attrib->children->content;
                    pstName = to_wide_string(str);
                }
                else if (xmlStrEqual(attrib->name, (const xmlChar*)"file"))
                {
                    /* we found the tag activate */
                    const char *str = (const char*)attrib->children->content;
                    pstFileName = to_wide_string(str);
                }
                else if (xmlStrEqual(attrib->name, (const xmlChar*)"md5"))
                {
                    /* we found the tag activate */
                    const char *str = (const char*)attrib->children->content;
                    pstMd5 = to_wide_string(str);
                }
                attrib = attrib->next;
            }

            if (pstName && pstFileName && pstMd5)
            {
                info[pstFileName] = MacroInfo(pstName, pstFileName, pstMd5);
            }

            if (pstName)
            {
                FREE(pstName);
                pstName = NULL;
            }

            if (pstFileName)
            {
                FREE(pstFileName);
                pstFileName = NULL;
            }

            if (pstMd5)
            {
                FREE(pstMd5);
                pstMd5 = NULL;
            }
        }
    }

    if (xpathObj)
    {
        xmlXPathFreeObject(xpathObj);
    }
    if (xpathCtxt)
    {
        xmlXPathFreeContext(xpathCtxt);
    }

    xmlFreeDoc(doc);
    return 0;
}
Exemplo n.º 5
0
/**
 * xmlXIncludeLoadDoc:
 * @ctxt:  the XInclude context
 * @url:  the associated URL
 * @nr:  the xinclude node number
 *
 * Load the document, and store the result in the XInclude context
 */
static void
xmlXIncludeLoadDoc(xmlXIncludeCtxtPtr ctxt, const xmlChar *url, int nr) {
    xmlDocPtr doc;
    xmlURIPtr uri;
    xmlChar *URL;
    xmlChar *fragment = NULL;
    int i;
    /*
     * Check the URL and remove any fragment identifier
     */
    uri = xmlParseURI((const char *)url);
    if (uri == NULL) {
        xmlGenericError(xmlGenericErrorContext,
                        "XInclude: invalid value URI %s\n", url);
        return;
    }
    if (uri->fragment != NULL) {
        fragment = (xmlChar *) uri->fragment;
        uri->fragment = NULL;
    }
    URL = xmlSaveUri(uri);
    xmlFreeURI(uri);
    if (URL == NULL) {
        xmlGenericError(xmlGenericErrorContext,
                        "XInclude: invalid value URI %s\n", url);
        if (fragment != NULL)
            xmlFree(fragment);
        return;
    }

    /*
     * Handling of references to the local document are done
     * directly through ctxt->doc.
     */
    if ((URL[0] == 0) || (URL[0] == '#')) {
        doc = NULL;
        goto loaded;
    }

    /*
     * Prevent reloading twice the document.
     */
    for (i = 0; i < ctxt->docNr; i++) {
        if (xmlStrEqual(URL, ctxt->urlTab[i])) {
            doc = ctxt->docTab[i];
            goto loaded;
        }
    }
    /*
     * Load it.
     */
    doc = xmlParseFile((const char *)URL);
    if (doc == NULL) {
        xmlGenericError(xmlGenericErrorContext,
                        "XInclude: could not load %s\n", URL);
        xmlFree(URL);
        if (fragment != NULL)
            xmlFree(fragment);
        return;
    }
    xmlXIncludeAddDoc(ctxt, doc, URL);

loaded:
    if (fragment == NULL) {
        /*
         * Add the top children list as the replacement copy.
         */
        if (doc == NULL)
        {
            /* Hopefully a DTD declaration won't be copied from
             * the same document */
            ctxt->repTab[nr] = xmlCopyNodeList(ctxt->doc->children);
        } else {
            ctxt->repTab[nr] = xmlXIncludeCopyNodeList(ctxt, ctxt->doc,
                               doc, doc->children);
        }
    } else {
        /*
         * Computes the XPointer expression and make a copy used
         * as the replacement copy.
         */
        xmlXPathObjectPtr xptr;
        xmlXPathContextPtr xptrctxt;
        xmlNodeSetPtr set;

        if (doc == NULL) {
            xptrctxt = xmlXPtrNewContext(ctxt->doc, ctxt->incTab[nr], NULL);
        } else {
            xptrctxt = xmlXPtrNewContext(doc, NULL, NULL);
        }
        if (xptrctxt == NULL) {
            xmlGenericError(xmlGenericErrorContext,
                            "XInclude: could create XPointer context\n");
            xmlFree(URL);
            xmlFree(fragment);
            return;
        }
        xptr = xmlXPtrEval(fragment, xptrctxt);
        if (xptr == NULL) {
            xmlGenericError(xmlGenericErrorContext,
                            "XInclude: XPointer evaluation failed: #%s\n",
                            fragment);
            xmlXPathFreeContext(xptrctxt);
            xmlFree(URL);
            xmlFree(fragment);
            return;
        }
        switch (xptr->type) {
        case XPATH_UNDEFINED:
        case XPATH_BOOLEAN:
        case XPATH_NUMBER:
        case XPATH_STRING:
        case XPATH_POINT:
        case XPATH_USERS:
        case XPATH_XSLT_TREE:
            xmlGenericError(xmlGenericErrorContext,
                            "XInclude: XPointer is not a range: #%s\n",
                            fragment);
            xmlXPathFreeContext(xptrctxt);
            xmlFree(URL);
            xmlFree(fragment);
            return;
        case XPATH_NODESET:
        case XPATH_RANGE:
        case XPATH_LOCATIONSET:
            break;
        }
        set = xptr->nodesetval;
        if (set != NULL) {
            for (i = 0; i < set->nodeNr; i++) {
                if (set->nodeTab[i] == NULL)
                    continue;
                switch (set->nodeTab[i]->type) {
                case XML_TEXT_NODE:
                case XML_CDATA_SECTION_NODE:
                case XML_ELEMENT_NODE:
                case XML_ENTITY_REF_NODE:
                case XML_ENTITY_NODE:
                case XML_PI_NODE:
                case XML_COMMENT_NODE:
                case XML_DOCUMENT_NODE:
                case XML_HTML_DOCUMENT_NODE:
#ifdef LIBXML_DOCB_ENABLED
                case XML_DOCB_DOCUMENT_NODE:
#endif
                    continue;
                case XML_ATTRIBUTE_NODE:
                    xmlGenericError(xmlGenericErrorContext,
                                    "XInclude: XPointer selects an attribute: #%s\n",
                                    fragment);
                    set->nodeTab[i] = NULL;
                    continue;
                case XML_NAMESPACE_DECL:
                    xmlGenericError(xmlGenericErrorContext,
                                    "XInclude: XPointer selects a namespace: #%s\n",
                                    fragment);
                    set->nodeTab[i] = NULL;
                    continue;
                case XML_DOCUMENT_TYPE_NODE:
                case XML_DOCUMENT_FRAG_NODE:
                case XML_NOTATION_NODE:
                case XML_DTD_NODE:
                case XML_ELEMENT_DECL:
                case XML_ATTRIBUTE_DECL:
                case XML_ENTITY_DECL:
                case XML_XINCLUDE_START:
                case XML_XINCLUDE_END:
                    xmlGenericError(xmlGenericErrorContext,
                                    "XInclude: XPointer selects unexpected nodes: #%s\n",
                                    fragment);
                    set->nodeTab[i] = NULL;
                    set->nodeTab[i] = NULL;
                    continue; /* for */
                }
            }
        }
        ctxt->repTab[nr] = xmlXIncludeCopyXPointer(ctxt, ctxt->doc, doc, xptr);
        xmlXPathFreeObject(xptr);
        xmlXPathFreeContext(xptrctxt);
        xmlFree(fragment);
    }
    xmlFree(URL);
}
Exemplo n.º 6
0
static void linphone_friend_list_parse_multipart_related_body(LinphoneFriendList *list, const LinphoneContent *body, const char *first_part_body) {
	xmlparsing_context_t *xml_ctx = linphone_xmlparsing_context_new();
	xmlSetGenericErrorFunc(xml_ctx, linphone_xmlparsing_genericxml_error);
	xml_ctx->doc = xmlReadDoc((const unsigned char*)first_part_body, 0, NULL, 0);
	if (xml_ctx->doc != NULL) {
		char xpath_str[MAX_XPATH_LENGTH];
		LinphoneFriend *lf;
		LinphoneContent *presence_part;
		xmlXPathObjectPtr resource_object;
		const char *version_str = NULL;
		const char *full_state_str = NULL;
		const char *uri = NULL;
		bool_t full_state = FALSE;
		int version;
		int i;

		if (linphone_create_xml_xpath_context(xml_ctx) < 0) goto end;
		xmlXPathRegisterNs(xml_ctx->xpath_ctx, (const xmlChar *)"rlmi", (const xmlChar *)"urn:ietf:params:xml:ns:rlmi");

		version_str = linphone_get_xml_attribute_text_content(xml_ctx, "/rlmi:list", "version");
		if (version_str == NULL) {
			ms_warning("rlmi+xml: No version attribute in list");
			goto end;
		}
		version = atoi(version_str);
		linphone_free_xml_text_content(version_str);
		if (version < list->expected_notification_version) {
			ms_warning("rlmi+xml: Discarding received notification with version %d because %d was expected", version, list->expected_notification_version);
			linphone_friend_list_update_subscriptions(list, NULL, FALSE); /* Refresh subscription to get new full state notify. */
			goto end;
		}

		full_state_str = linphone_get_xml_attribute_text_content(xml_ctx, "/rlmi:list", "fullState");
		if (full_state_str == NULL) {
			ms_warning("rlmi+xml: No fullState attribute in list");
			goto end;
		}
		if ((strcmp(full_state_str, "true") == 0) || (strcmp(full_state_str, "1") == 0)) {
			bctbx_list_t *l = list->friends;
			for (; l != NULL; l = l->next) {
				lf = (LinphoneFriend *)l->data;
				linphone_friend_set_presence_model(lf, NULL);
			}
			full_state = TRUE;
		}
		linphone_free_xml_text_content(full_state_str);
		if ((list->expected_notification_version == 0) && (full_state == FALSE)) {
			ms_warning("rlmi+xml: Notification with version 0 is not full state, this is not valid");
			goto end;
		}
		list->expected_notification_version = version + 1;

		resource_object = linphone_get_xml_xpath_object_for_node_list(xml_ctx, "/rlmi:list/rlmi:resource");
		if ((resource_object != NULL) && (resource_object->nodesetval != NULL)) {
			for (i = 1; i <= resource_object->nodesetval->nodeNr; i++) {
				snprintf(xpath_str, sizeof(xpath_str), "/rlmi:list/rlmi:resource[%i]/@uri", i);
				uri = linphone_get_xml_text_content(xml_ctx, xpath_str);
				if (uri == NULL) continue;
				lf = linphone_friend_list_find_friend_by_uri(list, uri);
				if (lf != NULL) {
					const char *state = NULL;
					snprintf(xpath_str, sizeof(xpath_str),"/rlmi:list/rlmi:resource[%i]/rlmi:instance/@state", i);
					state = linphone_get_xml_text_content(xml_ctx, xpath_str);
					if ((state != NULL) && (strcmp(state, "active") == 0)) {
						const char *cid = NULL;
						snprintf(xpath_str, sizeof(xpath_str),"/rlmi:list/rlmi:resource[%i]/rlmi:instance/@cid", i);
						cid = linphone_get_xml_text_content(xml_ctx, xpath_str);
						if (cid != NULL) {
							presence_part = linphone_content_find_part_by_header(body, "Content-Id", cid);
							if (presence_part == NULL) {
								ms_warning("rlmi+xml: Cannot find part with Content-Id: %s", cid);
							} else {
								SalPresenceModel *presence = NULL;
								linphone_notify_parse_presence(linphone_content_get_type(presence_part), linphone_content_get_subtype(presence_part), linphone_content_get_string_buffer(presence_part), &presence);
								if (presence != NULL) {
									lf->presence_received = TRUE;
									linphone_friend_set_presence_model(lf, (LinphonePresenceModel *)presence);
									if (full_state == FALSE) {
										linphone_core_notify_notify_presence_received(list->lc, lf);
									}
								}
								linphone_content_unref(presence_part);
							}
						}
						if (cid != NULL) linphone_free_xml_text_content(cid);
					}
					if (state != NULL) linphone_free_xml_text_content(state);
					lf->subscribe_active = TRUE;
				}
				linphone_free_xml_text_content(uri);
			}
		}
		if (resource_object != NULL) xmlXPathFreeObject(resource_object);

		if (full_state == TRUE) {
			bctbx_list_t *l = list->friends;
			for (; l != NULL; l = l->next) {
				lf = (LinphoneFriend *)l->data;
				if (linphone_friend_is_presence_received(lf) == TRUE) {
					linphone_core_notify_notify_presence_received(list->lc, lf);
				}
			}
		}
	} else {
		ms_warning("Wrongly formatted rlmi+xml body: %s", xml_ctx->errorBuffer);
	}

end:
	linphone_xmlparsing_context_destroy(xml_ctx);
}
Exemplo n.º 7
0
static int
refresh_lists (void)
{
    int n;

    n = virConnectNumOfDomains (conn);
    if (n < 0) {
        VIRT_ERROR (conn, "reading number of domains");
        return -1;
    }

    if (n > 0) {
        int i;
        int *domids;

        /* Get list of domains. */
        domids = malloc (sizeof (int) * n);
        if (domids == 0) {
            ERROR ("libvirt plugin: malloc failed.");
            return -1;
        }

        n = virConnectListDomains (conn, domids, n);
        if (n < 0) {
            VIRT_ERROR (conn, "reading list of domains");
            sfree (domids);
            return -1;
        }

        free_block_devices ();
        free_interface_devices ();
        free_domains ();

        /* Fetch each domain and add it to the list, unless ignore. */
        for (i = 0; i < n; ++i) {
            virDomainPtr dom = NULL;
            const char *name;
            char *xml = NULL;
            xmlDocPtr xml_doc = NULL;
            xmlXPathContextPtr xpath_ctx = NULL;
            xmlXPathObjectPtr xpath_obj = NULL;
            int j;

            dom = virDomainLookupByID (conn, domids[i]);
            if (dom == NULL) {
                VIRT_ERROR (conn, "virDomainLookupByID");
                /* Could be that the domain went away -- ignore it anyway. */
                continue;
            }

            name = virDomainGetName (dom);
            if (name == NULL) {
                VIRT_ERROR (conn, "virDomainGetName");
                goto cont;
            }

            if (il_domains && ignorelist_match (il_domains, name) != 0)
                goto cont;

            if (add_domain (dom) < 0) {
                ERROR ("libvirt plugin: malloc failed.");
                goto cont;
            }

            /* Get a list of devices for this domain. */
            xml = virDomainGetXMLDesc (dom, 0);
            if (!xml) {
                VIRT_ERROR (conn, "virDomainGetXMLDesc");
                goto cont;
            }

            /* Yuck, XML.  Parse out the devices. */
            xml_doc = xmlReadDoc ((xmlChar *) xml, NULL, NULL, XML_PARSE_NONET);
            if (xml_doc == NULL) {
                VIRT_ERROR (conn, "xmlReadDoc");
                goto cont;
            }

            xpath_ctx = xmlXPathNewContext (xml_doc);

            /* Block devices. */
            xpath_obj = xmlXPathEval
                ((xmlChar *) "/domain/devices/disk/target[@dev]",
                 xpath_ctx);
            if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
                xpath_obj->nodesetval == NULL)
                goto cont;

            for (j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
                xmlNodePtr node;
                char *path = NULL;

                node = xpath_obj->nodesetval->nodeTab[j];
                if (!node) continue;
                path = (char *) xmlGetProp (node, (xmlChar *) "dev");
                if (!path) continue;

                if (il_block_devices &&
                    ignore_device_match (il_block_devices, name, path) != 0)
                    goto cont2;

                add_block_device (dom, path);
            cont2:
                if (path) xmlFree (path);
            }
            xmlXPathFreeObject (xpath_obj);

            /* Network interfaces. */
            xpath_obj = xmlXPathEval
                ((xmlChar *) "/domain/devices/interface[target[@dev]]",
                 xpath_ctx);
            if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
                xpath_obj->nodesetval == NULL)
                goto cont;

            xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;

            for (j = 0; j < xml_interfaces->nodeNr; ++j) {
                char *path = NULL;
                char *address = NULL;
                xmlNodePtr xml_interface;

                xml_interface = xml_interfaces->nodeTab[j];
                if (!xml_interface) continue;
                xmlNodePtr child = NULL;

                for (child = xml_interface->children; child; child = child->next) {
                    if (child->type != XML_ELEMENT_NODE) continue;

                    if (xmlStrEqual(child->name, (const xmlChar *) "target")) {
                        path = (char *) xmlGetProp (child, (const xmlChar *) "dev");
                        if (!path) continue;
                    } else if (xmlStrEqual(child->name, (const xmlChar *) "mac")) {
                        address = (char *) xmlGetProp (child, (const xmlChar *) "address");
                        if (!address) continue;
                    }
                }

                if (il_interface_devices &&
                    (ignore_device_match (il_interface_devices, name, path) != 0 ||
                     ignore_device_match (il_interface_devices, name, address) != 0))
                    goto cont3;

                add_interface_device (dom, path, address);
                cont3:
                    if (path) xmlFree (path);
                    if (address) xmlFree (address);
            }

        cont:
            if (xpath_obj) xmlXPathFreeObject (xpath_obj);
            if (xpath_ctx) xmlXPathFreeContext (xpath_ctx);
            if (xml_doc) xmlFreeDoc (xml_doc);
            sfree (xml);
        }

        sfree (domids);
    }

    return 0;
}
Exemplo n.º 8
0
/**
 * get content of xpath pointer
 */
int xcaps_xpath_get(str *inbuf, str *xpaths, str *outbuf)
{
	xmlDocPtr doc = NULL;
	xmlXPathContextPtr xpathCtx = NULL; 
	xmlXPathObjectPtr xpathObj = NULL; 
	xmlNodeSetPtr nodes;
	xmlChar *keyword;
	xmlBufferPtr psBuf;
	int size;
	int i;
	char *p;
	char *end;
	char *pos;

	doc = xmlParseMemory(inbuf->s, inbuf->len);
	if(doc == NULL)
		return -1;

	xpathCtx = xmlXPathNewContext(doc);
	if(xpathCtx == NULL)
	{
		LM_ERR("unable to create new XPath context\n");
		goto error;
	}
	
	/* Evaluate xpath expression */
	// xcaps_xpath_register_ns(xpathCtx);
	xpathObj = xmlXPathEvalExpression(
					(const xmlChar*)xpaths->s, xpathCtx);
	if(xpathObj == NULL)
	{
		LM_ERR("unable to evaluate xpath expression [%s]\n", xpaths->s);
		goto error;
	}
    nodes = xpathObj->nodesetval;
	if(nodes==NULL)
	{
		outbuf->len = 0;
		outbuf->s[outbuf->len] = '\0';
		goto done;
	}
	size = nodes->nodeNr;
    p = outbuf->s;
	end = outbuf->s + outbuf->len;
	for(i = 0; i < size; ++i)
	{
		if(nodes->nodeTab[i]==NULL)
			continue;
		if(i!=0)
		{
			if(p>=end)
			{
				LM_ERR("output buffer overflow\n");
				goto error;
			}
			*p = ',';
			p++;
		}
		if(nodes->nodeTab[i]->type == XML_ATTRIBUTE_NODE)
		{
			keyword = xmlNodeListGetString(doc,
				nodes->nodeTab[i]->children, 0);
			if(keyword != NULL)
			{
				pos = p + strlen((char*)keyword);
				if(pos>=end)
				{
					LM_ERR("output buffer overflow\n");
					goto error;
				}
				strcpy(p, (char*)keyword);
				p = pos;
				xmlFree(keyword);
				keyword = NULL;
			}
		} else {
			if(nodes->nodeTab[i]->content!=NULL)
			{
				pos = p + strlen((char*)nodes->nodeTab[i]->content);
				if(pos>=end)
				{
					LM_ERR("output buffer overflow\n");
					goto error;
				}
				strcpy(p, (char*)nodes->nodeTab[i]->content);
				p = pos;
			} else {
				psBuf = xmlBufferCreate();
				if(psBuf != NULL && xmlNodeDump(psBuf, doc,
						nodes->nodeTab[i], 0, 0)>0)
				{
					pos = p + strlen((char*)xmlBufferContent(psBuf));
					if(pos>=end)
					{
						LM_ERR("output buffer overflow\n");
						goto error;
					}
					strcpy(p, (char*)xmlBufferContent(psBuf));
					p = pos;
				}
				if(psBuf != NULL) xmlBufferFree(psBuf);
				psBuf = NULL;
			}
		}
	}
	outbuf->len = p - outbuf->s;
	outbuf->s[outbuf->len] = '\0';

done:
	if(xpathObj!=NULL) xmlXPathFreeObject(xpathObj);
	if(xpathCtx!=NULL) xmlXPathFreeContext(xpathCtx); 
	if(doc!=NULL) xmlFreeDoc(doc);
	xpathObj = NULL;
	xpathCtx = NULL; 
	doc = NULL; 
	return 0;

error:
	if(xpathObj!=NULL) xmlXPathFreeObject(xpathObj);
	if(xpathCtx!=NULL) xmlXPathFreeContext(xpathCtx); 
	if(doc!=NULL) xmlFreeDoc(doc);
	xpathObj = NULL;
	xpathCtx = NULL; 
	doc = NULL; 
	outbuf->len = 0;
	outbuf->s[outbuf->len] = '\0';
	return -1;
}
Exemplo n.º 9
0
/**
 * set content of xpath pointer
 */
int xcaps_xpath_set(str *inbuf, str *xpaths, str *val, str *outbuf)
{
	xmlDocPtr doc = NULL;
	xmlDocPtr newnode = NULL;
	xmlXPathContextPtr xpathCtx = NULL; 
	xmlXPathObjectPtr xpathObj = NULL; 
	xmlNodeSetPtr nodes;
	const xmlChar* value = NULL;
	xmlChar *xmem = NULL;
	xmlNodePtr parent = NULL;
	int size;
	int i;
	char *p;

	doc = xmlParseMemory(inbuf->s, inbuf->len);
	if(doc == NULL)
		return -1;

	if(val!=NULL)
	{
		newnode = xmlParseMemory(val->s, val->len);
		if(newnode==NULL)
			goto error;
	}

	outbuf->s   = NULL;
	outbuf->len = 0;

	xpathCtx = xmlXPathNewContext(doc);
	if(xpathCtx == NULL)
	{
		LM_ERR("unable to create new XPath context\n");
		goto error;
	}
	
	/* Evaluate xpath expression */
	xpathObj = xmlXPathEvalExpression(
					(const xmlChar*)xpaths->s, xpathCtx);
	if(xpathObj == NULL)
	{
		LM_ERR("unable to evaluate xpath expression [%s]\n", xpaths->s);
		goto error;
	}
	nodes = xpathObj->nodesetval;
	if(nodes==NULL || nodes->nodeNr==0 || nodes->nodeTab == NULL)
	{
		/* no selection for xpath expression */
		LM_DBG("no selection for xpath expression [%s]\n", xpaths->s);
		if(val==NULL)
			goto done;
		/* could be an insert - locate the selection of parent node */
		p = strrchr(xpaths->s, '/');
		if(p==NULL)
			goto done;
		/* evaluate xpath expression for parrent node */
		*p = 0;
		xpathObj = xmlXPathEvalExpression(
					(const xmlChar*)xpaths->s, xpathCtx);
		if(xpathObj == NULL)
		{
			LM_DBG("unable to evaluate xpath parent expression [%s]\n",
					xpaths->s);
			*p = '/';
			goto done;
		}
		*p = '/';
		nodes = xpathObj->nodesetval;
		if(nodes==NULL || nodes->nodeNr==0 || nodes->nodeTab == NULL)
		{
			LM_DBG("no selection for xpath parent expression [%s]\n",
					xpaths->s);
			goto done;
		}
		/* add the new content as child to first selected element node */
		if(nodes->nodeTab[0]==NULL)
		{
			LM_DBG("selection for xpath parent expression has first child"
					" NULL [%s]\n", xpaths->s);
			goto done;
		}
		if(nodes->nodeTab[0]->type==XML_ELEMENT_NODE)
		{
			xmlAddChild(nodes->nodeTab[0], xmlCopyNode(newnode->children, 1));
		} else {
			LM_DBG("selection for xpath parent expression is not element"
					" node [%s]\n", xpaths->s);
			goto done;
		}
	} else {
		/* selection for xpath expression */
		size = nodes->nodeNr;
		if(val!=NULL)
			value = (const xmlChar*)val->s;
    
	/*
	 * NOTE: the nodes are processed in reverse order, i.e. reverse document
	 *       order because xmlNodeSetContent can actually free up descendant
	 *       of the node and such nodes may have been selected too ! Handling
	 *       in reverse order ensure that descendant are accessed first, before
	 *       they get removed. Mixing XPath and modifications on a tree must be
	 *       done carefully !
	 */
		for(i = size - 1; i >= 0; i--) {
			if(nodes->nodeTab[i]==NULL)
				continue;

			if(nodes->nodeTab[i]->type==XML_ELEMENT_NODE)
			{
				parent = nodes->nodeTab[i]->parent;
				xmlUnlinkNode(nodes->nodeTab[i]);
				if(val!=NULL && newnode!=NULL)
					xmlAddChild(parent, xmlCopyNode(newnode->children, 1));
			} else {
				if(val!=NULL)
					xmlNodeSetContent(nodes->nodeTab[i], value);
				else
					xmlNodeSetContent(nodes->nodeTab[i], (const xmlChar*)"");
			}
		/*
		 * All the elements returned by an XPath query are pointers to
		 * elements from the tree *except* namespace nodes where the XPath
		 * semantic is different from the implementation in libxml2 tree.
		 * As a result when a returned node set is freed when
		 * xmlXPathFreeObject() is called, that routine must check the
		 * element type. But node from the returned set may have been removed
		 * by xmlNodeSetContent() resulting in access to freed data.
		 * This can be exercised by running
		 *       valgrind xpath2 test3.xml '//discarded' discarded
		 * There is 2 ways around it:
		 *   - make a copy of the pointers to the nodes from the result set 
		 *     then call xmlXPathFreeObject() and then modify the nodes
		 * or
		 *   - remove the reference to the modified nodes from the node set
		 *     as they are processed, if they are not namespace nodes.
		 */
			if (nodes->nodeTab[i]->type != XML_NAMESPACE_DECL)
				nodes->nodeTab[i] = NULL;
		}
	}

	xmlDocDumpMemory(doc, &xmem, &size);
	if(xmem==NULL)
	{
		LM_ERR("error printing output\n");
		goto error;
	}

	if(size<=0)
	{
		LM_ERR("invalid output size\n");
		xmlFree(xmem);
		goto error;
	}
	outbuf->s = (char*)pkg_malloc(size+1);
	if(outbuf->s==NULL)
	{
		LM_ERR("no pkg for output\n");
		xmlFree(xmem);
		goto error;
	}
	memcpy(outbuf->s, xmem, size);
	outbuf->s[size] = '\0';
	outbuf->len = size;
	xmlFree(xmem);

done:
	if(xpathObj!=NULL) xmlXPathFreeObject(xpathObj);
	if(xpathCtx!=NULL) xmlXPathFreeContext(xpathCtx); 
	if(doc!=NULL) xmlFreeDoc(doc);
	if(newnode!=NULL) xmlFreeDoc(newnode);
	xpathObj = NULL;
	xpathCtx = NULL; 
	doc = NULL; 
	return 0;

error:
	if(xpathObj!=NULL) xmlXPathFreeObject(xpathObj);
	if(xpathCtx!=NULL) xmlXPathFreeContext(xpathCtx); 
	if(doc!=NULL) xmlFreeDoc(doc);
	if(newnode!=NULL) xmlFreeDoc(newnode);
	xpathObj = NULL;
	xpathCtx = NULL; 
	doc = NULL; 
	outbuf->s =   NULL;
	outbuf->len = 0;
	return -1;
}
Exemplo n.º 10
0
static xmlSecNodeSetPtr
xmlSecXPathDataExecute(xmlSecXPathDataPtr data, xmlDocPtr doc, xmlNodePtr hereNode) {
    xmlXPathObjectPtr xpathObj = NULL;
    xmlSecNodeSetPtr nodes;

    xmlSecAssert2(data != NULL, NULL);
    xmlSecAssert2(data->expr != NULL, NULL);
    xmlSecAssert2(data->ctx != NULL, NULL);
    xmlSecAssert2(doc != NULL, NULL);
    xmlSecAssert2(hereNode != NULL, NULL);

    /* do not forget to set the doc */
    data->ctx->doc = doc;

    /* here function works only on the same document */
    if(hereNode->doc == doc) {
        xmlXPathRegisterFunc(data->ctx, (xmlChar *)"here", xmlSecXPathHereFunction);
        data->ctx->here = hereNode;
        data->ctx->xptr = 1;
    }

    /* execute xpath or xpointer expression */
    switch(data->type) {
    case xmlSecXPathDataTypeXPath:
    case xmlSecXPathDataTypeXPath2:
        xpathObj = xmlXPathEvalExpression(data->expr, data->ctx);
        if(xpathObj == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlXPathEvalExpression",
                        XMLSEC_ERRORS_R_XML_FAILED,
                        "expr=%s",
                        xmlSecErrorsSafeString(data->expr));
            return(NULL);
        }
        break;
    case xmlSecXPathDataTypeXPointer:
        xpathObj = xmlXPtrEval(data->expr, data->ctx);
        if(xpathObj == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlXPtrEval",
                        XMLSEC_ERRORS_R_XML_FAILED,
                        "expr=%s",
                        xmlSecErrorsSafeString(data->expr));
            return(NULL);
        }
        break;
    }

    /* sometime LibXML2 returns an empty nodeset or just NULL, we want
    to reserve NULL for our own purposes so we simply create an empty
    node set here */
    if(xpathObj->nodesetval == NULL) {
	xpathObj->nodesetval = xmlXPathNodeSetCreate(NULL);
	if(xpathObj->nodesetval == NULL) {
		xmlXPathFreeObject(xpathObj);
		xmlSecError(XMLSEC_ERRORS_HERE,
			NULL,
                        "xmlXPathNodeSetCreate",
                        XMLSEC_ERRORS_R_XML_FAILED,
                        "expr=%s",
                        xmlSecErrorsSafeString(data->expr));
            	return(NULL);
	}
    }

    nodes = xmlSecNodeSetCreate(doc, xpathObj->nodesetval, data->nodeSetType);
    if(nodes == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecNodeSetCreate",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    "type=%d", data->nodeSetType);
        xmlXPathFreeObject(xpathObj);
        return(NULL);
    }
    xpathObj->nodesetval = NULL;
    xmlXPathFreeObject(xpathObj);

    return(nodes);
}
Exemplo n.º 11
0
void xml_value(	const char	*xmlBuf,
       		const char	*elementName, 
       		int 		elementNumber, 
		const char	*childName,
		int		childNumber,
		char		**value,
       		int		*iret )
/************************************************************************
 * xml_value                                                            *
 *                                                                      *
 * This function returns the value of the specified element that is     *
 * contained in an xml file.   						*
 * 									*
 * The input element is actually part of an XPath expression.  This     *
 * expression by default assumes the searched for element is a child    *
 * of the root node of the xml document (/root/elementName).  The root  *
 * node should not be specified in elementName, however.  This routine  *
 * will prepend "[slash]*[slash]" to the beginning of the element name, *
 * thus always matching the root.					* 
 *                                                                      *
 * See additional documentation and usage examples of this and other    *
 * cgemlib/xml library routines at:					*
 *									*
 *	$NAWIPS/doc/Prog_guid/xml/cgemlibxml.sxw.			*
 *									*
 *                                                                      *
 * int xml_value( xmlBuf, elementName, elementNumber, childName,        *
 *			childNumber, value, iret ) 			*
 *                                                                      *
 * Input parameters:                                                    *
 *      *xmlBuf		const char	buffer containing xml document  *
 *	*elementName	const char	element name to be counted	* 
 *	elementNumber 	int       	element number or 0         	*
 *      *childName   	const char	name of child element or NULL   *
 *	childNumber 	int       	child number or 0          	*
 *                                                                      *
 * Output parameters:                                                   *
 *	**value		char		value of element (calling 	*
 *					  routine must free memory)	*
 *      *iret           int             Return code                     *
 *					  1 = non-fatal xpath error     *
 *					       see Valid Inputs above   *
 *                                        0 = normal                    *
 *                                       -1 = bad xmlBuf pointer (NULL) *
 *                                       -2 = bufSize <= 0              *
 *					 -3 = fatal error creating      *
 *					       XPath expression		*
 *					-15 = error executing xpath expr*
 *                                       -9 = node list is empty        *
 *                                      -16 = xpath expr returned more  *
 *						than one node		*
 *					 -9 = selected node is empty	*
 **                                                                     *
 * Log:                                                                 *
 * E. Safford/SAIC	11/05	initial coding (adapted from tutorial   *
 *				 by Aleksey Sanin, Copyright 2004, used *
 *                               under GNU Free Documentation License)  *
 * E. Safford/SAIC	04/06	correct error codes with xml.err	*
 ***********************************************************************/
{
    int 		ier, bufSize = 0, size = 0;
    xmlChar		*xpathExpr = NULL;
    xmlXPathObjectPtr	xpathObj;
    xmlNodeSetPtr	nodes;
    xmlNodePtr 		curNode;
    xmlDocPtr 		doc; 

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

    *iret = 0;

    /*
     *  sanity check on parameters
     */ 
    if( xmlBuf == NULL ) {
	*iret = -1;
	return;
    }
    
    bufSize = strlen( xmlBuf );

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


    /* 
     * Init libxml 
     */
    xmlInitParser();


    /*
     * Make the xpath expression
     */
    xml_makeXpathExpr( elementName, elementNumber, childName, 
    		       childNumber, NULL, &xpathExpr, &ier );

    if( ier < 0 ) {
	*iret = -3;
	G_FREE( xpathExpr, xmlChar );
	return;
    }
    else if( ier > 0 ) {
	*iret = 1;
    }


    xml_executeXpathExpr( xmlBuf, bufSize, xpathExpr, &doc, &xpathObj, &ier );
    if( ier != 0 ) {
        *iret = -15;
    }
    else {
        nodes = xpathObj->nodesetval;
        if( nodes ) {
            size = nodes->nodeNr;
        }


        /*
         *  Size indicates the number of nodes returned from the XPath 
	 *  expression.  This should be 1 and only 1; both 0 and > 1 are 
	 *  errors.  0 means the XPath expression didn't match anything, 
	 *  and > 1 means it matched too many things and we can't identify
	 *  a unique value to return.
         */
        if( size <= 0 ) {
	    *iret = -9;
        }

        if( size > 1 ) {
	    *iret = -16;
        }
    }


    if( *iret >= 0 ) {

        /*
         *  Return the content of the node.  This must be an XML_TEXT_NODE and 
	 *  it must have non-NULL content.  Any other condition is an error.
         */
        curNode = nodes->nodeTab[0];

        if( curNode->type == XML_ELEMENT_NODE ) {
	    curNode= curNode->children;
        }

	if( ( curNode->type == XML_TEXT_NODE ) && curNode->content ) {
	    *value = malloc( (strlen( (char *)(curNode->content) ) + 1) * 
	    			sizeof( char ));
	    strcpy( *value, (char *)curNode->content );
        }
        else {
	    *iret = -9;
        }
    }

    /* 
     * Shutdown libxml and clean up
     */
    xmlCleanupParser();
    G_FREE( xpathExpr, xmlChar );

    xmlXPathFreeObject( xpathObj );
    xmlFreeDoc( doc ); 
    
    return;
}
Exemplo n.º 12
0
// 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;
}
Exemplo n.º 13
0
PyObject *
libxml_xmlXPathObjectPtrWrap(xmlXPathObjectPtr obj)
{
    PyObject *ret;

#ifdef DEBUG
    printf("libxml_xmlXPathObjectPtrWrap: ctxt = %p\n", obj);
#endif
    if (obj == NULL) {
        Py_INCREF(Py_None);
        return (Py_None);
    }
    switch (obj->type) {
    case XPATH_XSLT_TREE: {
        if ((obj->nodesetval == NULL) ||
                (obj->nodesetval->nodeNr == 0) ||
                (obj->nodesetval->nodeTab == NULL)) {
            ret = PyList_New(0);
        } else {
            int i, len = 0;
            xmlNodePtr node;

            node = obj->nodesetval->nodeTab[0]->children;
            while (node != NULL) {
                len++;
                node = node->next;
            }
            ret = PyList_New(len);
            node = obj->nodesetval->nodeTab[0]->children;
            for (i = 0; i < len; i++) {
                PyList_SetItem(ret, i, libxml_xmlNodePtrWrap(node));
                node = node->next;
            }
        }
        /*
         * Return now, do not free the object passed down
         */
        return (ret);
    }
    case XPATH_NODESET:
        if ((obj->nodesetval == NULL)
                || (obj->nodesetval->nodeNr == 0)) {
            ret = PyList_New(0);
        } else {
            int i;
            xmlNodePtr node;

            ret = PyList_New(obj->nodesetval->nodeNr);
            for (i = 0; i < obj->nodesetval->nodeNr; i++) {
                node = obj->nodesetval->nodeTab[i];
                if (node->type == XML_NAMESPACE_DECL) {
                    PyObject *ns = PyCapsule_New((void *) node,
                                                 (char *) "xmlNsPtr",
                                                 libxml_xmlXPathDestructNsNode);
                    PyList_SetItem(ret, i, ns);
                    /* make sure the xmlNsPtr is not destroyed now */
                    obj->nodesetval->nodeTab[i] = NULL;
                } else {
                    PyList_SetItem(ret, i, libxml_xmlNodePtrWrap(node));
                }
            }
        }
        break;
    case XPATH_BOOLEAN:
        ret = PY_IMPORT_INT((long) obj->boolval);
        break;
    case XPATH_NUMBER:
        ret = PyFloat_FromDouble(obj->floatval);
        break;
    case XPATH_STRING:
        ret = PY_IMPORT_STRING((char *) obj->stringval);
        break;
    case XPATH_POINT:
    {
        PyObject *node;
        PyObject *indexIntoNode;
        PyObject *tuple;

        node = libxml_xmlNodePtrWrap(obj->user);
        indexIntoNode = PY_IMPORT_INT((long) obj->index);

        tuple = PyTuple_New(2);
        PyTuple_SetItem(tuple, 0, node);
        PyTuple_SetItem(tuple, 1, indexIntoNode);

        ret = tuple;
        break;
    }
    case XPATH_RANGE:
    {
        unsigned short bCollapsedRange;

        bCollapsedRange = ( (obj->user2 == NULL) ||
                            ((obj->user2 == obj->user) && (obj->index == obj->index2)) );
        if ( bCollapsedRange ) {
            PyObject *node;
            PyObject *indexIntoNode;
            PyObject *tuple;
            PyObject *list;

            list = PyList_New(1);

            node = libxml_xmlNodePtrWrap(obj->user);
            indexIntoNode = PY_IMPORT_INT((long) obj->index);

            tuple = PyTuple_New(2);
            PyTuple_SetItem(tuple, 0, node);
            PyTuple_SetItem(tuple, 1, indexIntoNode);

            PyList_SetItem(list, 0, tuple);

            ret = list;
        } else {
            PyObject *node;
            PyObject *indexIntoNode;
            PyObject *tuple;
            PyObject *list;

            list = PyList_New(2);

            node = libxml_xmlNodePtrWrap(obj->user);
            indexIntoNode = PY_IMPORT_INT((long) obj->index);

            tuple = PyTuple_New(2);
            PyTuple_SetItem(tuple, 0, node);
            PyTuple_SetItem(tuple, 1, indexIntoNode);

            PyList_SetItem(list, 0, tuple);

            node = libxml_xmlNodePtrWrap(obj->user2);
            indexIntoNode = PY_IMPORT_INT((long) obj->index2);

            tuple = PyTuple_New(2);
            PyTuple_SetItem(tuple, 0, node);
            PyTuple_SetItem(tuple, 1, indexIntoNode);

            PyList_SetItem(list, 1, tuple);

            ret = list;
        }
        break;
    }
    case XPATH_LOCATIONSET:
    {
        xmlLocationSetPtr set;

        set = obj->user;
        if ( set && set->locNr > 0 ) {
            int i;
            PyObject *list;

            list = PyList_New(set->locNr);

            for (i=0; i<set->locNr; i++) {
                xmlXPathObjectPtr setobj;
                PyObject *pyobj;

                setobj = set->locTab[i]; /*xmlXPathObjectPtr setobj*/

                pyobj = libxml_xmlXPathObjectPtrWrap(setobj);
                /* xmlXPathFreeObject(setobj) is called */
                set->locTab[i] = NULL;

                PyList_SetItem(list, i, pyobj);
            }
            set->locNr = 0;
            ret = list;
        } else {
            Py_INCREF(Py_None);
            ret = Py_None;
        }
        break;
    }
    default:
#ifdef DEBUG
        printf("Unable to convert XPath object type %d\n", obj->type);
#endif
        Py_INCREF(Py_None);
        ret = Py_None;
    }
    xmlXPathFreeObject(obj);
    return (ret);
}
Exemplo n.º 14
0
char * read_scheda(char *baseUrl, xmlChar *url, char *epgdb_root)
{
	static char buf[2048];
	int i;
	FILE *fd;
	char cachefile[strlen(epgdb_root) + strlen((char*)url) + 2];
	htmlDocPtr docScheda = NULL;
	xmlXPathContextPtr contextScheda = NULL;
	xmlXPathObjectPtr par = NULL;
	xmlChar *urlScheda = NULL;

	/* build cache filename */
	buf[0]='\0';
	strcpy(cachefile, epgdb_root);
	cachefile[strlen(epgdb_root)] = '/';
	for (i=0; i<strlen((char*)url); i++)
		if (url[i] == '/' || url[i] == '\\' || url[i] == '?' || url[i] == '&' || url[i] == '=')
			cachefile[i+strlen(epgdb_root)+1] = '_';
		else
			cachefile[i+strlen(epgdb_root)+1] = url[i];

	cachefile[i+strlen(epgdb_root)+1] = '\0';
	
	/* try to read from cache */
	fd = fopen(cachefile, "r");
	if (fd)
	{
		fread(buf, 2048, 1, fd);
		fclose(fd);
		return buf;
	}
	
	/* ok... no cache... download it! */
	urlScheda = xmlBuildURI(url, (xmlChar *)baseUrl);
	
	if (urlScheda != NULL )
	{
		docScheda = htmlReadFile((char *)urlScheda, NULL, HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);

		if (docScheda != NULL )
		{
			contextScheda = xmlXPathNewContext(docScheda);

			if (contextScheda != NULL)
			{
				// Prende il primo paragrafo sotto la div con id="box"
				par = xmlXPathEvalExpression((const xmlChar *)"//div[@id='box']/p[1]", contextScheda);

				if (par != NULL && !xmlXPathNodeSetIsEmpty(par->nodesetval))
				{
					append_scheda(buf, par->nodesetval->nodeTab[0]->children, 0, 2048);
					
					xmlXPathFreeObject(par);
				}

				xmlXPathFreeContext(contextScheda);
			}

			xmlFreeDoc(docScheda);
		}
	
		xmlFree(urlScheda);
	}

	/* save the cache */
	if (strlen(buf) > 0)
	{
		fd = fopen(cachefile, "w");
		if (fd)
		{
			fwrite(buf, strlen(buf)+1, 1, fd);
			fclose(fd);
		}
	}
	
	return buf;
}
Exemplo n.º 15
0
Arquivo: board.cpp Projeto: fkp/src
bool Board::InitFromXMLFile(const char * fileName)
{
  bool toReturn = false;
  xmlDocPtr doc;
  xmlXPathContextPtr xpathCtx; 
  xmlXPathObjectPtr xpathObj; 
  int ret;

  // Init libxml
  xmlInitParser();
  LIBXML_TEST_VERSION

  assert(fileName);
  assert(XPathExpression);

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

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

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

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

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

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

  return toReturn;
}
Exemplo n.º 16
0
/**
 * xsltICUSortFunction:
 * @ctxt:  a XSLT process context
 * @sorts:  array of sort nodes
 * @nbsorts:  the number of sorts in the array
 *
 * reorder the current node list accordingly to the set of sorting
 * requirement provided by the arry of nodes.
 * uses the ICU library
 */
void
xsltICUSortFunction(xsltTransformContextPtr ctxt, xmlNodePtr *sorts,
	           int nbsorts) {
    xmlXPathObjectPtr *resultsTab[XSLT_MAX_SORT];
    xmlXPathObjectPtr *results = NULL, *res;
    xmlNodeSetPtr list = NULL;
    int descending, number, desc, numb;
    int len = 0;
    int i, j, incr;
    int tst;
    int depth;
    xmlNodePtr node;
    xmlXPathObjectPtr tmp;
    xsltStylePreCompPtr comp;
    int tempstype[XSLT_MAX_SORT], temporder[XSLT_MAX_SORT];

    /* Start ICU change */
    UCollator *coll = 0;
    UConverter *conv;
    UErrorCode status;
    UChar *target,*target2;
    int targetlen, target2len;
    /* End ICU change */

    if ((ctxt == NULL) || (sorts == NULL) || (nbsorts <= 0) ||
	(nbsorts >= XSLT_MAX_SORT))
	return;
    if (sorts[0] == NULL)
	return;
    comp = sorts[0]->_private;
    if (comp == NULL)
	return;

    list = ctxt->nodeList;
    if ((list == NULL) || (list->nodeNr <= 1))
	return; /* nothing to do */

    for (j = 0; j < nbsorts; j++) {
	comp = sorts[j]->_private;
	tempstype[j] = 0;
	if ((comp->stype == NULL) && (comp->has_stype != 0)) {
	    comp->stype =
		xsltEvalAttrValueTemplate(ctxt, sorts[j],
					  (const xmlChar *) "data-type",
					  XSLT_NAMESPACE);
	    if (comp->stype != NULL) {
		tempstype[j] = 1;
		if (xmlStrEqual(comp->stype, (const xmlChar *) "text"))
		    comp->number = 0;
		else if (xmlStrEqual(comp->stype, (const xmlChar *) "number"))
		    comp->number = 1;
		else {
		    xsltTransformError(ctxt, NULL, sorts[j],
			  "xsltDoSortFunction: no support for data-type = %s\n",
				     comp->stype);
		    comp->number = 0; /* use default */
		}
	    }
	}
	temporder[j] = 0;
	if ((comp->order == NULL) && (comp->has_order != 0)) {
	    comp->order = xsltEvalAttrValueTemplate(ctxt, sorts[j],
						    (const xmlChar *) "order",
						    XSLT_NAMESPACE);
	    if (comp->order != NULL) {
		temporder[j] = 1;
		if (xmlStrEqual(comp->order, (const xmlChar *) "ascending"))
		    comp->descending = 0;
		else if (xmlStrEqual(comp->order,
				     (const xmlChar *) "descending"))
		    comp->descending = 1;
		else {
		    xsltTransformError(ctxt, NULL, sorts[j],
			     "xsltDoSortFunction: invalid value %s for order\n",
				     comp->order);
		    comp->descending = 0; /* use default */
		}
	    }
	}
    }

    len = list->nodeNr;

    resultsTab[0] = xsltComputeSortResult(ctxt, sorts[0]);
    for (i = 1;i < XSLT_MAX_SORT;i++)
	resultsTab[i] = NULL;

    results = resultsTab[0];

    comp = sorts[0]->_private;
    descending = comp->descending;
    number = comp->number;
    if (results == NULL)
	return;

    /* Start ICU change */
    status = U_ZERO_ERROR;
    conv = ucnv_open("UTF8", &status);
    if(U_FAILURE(status)) {
	xsltTransformError(ctxt, NULL, NULL, "xsltICUSortFunction: Error opening converter\n");
    }	
    if(comp->has_lang) 
	coll = ucol_open(comp->lang, &status);
    if(U_FAILURE(status) || !comp->has_lang) {
	status = U_ZERO_ERROR;
	coll = ucol_open("en", &status);
    }
    if(U_FAILURE(status)) {
	xsltTransformError(ctxt, NULL, NULL, "xsltICUSortFunction: Error opening collator\n");
    }
    if(comp->lower_first) 
	ucol_setAttribute(coll,UCOL_CASE_FIRST,UCOL_LOWER_FIRST,&status);
    else 
	ucol_setAttribute(coll,UCOL_CASE_FIRST,UCOL_UPPER_FIRST,&status);
    if(U_FAILURE(status)) {
	xsltTransformError(ctxt, NULL, NULL, "xsltICUSortFunction: Error setting collator attribute\n");
    }
    /* End ICU change */

    /* Shell's sort of node-set */
    for (incr = len / 2; incr > 0; incr /= 2) {
	for (i = incr; i < len; i++) {
	    j = i - incr;
	    if (results[i] == NULL)
		continue;
	    
	    while (j >= 0) {
		if (results[j] == NULL)
		    tst = 1;
		else {
		    if (number) {
			if (results[j]->floatval == results[j + incr]->floatval)
			    tst = 0;
			else if (results[j]->floatval > 
				results[j + incr]->floatval)
			    tst = 1;
			else tst = -1;
		    } else {
/*			tst = xmlStrcmp(results[j]->stringval,
				     results[j + incr]->stringval); */
			/* Start ICU change */
			targetlen = xmlStrlen(results[j]->stringval) * 2;
			target2len = xmlStrlen(results[j + incr]->stringval) * 2;
			target = xmlMalloc(targetlen * sizeof(UChar));
			target2 = xmlMalloc(target2len * sizeof(UChar));
			targetlen = ucnv_toUChars(conv, target, targetlen, results[j]->stringval, -1, &status);
			target2len = ucnv_toUChars(conv, target2, target2len, results[j+incr]->stringval, -1, &status);
			tst = ucol_strcoll(coll, target, u_strlen(target), target2, u_strlen(target2));
			/* End ICU change */
		    }
		    if (descending)
			tst = -tst;
		}
		if (tst == 0) {
		    /*
		     * Okay we need to use multi level sorts
		     */
		    depth = 1;
		    while (depth < nbsorts) {
			if (sorts[depth] == NULL)
			    break;
			comp = sorts[depth]->_private;
			if (comp == NULL)
			    break;
			desc = comp->descending;
			numb = comp->number;

			/*
			 * Compute the result of the next level for the
			 * full set, this might be optimized ... or not
			 */
			if (resultsTab[depth] == NULL) 
			    resultsTab[depth] = xsltComputeSortResult(ctxt,
				                        sorts[depth]);
			res = resultsTab[depth];
			if (res == NULL) 
			    break;
			if (res[j] == NULL)
			    tst = 1;
			else {
			    if (numb) {
				if (res[j]->floatval == res[j + incr]->floatval)
				    tst = 0;
				else if (res[j]->floatval > 
					res[j + incr]->floatval)
				    tst = 1;
				else tst = -1;
			    } else {
/*				tst = xmlStrcmp(res[j]->stringval,
					     res[j + incr]->stringval); */
				/* Start ICU change */
				targetlen = xmlStrlen(res[j]->stringval) * 2;
				target2len = xmlStrlen(res[j + incr]->stringval) * 2;
				target = xmlMalloc(targetlen * sizeof(UChar));
				target2 = xmlMalloc(target2len * sizeof(UChar));
				targetlen = ucnv_toUChars(conv, target, targetlen, res[j]->stringval, -1, &status);
				target2len = ucnv_toUChars(conv, target2, target2len, res[j+incr]->stringval, -1, &status);
				tst = ucol_strcoll(coll, target, u_strlen(target), target2, u_strlen(target2));
				/* End ICU change */
			    }
			    if (desc)
			      tst = -tst;
			}
			/*
			 * if we still can't differenciate at this level
			 * try one level deeper.
			 */
			if (tst != 0)
			    break;
			depth++;
		    }
		}
		if (tst == 0) {
		    tst = results[j]->index > results[j + incr]->index;
		}
		if (tst > 0) {
		    tmp = results[j];
		    results[j] = results[j + incr];
		    results[j + incr] = tmp;
		    node = list->nodeTab[j];
		    list->nodeTab[j] = list->nodeTab[j + incr];
		    list->nodeTab[j + incr] = node;
		    depth = 1;
		    while (depth < nbsorts) {
			if (sorts[depth] == NULL)
			    break;
			if (resultsTab[depth] == NULL)
			    break;
			res = resultsTab[depth];
			tmp = res[j];
			res[j] = res[j + incr];
			res[j + incr] = tmp;
			depth++;
		    }
		    j -= incr;
		} else
		    break;
	    }
	}
    }

    /* Start ICU change */
    ucol_close(coll);
    ucnv_close(conv);
    /* End ICU change */

    for (j = 0; j < nbsorts; j++) {
	comp = sorts[j]->_private;
	if (tempstype[j] == 1) {
	    /* The data-type needs to be recomputed each time */
	    xmlFree(comp->stype);
	    comp->stype = NULL;
	}
	if (temporder[j] == 1) {
	    /* The order needs to be recomputed each time */
	    xmlFree(comp->order);
	    comp->order = NULL;
	}
	if (resultsTab[j] != NULL) {
	    for (i = 0;i < len;i++)
		xmlXPathFreeObject(resultsTab[j][i]);
	    xmlFree(resultsTab[j]);
	}
    }
}
Exemplo n.º 17
0
static int
rest_show_check(noit_http_rest_closure_t *restc,
                int npats, char **pats) {
  noit_http_session_ctx *ctx = restc->http_ctx;
  xmlXPathObjectPtr pobj = NULL;
  xmlXPathContextPtr xpath_ctxt = NULL;
  xmlDocPtr doc = NULL;
  xmlNodePtr node, root, attr, config, state, tmp, anode;
  uuid_t checkid;
  noit_check_t *check;
  char xpath[1024], *uuid_conf, *module, *value;
  int rv, cnt, error_code = 500;
  noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
  const char *k;
  int klen;
  void *data;
  noit_hash_table *configh;

  if(npats != 2) goto error;

  rv = noit_check_xpath(xpath, sizeof(xpath), pats[0], pats[1]);
  if(rv == 0) goto not_found;
  if(rv < 0) goto error;

  noit_conf_xml_xpath(NULL, &xpath_ctxt);
  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET ||
     xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto not_found;
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  if(cnt != 1) goto error;

  node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
  uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
  if(!uuid_conf || uuid_parse(uuid_conf, checkid)) goto error;

  doc = xmlNewDoc((xmlChar *)"1.0");
  root = xmlNewDocNode(doc, NULL, (xmlChar *)"check", NULL);
  xmlDocSetRootElement(doc, root);

#define MYATTR(node,a,n,b) _noit_conf_get_string(node, &(n), "@" #a, &(b))
#define INHERIT(node,a,n,b) \
  _noit_conf_get_string(node, &(n), "ancestor-or-self::node()/@" #a, &(b))
#define SHOW_ATTR(parent, node, a) do { \
  xmlNodePtr anode = NULL; \
  char *value = NULL; \
  INHERIT(node, a, anode, value); \
  if(value != NULL) { \
    int clen, plen;\
    const char *cpath, *apath; \
    xmlNodePtr child; \
    cpath = node ? (char *)xmlGetNodePath(node) : ""; \
    apath = anode ? (char *)xmlGetNodePath(anode) : ""; \
    clen = strlen(cpath); \
    plen = strlen("/noit/checks"); \
    child = xmlNewNode(NULL, (xmlChar *)#a); \
    xmlNodeAddContent(child, (xmlChar *)value); \
    if(!strncmp(cpath, apath, clen) && apath[clen] == '/') { \
    } \
    else { \
      xmlSetProp(child, (xmlChar *)"inherited", (xmlChar *)apath+plen); \
    } \
    xmlAddChild(parent, child); \
  } \
} while(0)

  attr = xmlNewNode(NULL, (xmlChar *)"attributes");
  xmlAddChild(root, attr);

  SHOW_ATTR(attr,node,uuid);

  /* Name is odd, it falls back transparently to module */
  if(!INHERIT(node, module, tmp, module)) module = NULL;
  xmlAddChild(attr, (tmp = xmlNewNode(NULL, (xmlChar *)"name")));
  if(MYATTR(node, name, anode, value))
    xmlNodeAddContent(tmp, (xmlChar *)value);
  else if(module)
    xmlNodeAddContent(tmp, (xmlChar *)module);

  SHOW_ATTR(attr,node,module);
  SHOW_ATTR(attr,node,target);
  SHOW_ATTR(attr,node,period);
  SHOW_ATTR(attr,node,timeout);
  SHOW_ATTR(attr,node,oncheck);
  SHOW_ATTR(attr,node,filterset);
  SHOW_ATTR(attr,node,disable);

  /* Add the config */
  config = xmlNewNode(NULL, (xmlChar *)"config");
  configh = noit_conf_get_hash(node, "config");
  while(noit_hash_next(configh, &iter, &k, &klen, &data))
    NODE_CONTENT(config, k, data);
  noit_hash_destroy(configh, free, free);
  free(configh);
  xmlAddChild(root, config);

  /* Add the state */
  check = noit_poller_lookup(checkid);
  if(!check) {
    state = xmlNewNode(NULL, (xmlChar *)"state");
    xmlSetProp(state, (xmlChar *)"error", (xmlChar *)"true");
  }
  else
    state = noit_check_state_as_xml(check);
  xmlAddChild(root, state);
  noit_http_response_ok(ctx, "text/xml");
  noit_http_response_xml(ctx, doc);
  noit_http_response_end(ctx);
  goto cleanup;

 not_found:
  noit_http_response_not_found(ctx, "text/html");
  noit_http_response_end(ctx);
  goto cleanup;

 error:
  noit_http_response_standard(ctx, error_code, "ERROR", "text/html");
  noit_http_response_end(ctx);
  goto cleanup;

 cleanup:
  if(pobj) xmlXPathFreeObject(pobj);
  if(doc) xmlFreeDoc(doc);
  return 0;
}
Exemplo n.º 18
0
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);
}
Exemplo n.º 19
0
void
te_update_diff(const char *event, xmlNode *msg)
{
	int rc = -1;
	const char *op = NULL;

	xmlNode *diff = NULL;
	xmlNode *cib_top = NULL;
	xmlXPathObject *xpathObj = NULL;

	int diff_add_updates     = 0;
	int diff_add_epoch       = 0;
	int diff_add_admin_epoch = 0;

	int diff_del_updates     = 0;
	int diff_del_epoch       = 0;
	int diff_del_admin_epoch = 0;
	
	CRM_CHECK(msg != NULL, return);
	crm_element_value_int(msg, F_CIB_RC, &rc);	

	if(transition_graph == NULL) {
	    crm_debug_3("No graph");
	    return;

	} else if(rc < cib_ok) {
	    crm_debug_3("Filter rc=%d (%s)", rc, cib_error2string(rc));
	    return;

	} else if(transition_graph->complete == TRUE
		  && fsa_state != S_IDLE
		  && fsa_state != S_TRANSITION_ENGINE
		  && fsa_state != S_POLICY_ENGINE) {
	    crm_debug_2("Filter state=%s, complete=%d", fsa_state2string(fsa_state), transition_graph->complete);
	    return;
	} 	

	op = crm_element_value(msg, F_CIB_OPERATION);
	diff = get_message_xml(msg, F_CIB_UPDATE_RESULT);

	cib_diff_version_details(
		diff,
		&diff_add_admin_epoch, &diff_add_epoch, &diff_add_updates, 
		&diff_del_admin_epoch, &diff_del_epoch, &diff_del_updates);
	
	crm_debug("Processing diff (%s): %d.%d.%d -> %d.%d.%d (%s)", op,
		  diff_del_admin_epoch,diff_del_epoch,diff_del_updates,
		  diff_add_admin_epoch,diff_add_epoch,diff_add_updates,
		  fsa_state2string(fsa_state));
	log_cib_diff(LOG_DEBUG_2, diff, op);

	/* Process anything that was added */
	cib_top = get_xpath_object("//"F_CIB_UPDATE_RESULT"//"XML_TAG_DIFF_ADDED"//"XML_TAG_CIB, diff, LOG_ERR);
	if(need_abort(cib_top)) {
	    goto bail; /* configuration changed */
	}

	/* Process anything that was removed */
	cib_top = get_xpath_object("//"F_CIB_UPDATE_RESULT"//"XML_TAG_DIFF_REMOVED"//"XML_TAG_CIB, diff, LOG_ERR);
	if(need_abort(cib_top)) {
	    goto bail; /* configuration changed */
	}

	/* Transient Attributes - Added/Updated */
	xpathObj = xpath_search(diff,"//"F_CIB_UPDATE_RESULT"//"XML_TAG_DIFF_ADDED"//"XML_TAG_TRANSIENT_NODEATTRS"//"XML_CIB_TAG_NVPAIR);
	if(xpathObj && xpathObj->nodesetval->nodeNr > 0) {
	    int lpc;
	    for(lpc = 0; lpc < xpathObj->nodesetval->nodeNr; lpc++) {
		xmlNode *attr = getXpathResult(xpathObj, lpc);
		const char *name = crm_element_value(attr, XML_NVPAIR_ATTR_NAME);
		const char *value = NULL;
		
		if(safe_str_eq(CRM_OP_PROBED, name)) {
		    value = crm_element_value(attr, XML_NVPAIR_ATTR_VALUE);
		}

		if(crm_is_true(value) == FALSE) {
		    abort_transition(INFINITY, tg_restart, "Transient attribute: update", attr);
		    crm_log_xml_debug_2(attr, "Abort");
		    goto bail;
		}
	    }

	} else if(xpathObj) {
	    xmlXPathFreeObject(xpathObj);
	}
	
	/* Transient Attributes - Removed */
	xpathObj = xpath_search(diff,"//"F_CIB_UPDATE_RESULT"//"XML_TAG_DIFF_REMOVED"//"XML_TAG_TRANSIENT_NODEATTRS);
	if(xpathObj && xpathObj->nodesetval->nodeNr > 0) {
	    xmlNode *aborted = getXpathResult(xpathObj, 0);
	    abort_transition(INFINITY, tg_restart, "Transient attribute: removal", aborted);
	    goto bail;

	} else if(xpathObj) {
	    xmlXPathFreeObject(xpathObj);
	}

	/* Check for node state updates... possibly from a shutdown we requested */
	xpathObj = xpath_search(diff, "//"F_CIB_UPDATE_RESULT"//"XML_TAG_DIFF_ADDED"//"XML_CIB_TAG_STATE);
	if(xpathObj) {
	    int lpc = 0, max = xpathObj->nodesetval->nodeNr;
	    for(lpc = 0; lpc < max; lpc++) {
		xmlNode *node = getXpathResult(xpathObj, lpc);
		const char *event_node = crm_element_value(node, XML_ATTR_ID);
		const char *ccm_state  = crm_element_value(node, XML_CIB_ATTR_INCCM);
		const char *ha_state   = crm_element_value(node, XML_CIB_ATTR_HASTATE);
		const char *shutdown_s = crm_element_value(node, XML_CIB_ATTR_SHUTDOWN);
		const char *crmd_state = crm_element_value(node, XML_CIB_ATTR_CRMDSTATE);

		if(safe_str_eq(ccm_state, XML_BOOLEAN_FALSE)
		   || safe_str_eq(ha_state, DEADSTATUS)
		   || safe_str_eq(crmd_state, CRMD_JOINSTATE_DOWN)) {
		    crm_action_t *shutdown = match_down_event(0, event_node, NULL);
		    
		    if(shutdown != NULL) {
			const char *task = crm_element_value(shutdown->xml, XML_LRM_ATTR_TASK);
			if(safe_str_neq(task, CRM_OP_FENCE)) {
			    /* Wait for stonithd to tell us it is complete via tengine_stonith_callback() */
			    update_graph(transition_graph, shutdown);
			    trigger_graph();
			}
			
		    } else {
			crm_info("Stonith/shutdown of %s not matched", event_node);
			abort_transition(INFINITY, tg_restart, "Node failure", node);
		    }			
		    fail_incompletable_actions(transition_graph, event_node);
		}
	 
		if(shutdown_s) {
		    int shutdown = crm_parse_int(shutdown_s, NULL);
		    if(shutdown > 0) {
			crm_info("Aborting on "XML_CIB_ATTR_SHUTDOWN" attribute for %s", event_node);
			abort_transition(INFINITY, tg_restart, "Shutdown request", node);
		    }
		}
	    }
	    xmlXPathFreeObject(xpathObj);
	}

	/*
	 * Check for and fast-track the processing of LRM refreshes
	 * In large clusters this can result in _huge_ speedups
	 *
	 * Unfortunately we can only do so when there are no pending actions
	 * Otherwise we could miss updates we're waiting for and stall 
	 *
	 */
	xpathObj = NULL;
	if(transition_graph->pending == 0) {
	    xpathObj = xpath_search(diff, "//"F_CIB_UPDATE_RESULT"//"XML_TAG_DIFF_ADDED"//"XML_LRM_TAG_RESOURCE);
	}
	
	if(xpathObj) {
	    int updates = xpathObj->nodesetval->nodeNr;
	    if(updates > 1) {
		/* Updates by, or in response to, TE actions will never contain updates
		 * for more than one resource at a time
		 */
		crm_info("Detected LRM refresh - %d resources updated: Skipping all resource events", updates);
		abort_transition(INFINITY, tg_restart, "LRM Refresh", diff);
		goto bail;
	    }
	    xmlXPathFreeObject(xpathObj);
	}

	/* Process operation updates */
	xpathObj = xpath_search(diff, "//"F_CIB_UPDATE_RESULT"//"XML_TAG_DIFF_ADDED"//"XML_LRM_TAG_RSC_OP);
	if(xpathObj) {
	    process_resource_updates(xpathObj);
	    xmlXPathFreeObject(xpathObj);
	}
	
	/* Detect deleted (as opposed to replaced or added) actions - eg. crm_resource -C */ 
	xpathObj = xpath_search(diff, "//"XML_TAG_DIFF_REMOVED"//"XML_LRM_TAG_RSC_OP);
	if(xpathObj) {
	    int lpc = 0, max = xpathObj->nodesetval->nodeNr;
	    
	    for(lpc = 0; lpc < max; lpc++) {
		int max = 0;
		const char *op_id = NULL;
		char *rsc_op_xpath = NULL;
		xmlXPathObject *op_match = NULL;
		xmlNode *match = getXpathResult(xpathObj, lpc);
		CRM_CHECK(match != NULL, continue);

		op_id = ID(match);

		max = strlen(rsc_op_template) + strlen(op_id) + 1;
		crm_malloc0(rsc_op_xpath, max);
		snprintf(rsc_op_xpath, max, rsc_op_template, op_id);
		
		op_match = xpath_search(diff, rsc_op_xpath);
		if(op_match == NULL || op_match->nodesetval->nodeNr == 0) {
		    /* Prevent false positives by matching cancelations too */
		    const char *node = get_node_id(match);
		    crm_action_t *cancelled = get_cancel_action(op_id, node);

		    if(cancelled == NULL) {
			crm_debug("No match for deleted action %s (%s on %s)", rsc_op_xpath, op_id, node);
			abort_transition(INFINITY, tg_restart, "Resource op removal", match);
			if(op_match) {
			    xmlXPathFreeObject(op_match);
			}
			crm_free(rsc_op_xpath);
			goto bail;

		    } else {
			crm_debug("Deleted lrm_rsc_op %s on %s was for graph event %d",
				  op_id, node, cancelled->id);
		    }
		}

		if(op_match) {
		    xmlXPathFreeObject(op_match);
		}
		crm_free(rsc_op_xpath);
	    }
	}

  bail:
	if(xpathObj) {
	    xmlXPathFreeObject(xpathObj);
	}
}
Exemplo n.º 20
0
/*< private >*/
static gboolean
lt_region_db_parse(lt_region_db_t  *regiondb,
		   GError         **error)
{
	gboolean retval = TRUE;
	xmlDocPtr doc = NULL;
	xmlXPathContextPtr xctxt = NULL;
	xmlXPathObjectPtr xobj = NULL;
	GError *err = NULL;
	int i, n;

	g_return_val_if_fail (regiondb != NULL, FALSE);

	doc = lt_xml_get_subtag_registry(regiondb->xml);
	xctxt = xmlXPathNewContext(doc);
	if (!xctxt) {
		g_set_error(&err, LT_ERROR, LT_ERR_OOM,
			    "Unable to create an instance of xmlXPathContextPtr.");
		goto bail;
	}
	xobj = xmlXPathEvalExpression((const xmlChar *)"/registry/region", xctxt);
	if (!xobj) {
		g_set_error(&err, LT_ERROR, LT_ERR_FAIL_ON_XML,
			    "No valid elements for %s",
			    doc->name);
		goto bail;
	}
	n = xmlXPathNodeSetGetLength(xobj->nodesetval);

	for (i = 0; i < n; i++) {
		xmlNodePtr ent = xmlXPathNodeSetItem(xobj->nodesetval, i);
		xmlNodePtr cnode;
		xmlChar *subtag = NULL, *desc = NULL, *preferred = NULL;
		lt_region_t *le = NULL;
		gchar *s;

		if (!ent) {
			g_set_error(&err, LT_ERROR, LT_ERR_FAIL_ON_XML,
				    "Unable to obtain the xml node via XPath.");
			goto bail;
		}
		cnode = ent->children;
		while (cnode != NULL) {
			if (xmlStrcmp(cnode->name, (const xmlChar *)"subtag") == 0) {
				if (subtag) {
					g_warning("Duplicate subtag element in region: previous value was '%s'",
						  subtag);
				} else {
					subtag = xmlNodeGetContent(cnode);
				}
			} else if (xmlStrcmp(cnode->name, (const xmlChar *)"added") == 0 ||
				   xmlStrcmp(cnode->name, (const xmlChar *)"text") == 0 ||
				   xmlStrcmp(cnode->name, (const xmlChar *)"deprecated") == 0 ||
				   xmlStrcmp(cnode->name, (const xmlChar *)"comments") == 0) {
				/* ignore it */
			} else if (xmlStrcmp(cnode->name, (const xmlChar *)"description") == 0) {
				/* wonder if many descriptions helps something. or is it a bug? */
				if (!desc)
					desc = xmlNodeGetContent(cnode);
			} else if (xmlStrcmp(cnode->name, (const xmlChar *)"preferred-value") == 0) {
				if (preferred) {
					g_warning("Duplicate preferred-value element in region: previous value was '%s'",
						  preferred);
				} else {
					preferred = xmlNodeGetContent(cnode);
				}
			} else {
				g_warning("Unknown node under /registry/region: %s", cnode->name);
			}
			cnode = cnode->next;
		}
		if (!subtag) {
			g_warning("No subtag node: description = '%s', preferred-value = '%s'",
				  desc, preferred);
			goto bail1;
		}
		if (!desc) {
			g_warning("No description node: subtag = '%s', preferred-value = '%s'",
				  subtag, preferred);
			goto bail1;
		}
		le = lt_region_create();
		if (!le) {
			g_set_error(&err, LT_ERROR, LT_ERR_OOM,
				    "Unable to create an instance of lt_region_t.");
			goto bail1;
		}
		lt_region_set_tag(le, (const gchar *)subtag);
		lt_region_set_name(le, (const gchar *)desc);
		if (preferred)
			lt_region_set_preferred_tag(le, (const gchar *)preferred);

		s = g_strdup(lt_region_get_tag(le));
		g_hash_table_replace(regiondb->region_entries,
				     lt_strlower(s),
				     lt_region_ref(le));
	  bail1:
		if (subtag)
			xmlFree(subtag);
		if (desc)
			xmlFree(desc);
		if (preferred)
			xmlFree(preferred);
		lt_region_unref(le);
	}
  bail:
	if (err) {
		if (error)
			*error = g_error_copy(err);
		else
			g_warning(err->message);
		g_error_free(err);
		retval = FALSE;
	}

	if (xobj)
		xmlXPathFreeObject(xobj);
	if (xctxt)
		xmlXPathFreeContext(xctxt);

	return retval;
}
Exemplo n.º 21
0
static void dom_xpath_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
{
	zval retval;
	int result, i;
	int error = 0;
	zend_fcall_info fci;
	xmlXPathObjectPtr obj;
	char *str;
	zend_string *callable = NULL;
	dom_xpath_object *intern;
	
	TSRMLS_FETCH();

	if (! zend_is_executing(TSRMLS_C)) {
		xmlGenericError(xmlGenericErrorContext,
		"xmlExtFunctionTest: Function called from outside of PHP\n");
		error = 1;
	} else {
		intern = (dom_xpath_object *) ctxt->context->userData;
		if (intern == NULL) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: failed to get the internal object\n");
			error = 1;
		}
		else if (intern->registerPhpFunctions == 0) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: PHP Object did not register PHP functions\n");
			error = 1;
		}
	}
	
	if (error == 1) {
		for (i = nargs - 1; i >= 0; i--) {
			obj = valuePop(ctxt);
			xmlXPathFreeObject(obj);
		}
		return;
	}
		
	fci.param_count = nargs - 1;
	if (fci.param_count > 0) {
		fci.params = safe_emalloc(fci.param_count, sizeof(zval), 0);
	}
	/* Reverse order to pop values off ctxt stack */
	for (i = nargs - 2; i >= 0; i--) {
		obj = valuePop(ctxt);
		switch (obj->type) {
			case XPATH_STRING:
				ZVAL_STRING(&fci.params[i],  (char *)obj->stringval);
				break;
			case XPATH_BOOLEAN:
				ZVAL_BOOL(&fci.params[i],  obj->boolval);
				break;
			case XPATH_NUMBER:
				ZVAL_DOUBLE(&fci.params[i], obj->floatval);
				break;
			case XPATH_NODESET:
				if (type == 1) {
					str = (char *)xmlXPathCastToString(obj);
					ZVAL_STRING(&fci.params[i], str);
					xmlFree(str);
				} else if (type == 2) {
					int j;
					array_init(&fci.params[i]);
					if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
						for (j = 0; j < obj->nodesetval->nodeNr; j++) {
							xmlNodePtr node = obj->nodesetval->nodeTab[j];
							zval child;
							/* not sure, if we need this... it's copied from xpath.c */
							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(node->doc, NULL, (xmlChar *) node->children, node->name);
								} else {
									node = xmlNewDocNode(node->doc, NULL, (xmlChar *) "xmlns", node->name);
								}
								node->type = XML_NAMESPACE_DECL;
								node->parent = nsparent;
								node->ns = curns;
							}
							php_dom_create_object(node, &child, &intern->dom TSRMLS_CC);
							add_next_index_zval(&fci.params[i], &child);
						}
					}
				}
				break;
			default:
			ZVAL_STRING(&fci.params[i], (char *)xmlXPathCastToString(obj));
		}
		xmlXPathFreeObject(obj);
	}
	
	fci.size = sizeof(fci);
	fci.function_table = EG(function_table);
	
	obj = valuePop(ctxt);
	if (obj->stringval == NULL) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Handler name must be a string");
		xmlXPathFreeObject(obj);
		if (fci.param_count > 0) {
			for (i = 0; i < nargs - 1; i++) {
				zval_ptr_dtor(&fci.params[i]);
			}
			efree(fci.params);
		}
		return; 
	}
	ZVAL_STRING(&fci.function_name, obj->stringval);
	xmlXPathFreeObject(obj);

	fci.symbol_table = NULL;
	fci.object = NULL;
	fci.retval = &retval;
	fci.no_separation = 0;

	if (!zend_make_callable(&fci.function_name, &callable TSRMLS_CC)) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", callable->val);
	} else if (intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable) == 0) { 
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not allowed to call handler '%s()'.", callable->val);
		/* Push an empty string, so that we at least have an xslt result... */
		valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
	} else {
		result = zend_call_function(&fci, NULL TSRMLS_CC);
		if (result == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
			if (Z_TYPE(retval) == IS_OBJECT && instanceof_function(Z_OBJCE(retval), dom_node_class_entry TSRMLS_CC)) {
				xmlNode *nodep;
				dom_object *obj;
				if (intern->node_list == NULL) {
					ALLOC_HASHTABLE(intern->node_list);
					zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
				}
				GC_REFCOUNT(&retval)++;
				zend_hash_next_index_insert(intern->node_list, &retval);
				obj = Z_DOMOBJ_P(&retval);
				nodep = dom_object_get_node(obj);
				valuePush(ctxt, xmlXPathNewNodeSet(nodep));
			} else if (Z_TYPE(retval) == IS_FALSE || Z_TYPE(retval) == IS_TRUE) {
				valuePush(ctxt, xmlXPathNewBoolean(Z_TYPE(retval) == IS_TRUE));
			} else if (Z_TYPE(retval) == IS_OBJECT) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
				valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
			} else {
				zend_string *str = zval_get_string(&retval);
				valuePush(ctxt, xmlXPathNewString(str->val));
				STR_RELEASE(str);
			}
			zval_ptr_dtor(&retval);
		}
	}
	STR_RELEASE(callable);
	zval_dtor(&fci.function_name);
	if (fci.param_count > 0) {
		for (i = 0; i < nargs - 1; i++) {
			zval_ptr_dtor(&fci.params[i]);
		}
		efree(fci.params);
	}
}
Exemplo n.º 22
0
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;
}
Exemplo n.º 23
0
Arquivo: htmlp.c Projeto: miwoow/bscan
void htmlp_get_link(spider_t *sp, const char *fname, const char *encoding)
{
  htmlDocPtr docp;
  xmlXPathContextPtr context;
  int i=0, j=0;
  xmlXPathObjectPtr result;
  xmlNodeSetPtr nodeset;
  struct _xmlAttr *attrs;
  char *url;
  char complete_url[1024] = {0};
  url_queue_t *uqueue = sp->urlq;
  char *pos = NULL;
  char *cur_chr = NULL;

  char *url_tmp_buf = NULL;
  /*
  printf("*******************************\n");
  printf("%s\n", sp->cur_url);
  printf("*******************************\n");
  */

  docp = htmlParseFile(fname, encoding);
  context = xmlXPathNewContext(docp);
  result = xmlXPathEvalExpression("//a", context);
  xmlXPathFreeContext(context);
  if(!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
    nodeset = result->nodesetval;
    for(i=0; i < nodeset->nodeNr; i++) {
      attrs = nodeset->nodeTab[i]->properties;
      while(attrs) {
	if (strncasecmp(attrs->name, "href", 4) == 0) {
	  url = attrs->children->content;
	  url_tmp_buf = calloc(1, strlen(url) + 1);
	  struct struct_parts uobj;
	  memcpy(url_tmp_buf, url, strlen(url));
	  printf("===================\n");
	  printf("url:%s\n", url);
	  urlp_parse(url_tmp_buf, &uobj);
	  printf("access: %s\n", uobj.access);
	  printf("host:%s\n", uobj.host);
	  printf("absolute:%s\n", uobj.absolute);
	  printf("relative:%s\n", uobj.relative);
	  printf("search:%s\n", uobj.search);
	  printf("anchor:%s\n", uobj.anchor);
	  printf("===================\n");
	  if (uobj.access != NULL) {
	    if (strcasecmp(uobj.access, "javascript") != 0) {
	      if (uobj.host != NULL) {
		if (memcmp(uobj.host, (sp->root_url_obj).host, strlen(uobj.host)) == 0) {
		  url_queue_uniq_add(uqueue, url);
		}
	      } else {
		url_queue_uniq_add(uqueue, url);
	      }
	    }
	  } else {
	    if (uobj.access == NULL)
	      uobj.access = (sp->root_url_obj).access;
	    if (uobj.host == NULL)
	      uobj.host = (sp->root_url_obj).host;
	    if (uobj.relative || uobj.absolute) {
	      memset(complete_url, 0, 1024);
	      if (uobj.relative) {
		pos = strrchr(sp->cur_url, '/');
		if (*(pos-1) == '/' && *(pos-2) == ':') {
		  snprintf(complete_url, 1023, "%s://%s",
			   uobj.access,
			   uobj.host);
		  complete_url[strlen(complete_url)] = '/';
		  strncat(complete_url, uobj.relative, 1023);
		} else {
		  for (j=0, cur_chr = sp->cur_url; cur_chr < pos + 1; cur_chr++, j++) {
		    complete_url[j] = *cur_chr;
		  }
		  strncat(complete_url, uobj.relative, 1023);
		}
	      }
	      
	      if (uobj.absolute) {
		snprintf(complete_url, 1023, "%s://%s",
			 uobj.access,
			 uobj.host);
		complete_url[strlen(complete_url)] = '/';
		strncat(complete_url, uobj.absolute, 1023);
	      }
	    } else {
	      memset(complete_url, 0, 1024);
	      snprintf(complete_url, 1023, "%s://%s",
		       uobj.access,
		       uobj.host);
	      complete_url[strlen(complete_url)] = '/'; 
	    }
	    if (uobj.search) {
	      complete_url[strlen(complete_url)] = '?';
	      strncat(complete_url, uobj.search, 1023);
	    }
	    if (uobj.anchor) {
	      complete_url[strlen(complete_url)] = '#';
	      strncat(complete_url, uobj.anchor, 1023);
	    }
	    printf("******preurl: %s\n", complete_url);
	    urlp_strip_dot(complete_url);
	    printf("******passurl: %s\n", complete_url);
	    url_queue_uniq_add(uqueue, complete_url);
	  }
	  
	  free(url_tmp_buf);
	  break;
	}
	attrs = attrs->next;
      }
    }
  }
  xmlXPathFreeObject (result);
  xmlCleanupParser();
}
Exemplo n.º 24
0
int module_enable(struct np_module* module, int add) {
	char *config_path = NULL, *repo_path = NULL, *repo_type_str = NULL;
	int repo_type = -1, main_model_count;
	xmlDocPtr module_config;
	xmlNodePtr node;
	xmlXPathContextPtr xpath_ctxt;
	xmlXPathObjectPtr xpath_obj;

	if (asprintf(&config_path, "%s/%s.xml", MODULES_CFG_DIR, module->name) == -1) {
		nc_verb_error("asprintf() failed (%s:%d).", __FILE__, __LINE__);
		return(EXIT_FAILURE);
	}
	if ((module_config = xmlReadFile(config_path, NULL, XML_PARSE_NOBLANKS|XML_PARSE_NSCLEAN|XML_PARSE_NOWARNING|XML_PARSE_NOERROR)) == NULL) {
		nc_verb_error("Reading configuration for %s module failed", module->name);
		free(config_path);
		return(EXIT_FAILURE);
	}
	free(config_path);

	if ((xpath_ctxt = xmlXPathNewContext(module_config)) == NULL) {
		nc_verb_error("Creating XPath context failed (%s:%d - module %s)", __FILE__, __LINE__, module->name);
		return (EXIT_FAILURE);
	}

	/* get datastore information */
	if ((xpath_obj = xmlXPathEvalExpression(BAD_CAST "/device/repo", xpath_ctxt)) == NULL) {
		nc_verb_error("XPath evaluating error (%s:%d)", __FILE__, __LINE__);
		goto err_cleanup;
	} else if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
		nc_verb_verbose("repo is not unique in %s transAPI module configuration.", module->name);
		xmlXPathFreeObject(xpath_obj);
		goto err_cleanup;
	}

	for (node = xpath_obj->nodesetval->nodeTab[0]->children; node != NULL; node = node->next) {
		if (node->type != XML_ELEMENT_NODE) {
			continue;
		}
		if (xmlStrcmp(node->name, BAD_CAST "type") == 0) {
			repo_type_str = (char*)xmlNodeGetContent(node);
		} else if (xmlStrcmp(node->name, BAD_CAST "path") == 0) {
			repo_path = (char*)xmlNodeGetContent(node);
		}
	}
	if (repo_type_str == NULL) {
		nc_verb_warning("Missing attribute \'type\' in repo element for %s transAPI module.", module->name);
		repo_type_str = strdup("unknown");
	}
	if (strcmp(repo_type_str, "empty") == 0) {
		repo_type = NCDS_TYPE_EMPTY;
	} else if (strcmp(repo_type_str, "file") == 0) {
		repo_type = NCDS_TYPE_FILE;
	} else {
		nc_verb_warning("Unknown repo type \'%s\' in %s transAPI module configuration", repo_type_str, module->name);
		nc_verb_warning("Continuing with \'empty\' datastore type.");
		repo_type = NCDS_TYPE_EMPTY;
	}
	free(repo_type_str);

	if (repo_type == NCDS_TYPE_FILE && repo_path == NULL) {
		nc_verb_error("Missing path for \'file\' datastore type in %s transAPI module configuration.", module->name);
		xmlXPathFreeObject(xpath_obj);
		goto err_cleanup;
	}
	xmlXPathFreeObject(xpath_obj);

	/* get data-models element */
	if ((xpath_obj = xmlXPathEvalExpression(BAD_CAST "/device/data-models", xpath_ctxt)) == NULL) {
		nc_verb_error("XPath evaluating error (%s:%d)", __FILE__, __LINE__);
		goto err_cleanup;
	} else if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
		nc_verb_verbose("data-models is not unique in %s transAPI module configuration.", module->name);
		xmlXPathFreeObject(xpath_obj);
		goto err_cleanup;
	}

	/* parse models in the config-defined order, both main and augments */
	main_model_count = 0;
	for (node = xpath_obj->nodesetval->nodeTab[0]->children; node != NULL; node = node->next) {
		if (node->type != XML_ELEMENT_NODE) {
			continue;
		}
		if (xmlStrcmp(node->name, BAD_CAST "model") == 0) {
			parse_model_cfg(module, node, -1);
		}
		if (xmlStrcmp(node->name, BAD_CAST "model-main") == 0) {
			parse_model_cfg(module, node, repo_type);
			main_model_count++;
		}
	}
	xmlXPathFreeObject(xpath_obj);
	if (main_model_count == 0) {
		nc_verb_verbose("model-main is not present in %s transAPI module configuration.", module->name);
		goto err_cleanup;
	} else if (main_model_count > 1) {
		nc_verb_verbose("model-main is not unique in %s transAPI module configuration.", module->name);
		goto err_cleanup;
	}

	if (repo_type == NCDS_TYPE_FILE) {
		if (ncds_file_set_path(module->ds, repo_path)) {
			nc_verb_verbose("Unable to set path to datastore of the \'%s\' transAPI module.", module->name);
			goto err_cleanup;
		}
	}
	free(repo_path);
	repo_path = NULL;

	if ((module->id = ncds_init(module->ds)) < 0) {
		goto err_cleanup;
	}

	xmlXPathFreeContext(xpath_ctxt);
	xmlFreeDoc(module_config);

	if (ncds_consolidate() != 0) {
		nc_verb_warning("%s: consolidating libnetconf datastores failed for module %s.", __func__, module->name);
		return (EXIT_FAILURE);
	}

	/* remove datastore locks if any kept */
	if (server_start) {
		ncds_break_locks(NULL);
	}
	if (ncds_device_init(&(module->id), NULL, 1) != 0) {
		nc_verb_error("Device initialization of module %s failed.", module->name);
		ncds_free(module->ds);
		module->ds = NULL;
		return (EXIT_FAILURE);
	}

	if (add) {
		if (netopeer_options.modules) {
			netopeer_options.modules->prev = module;
		}
		module->next = netopeer_options.modules;
		netopeer_options.modules = module;
	}

	return (EXIT_SUCCESS);

err_cleanup:

	xmlXPathFreeContext(xpath_ctxt);
	xmlFreeDoc(module_config);

	ncds_free(module->ds);
	module->ds = NULL;

	free(repo_path);

	return (EXIT_FAILURE);
}
Exemplo n.º 25
0
/** Population a PCSCHEMA struct from the XML representation */
int
pc_schema_from_xml(const char *xml_str, PCSCHEMA **schema)
{
	xmlDocPtr xml_doc = NULL;
	xmlNodePtr xml_root = NULL;
	xmlNsPtr xml_ns = NULL;
	xmlXPathContextPtr xpath_ctx;
	xmlXPathObjectPtr xpath_obj;
	xmlNodeSetPtr nodes;
	PCSCHEMA *s;
	const char *xml_ptr = xml_str;

	/* Roll forward to start of XML string */
	while( (*xml_ptr != '\0') && (*xml_ptr != '<') )
	{
		xml_ptr++;
	}

	size_t xml_size = strlen(xml_ptr);
	static xmlChar *xpath_str = "/pc:PointCloudSchema/pc:dimension";
	static xmlChar *xpath_metadata_str = "/pc:PointCloudSchema/pc:metadata/Metadata";


	/* Parse XML doc */
	*schema = NULL;
	xmlInitParser();
	xml_doc = xmlReadMemory(xml_ptr, xml_size, NULL, NULL, 0);
	if ( ! xml_doc )
	{
		xmlCleanupParser();
		pcwarn("unable to parse schema XML");
		return PC_FAILURE;
	}

	/* Capture the namespace */
	xml_root = xmlDocGetRootElement(xml_doc);
	if ( xml_root->ns )
		xml_ns = xml_root->ns;

	/* Create xpath evaluation context */
	xpath_ctx = xmlXPathNewContext(xml_doc);
	if( ! xpath_ctx )
	{
		xmlFreeDoc(xml_doc);
		xmlCleanupParser();
		pcwarn("unable to create new XPath context to read schema XML");
		return PC_FAILURE;
	}

	/* Register the root namespace if there is one */
	if ( xml_ns )
		xmlXPathRegisterNs(xpath_ctx, "pc", xml_ns->href);

	/* Evaluate xpath expression */
	xpath_obj = xmlXPathEvalExpression(xpath_str, xpath_ctx);
	if( ! xpath_obj )
	{
	    xmlXPathFreeContext(xpath_ctx);
		xmlFreeDoc(xml_doc);
		xmlCleanupParser();
		pcwarn("unable to evaluate xpath expression \"%s\" against schema XML", xpath_str);
		return PC_FAILURE;
	}

	/* Iterate on the dimensions we found */
	if ( nodes = xpath_obj->nodesetval )
	{
		int ndims = nodes->nodeNr;
		int i;
		s = pc_schema_new(ndims);
		*schema = s;

		for ( i = 0; i < ndims; i++ )
		{
			/* This is a "dimension" */
			if( nodes->nodeTab[i]->type == XML_ELEMENT_NODE )
			{
				xmlNodePtr cur = nodes->nodeTab[i];
				xmlNodePtr child;
				PCDIMENSION *d = pc_dimension_new();
				char xydim = 0;

				/* These are the values of the dimension */
				for ( child = cur->children; child; child = child->next )
				{
					if( child->type == XML_ELEMENT_NODE )
					{
						if ( strcmp(child->name, "name") == 0 )
						{
							if ( strcasecmp(child->children->content, "X") == 0 ||
							     strcasecmp(child->children->content, "Longitude") == 0 ||
							     strcasecmp(child->children->content, "Lon") == 0 )
							{
								xydim = 'x';
							}
							if ( strcasecmp(child->children->content, "Y") == 0 ||
							     strcasecmp(child->children->content, "Latitude") == 0 ||
							     strcasecmp(child->children->content, "Lat") == 0 )
							{
								xydim = 'y';
							}
							d->name = pcstrdup(child->children->content);
						}
						else if ( strcmp(child->name, "description") == 0 )
							d->description = pcstrdup(child->children->content);
						else if ( strcmp(child->name, "size") == 0 )
							d->size = atoi(child->children->content);
						else if ( strcmp(child->name, "active") == 0 )
							d->active = atoi(child->children->content);
						else if ( strcmp(child->name, "position") == 0 )
							d->position = atoi(child->children->content) - 1;
						else if ( strcmp(child->name, "interpretation") == 0 )
							d->interpretation = pc_interpretation_number(child->children->content);
						else if ( strcmp(child->name, "scale") == 0 )
							d->scale = atof(child->children->content);
						else if ( strcmp(child->name, "offset") == 0 )
							d->offset = atof(child->children->content);
						else if ( strcmp(child->name, "uuid") == 0 )
							/* Ignore this tag for now */ 1;
						else if ( strcmp(child->name, "parent_uuid") == 0 )
							/* Ignore this tag for now */ 1;
						else
							pcinfo("unhandled schema type element \"%s\" encountered", child->name);
					}
				}

				/* Convert interprestation to size */
				d->size = pc_interpretation_size(d->interpretation);

				/* Store the dimension in the schema */
				if ( d->position >= 0 && d->position < ndims )
				{
					if ( s->dims[d->position] )
					{
						xmlXPathFreeObject(xpath_obj);
					    xmlXPathFreeContext(xpath_ctx);
						xmlFreeDoc(xml_doc);
						xmlCleanupParser();
						pc_schema_free(s);
						pcwarn("schema dimension at position \"%d\" is declared twice", d->position + 1, ndims);
						return PC_FAILURE;
					}
					if ( xydim == 'x' ) { s->x_position = d->position; }
					if ( xydim == 'y' ) { s->y_position = d->position; }
                    pc_schema_set_dimension(s, d);
				}
				else
				{
					xmlXPathFreeObject(xpath_obj);
				    xmlXPathFreeContext(xpath_ctx);
					xmlFreeDoc(xml_doc);
					xmlCleanupParser();
					pc_schema_free(s);
					pcwarn("schema dimension states position \"%d\", but number of XML dimensions is \"%d\"", d->position + 1, ndims);
					return PC_FAILURE;
				}
			}
		}

		/* Complete the byte offsets of dimensions from the ordered sizes */
		pc_schema_calculate_byteoffsets(s);
		/* Check X/Y positions */
		pc_schema_check_xy(s);
	}

	xmlXPathFreeObject(xpath_obj);

	/* SEARCH FOR METADATA ENTRIES */
	xpath_obj = xmlXPathEvalExpression(xpath_metadata_str, xpath_ctx);
	if( ! xpath_obj )
	{
	    xmlXPathFreeContext(xpath_ctx);
		xmlFreeDoc(xml_doc);
		xmlCleanupParser();
		pcwarn("unable to evaluate xpath expression \"%s\" against schema XML", xpath_metadata_str);
		return PC_FAILURE;
	}

	/* Iterate on the <Metadata> we find */
	if ( nodes = xpath_obj->nodesetval )
	{
		int i;

		for ( i = 0; i < nodes->nodeNr; i++ )
		{
            char *metadata_name = "";
            char *metadata_value = "";
		    /* Read the metadata name and value from the node */
		    /* <Metadata name="somename">somevalue</Metadata> */
		    xmlNodePtr cur = nodes->nodeTab[i];
            if( cur->type == XML_ELEMENT_NODE && strcmp(cur->name, "Metadata") == 0 )
            {
                metadata_name = xmlGetProp(cur, "name");
                metadata_value = xml_node_get_content(cur);
            }

            /* Store the compression type on the schema */
            if ( strcmp(metadata_name, "compression") == 0 )
            {
                int compression = pc_compression_number(metadata_value);
                if ( compression >= 0 )
                {
                    s->compression = compression;
                }
            }
            xmlFree(metadata_name);
        }
	}

	xmlXPathFreeObject(xpath_obj);

    xmlXPathFreeContext(xpath_ctx);
	xmlFreeDoc(xml_doc);
	xmlCleanupParser();

	return PC_SUCCESS;
}
Exemplo n.º 26
0
void
te_update_diff(const char *event, xmlNode * msg)
{
    int rc = -1;
    const char *op = NULL;

    xmlNode *diff = NULL;
    xmlXPathObject *xpathObj = NULL;

    int diff_add_updates = 0;
    int diff_add_epoch = 0;
    int diff_add_admin_epoch = 0;

    int diff_del_updates = 0;
    int diff_del_epoch = 0;
    int diff_del_admin_epoch = 0;

    CRM_CHECK(msg != NULL, return);
    crm_element_value_int(msg, F_CIB_RC, &rc);

    if (transition_graph == NULL) {
        crm_trace("No graph");
        return;

    } else if (rc < pcmk_ok) {
        crm_trace("Filter rc=%d (%s)", rc, pcmk_strerror(rc));
        return;

    } else if (transition_graph->complete == TRUE
               && fsa_state != S_IDLE
               && fsa_state != S_TRANSITION_ENGINE && fsa_state != S_POLICY_ENGINE) {
        crm_trace("Filter state=%s, complete=%d", fsa_state2string(fsa_state),
                    transition_graph->complete);
        return;
    }

    op = crm_element_value(msg, F_CIB_OPERATION);
    diff = get_message_xml(msg, F_CIB_UPDATE_RESULT);

    cib_diff_version_details(diff,
                             &diff_add_admin_epoch, &diff_add_epoch, &diff_add_updates,
                             &diff_del_admin_epoch, &diff_del_epoch, &diff_del_updates);

    crm_debug("Processing diff (%s): %d.%d.%d -> %d.%d.%d (%s)", op,
              diff_del_admin_epoch, diff_del_epoch, diff_del_updates,
              diff_add_admin_epoch, diff_add_epoch, diff_add_updates, fsa_state2string(fsa_state));
    log_cib_diff(LOG_DEBUG_2, diff, op);

    if (cib_config_changed(NULL, NULL, &diff)) {
        abort_transition(INFINITY, tg_restart, "Non-status change", diff);
        goto bail;              /* configuration changed */
    }

    /* Tickets Attributes - Added/Updated */
    xpathObj =
        xpath_search(diff,
                     "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_ADDED "//" XML_CIB_TAG_TICKETS);
    if (xpathObj && xpathObj->nodesetval->nodeNr > 0) {
        xmlNode *aborted = getXpathResult(xpathObj, 0);

        abort_transition(INFINITY, tg_restart, "Ticket attribute: update", aborted);
        goto bail;

    } else if (xpathObj) {
        xmlXPathFreeObject(xpathObj);
    }

    /* Tickets Attributes - Removed */
    xpathObj =
        xpath_search(diff,
                     "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_REMOVED "//" XML_CIB_TAG_TICKETS);
    if (xpathObj && xpathObj->nodesetval->nodeNr > 0) {
        xmlNode *aborted = getXpathResult(xpathObj, 0);

        abort_transition(INFINITY, tg_restart, "Ticket attribute: removal", aborted);
        goto bail;

    } else if (xpathObj) {
        xmlXPathFreeObject(xpathObj);
    }

    /* Transient Attributes - Added/Updated */
    xpathObj =
        xpath_search(diff,
                     "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_ADDED "//"
                     XML_TAG_TRANSIENT_NODEATTRS "//" XML_CIB_TAG_NVPAIR);
    if (xpathObj && xpathObj->nodesetval->nodeNr > 0) {
        int lpc;

        for (lpc = 0; lpc < xpathObj->nodesetval->nodeNr; lpc++) {
            xmlNode *attr = getXpathResult(xpathObj, lpc);
            const char *name = crm_element_value(attr, XML_NVPAIR_ATTR_NAME);
            const char *value = NULL;

            if (safe_str_eq(CRM_OP_PROBED, name)) {
                value = crm_element_value(attr, XML_NVPAIR_ATTR_VALUE);
            }

            if (crm_is_true(value) == FALSE) {
                abort_transition(INFINITY, tg_restart, "Transient attribute: update", attr);
                crm_log_xml_trace(attr, "Abort");
                goto bail;
            }
        }

    } else if (xpathObj) {
        xmlXPathFreeObject(xpathObj);
    }

    /* Transient Attributes - Removed */
    xpathObj =
        xpath_search(diff,
                     "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_REMOVED "//"
                     XML_TAG_TRANSIENT_NODEATTRS);
    if (xpathObj && xpathObj->nodesetval->nodeNr > 0) {
        xmlNode *aborted = getXpathResult(xpathObj, 0);

        abort_transition(INFINITY, tg_restart, "Transient attribute: removal", aborted);
        goto bail;

    } else if (xpathObj) {
        xmlXPathFreeObject(xpathObj);
    }

    /* Check for node state updates... possibly from a shutdown we requested */
    xpathObj =
        xpath_search(diff, "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_ADDED "//" XML_CIB_TAG_STATE);
    if (xpathObj) {
        int lpc = 0, max = xpathObj->nodesetval->nodeNr;

        for (lpc = 0; lpc < max; lpc++) {
            xmlNode *node = getXpathResult(xpathObj, lpc);
            const char *event_node = crm_element_value(node, XML_ATTR_ID);
            const char *event_uname = crm_element_value(node, XML_ATTR_UNAME);
            const char *is_peer = crm_element_value(node, XML_NODE_IS_PEER);

            /* Don't check the value of XML_NODE_IN_CLUSTER, only pacemaker may have been shut down */
            if (safe_str_eq(is_peer, XML_BOOLEAN_NO)) {
                /* Pacemaker is now stopped/gone
                 * Was it a shutdown or fencing operation?
                 */
                crm_action_t *shutdown = match_down_event(0, event_node, NULL);

                if (shutdown != NULL) {
                    const char *task = crm_element_value(shutdown->xml, XML_LRM_ATTR_TASK);

                    if (safe_str_eq(task, CRM_OP_FENCE)) {
                        crm_trace("Waiting for stonithd to report the fencing of %s is complete", event_uname); /* via tengine_stonith_callback() */

                    } else {
                        crm_debug("%s of %s (op %d) is complete", task, event_uname, shutdown->id);
                        /* match->confirmed = TRUE; */
                        stop_te_timer(shutdown->timer);
                        erase_node_from_join(event_uname);
                        update_graph(transition_graph, shutdown);
                        trigger_graph();
                    }

                } else {
                    crm_info("Stonith/shutdown of %s not matched", event_node);
                    abort_transition(INFINITY, tg_restart, "Node failure", node);
                }
                fail_incompletable_actions(transition_graph, event_node);
            }
        }
        xmlXPathFreeObject(xpathObj);
    }

    /*
     * Check for and fast-track the processing of LRM refreshes
     * In large clusters this can result in _huge_ speedups
     *
     * Unfortunately we can only do so when there are no pending actions
     * Otherwise we could miss updates we're waiting for and stall 
     *
     */
    xpathObj = NULL;
    if (transition_graph->pending == 0) {
        xpathObj =
            xpath_search(diff,
                         "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_ADDED "//"
                         XML_LRM_TAG_RESOURCE);
    }

    if (xpathObj) {
        int updates = xpathObj->nodesetval->nodeNr;

        if (updates > 1) {
            /* Updates by, or in response to, TE actions will never contain updates
             * for more than one resource at a time
             */
            crm_debug("Detected LRM refresh - %d resources updated: Skipping all resource events",
                     updates);
            crm_log_xml_trace(diff, "lrm-refresh");
            abort_transition(INFINITY, tg_restart, "LRM Refresh", NULL);
            goto bail;
        }
        xmlXPathFreeObject(xpathObj);
    }

    /* Process operation updates */
    xpathObj =
        xpath_search(diff,
                     "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_ADDED "//" XML_LRM_TAG_RSC_OP);
    if (xpathObj) {
        process_resource_updates(xpathObj);
        xmlXPathFreeObject(xpathObj);
    }

    /* Detect deleted (as opposed to replaced or added) actions - eg. crm_resource -C */
    xpathObj = xpath_search(diff, "//" XML_TAG_DIFF_REMOVED "//" XML_LRM_TAG_RSC_OP);
    if (xpathObj) {
        int lpc = 0, max = xpathObj->nodesetval->nodeNr;

        for (lpc = 0; lpc < max; lpc++) {
            int max = 0;
            const char *op_id = NULL;
            char *rsc_op_xpath = NULL;
            xmlXPathObject *op_match = NULL;
            xmlNode *match = getXpathResult(xpathObj, lpc);

            CRM_CHECK(match != NULL, continue);

            op_id = ID(match);

            max = strlen(rsc_op_template) + strlen(op_id) + 1;
            rsc_op_xpath = calloc(1, max);
            snprintf(rsc_op_xpath, max, rsc_op_template, op_id);

            op_match = xpath_search(diff, rsc_op_xpath);
            if (op_match == NULL || op_match->nodesetval->nodeNr == 0) {
                /* Prevent false positives by matching cancelations too */
                const char *node = get_node_id(match);
                crm_action_t *cancelled = get_cancel_action(op_id, node);

                if (cancelled == NULL) {
                    crm_debug("No match for deleted action %s (%s on %s)", rsc_op_xpath, op_id,
                              node);
                    abort_transition(INFINITY, tg_restart, "Resource op removal", match);
                    if (op_match) {
                        xmlXPathFreeObject(op_match);
                    }
                    free(rsc_op_xpath);
                    goto bail;

                } else {
                    crm_debug("Deleted lrm_rsc_op %s on %s was for graph event %d",
                              op_id, node, cancelled->id);
                }
            }

            if (op_match) {
                xmlXPathFreeObject(op_match);
            }
            free(rsc_op_xpath);
        }
    }

  bail:
    if (xpathObj) {
        xmlXPathFreeObject(xpathObj);
    }
}
Exemplo n.º 27
0
static int cx_handle_single_value_xpath(xmlXPathContextPtr xpath_ctx, /* {{{ */
                                        cx_xpath_t *xpath, const data_set_t *ds,
                                        value_list_t *vl, int index) {
  xmlXPathObjectPtr values_node_obj;
  xmlNodeSetPtr values_node;
  int tmp_size;
  char *node_value;

  values_node_obj =
      cx_evaluate_xpath(xpath_ctx, BAD_CAST xpath->values[index].path);
  if (values_node_obj == NULL)
    return -1; /* Error already logged. */

  values_node = values_node_obj->nodesetval;
  tmp_size = (values_node) ? values_node->nodeNr : 0;

  if (tmp_size == 0) {
    WARNING("curl_xml plugin: "
            "relative xpath expression \"%s\" doesn't match any of the nodes. "
            "Skipping...",
            xpath->values[index].path);
    xmlXPathFreeObject(values_node_obj);
    return -1;
  }

  if (tmp_size > 1) {
    WARNING("curl_xml plugin: "
            "relative xpath expression \"%s\" is expected to return "
            "only one node. Skipping...",
            xpath->values[index].path);
    xmlXPathFreeObject(values_node_obj);
    return -1;
  }

  /* ignoring the element if other than textnode/attribute*/
  if (cx_if_not_text_node(values_node->nodeTab[0])) {
    WARNING("curl_xml plugin: "
            "relative xpath expression \"%s\" is expected to return "
            "only text/attribute node which is not the case. Skipping...",
            xpath->values[index].path);
    xmlXPathFreeObject(values_node_obj);
    return -1;
  }

  node_value = (char *)xmlNodeGetContent(values_node->nodeTab[0]);
  switch (ds->ds[index].type) {
  case DS_TYPE_COUNTER:
    vl->values[index].counter =
        (counter_t)strtoull(node_value,
                            /* endptr = */ NULL, /* base = */ 0);
    break;
  case DS_TYPE_DERIVE:
    vl->values[index].derive =
        (derive_t)strtoll(node_value,
                          /* endptr = */ NULL, /* base = */ 0);
    break;
  case DS_TYPE_ABSOLUTE:
    vl->values[index].absolute =
        (absolute_t)strtoull(node_value,
                             /* endptr = */ NULL, /* base = */ 0);
    break;
  case DS_TYPE_GAUGE:
    vl->values[index].gauge = (gauge_t)strtod(node_value,
                                              /* endptr = */ NULL);
  }

  /* free up object */
  xmlXPathFreeObject(values_node_obj);
  sfree(node_value);

  /* We have reached here which means that
   * we have got something to work */
  return 0;
} /* }}} int cx_handle_single_value_xpath */
Exemplo n.º 28
0
END_TEST



START_TEST (test_get_entries)
{
	xmlXPathObject *xpath_obj = NULL;
	xmlDoc *doc = NULL;
	xmlNodeSet *nodes;
	struct gcal_event known_value;
	struct gcal_event extracted;
	int res;

	gcal_init_event(&known_value);
	gcal_init_event(&extracted);

	res = build_doc_tree(&doc, xml_data);
	fail_if(res == -1, "failed to build document tree!");

	xpath_obj = atom_get_entries(doc);
	fail_if(xpath_obj == NULL, "failed to get entry node list!");

	nodes = xpath_obj->nodesetval;
	fail_if(nodes->nodeNr != 4, "should return 4 entries!");

	res = atom_extract_data(nodes->nodeTab[0], &extracted);
	fail_if(res == -1, "failed to extract data from node!");

	known_value.common.title = "an event with location";
	known_value.common.id  = "http://www.google.com/calendar/feeds/gcal4tester%40gmail.com/private/full/saq81ktu4iqv7r20b8ctv70q7s";
	known_value.common.edit_uri  = "http://www.google.com/calendar/feeds/gcal4tester%40gmail.com/private/full/saq81ktu4iqv7r20b8ctv70q7s/63342246051";
	known_value.content  = "I should be there";
	/* The event is not recurrent: for empty fields, I use a empty string */
	known_value.dt_recurrent  = "";
	known_value.dt_start  = "2008-03-26T18:00:00.000-05:00";
	known_value.dt_end = "2008-03-26T19:00:00.000-05:00";
	known_value.where = "my house";
	known_value.status = "http://schemas.google.com/g/2005#event.confirmed";
	known_value.common.updated = "2008-03-26T20:20:51.000Z";

	fail_if(strcmp(known_value.common.title, extracted.common.title),
		"failed field extraction");
	fail_if(strcmp(known_value.common.id, extracted.common.id),
		"failed field extraction");
	fail_if(strcmp(known_value.common.edit_uri, extracted.common.edit_uri),
		"failed field extraction");
	fail_if(strcmp(known_value.content, extracted.content),
		"failed field extraction");
	fail_if(strcmp(known_value.dt_recurrent, extracted.dt_recurrent),
		"failed field extraction");
	fail_if(strcmp(known_value.dt_start, extracted.dt_start),
		"failed field extraction");
	fail_if(strcmp(known_value.dt_end, extracted.dt_end),
		"failed field extraction");
	fail_if(strcmp(known_value.where, extracted.where),
		"failed field extraction");
	fail_if(strcmp(known_value.status, extracted.status),
		"failed field extraction");
	fail_if(strcmp(known_value.common.updated, extracted.common.updated),
		"failed field extraction");

	if (xpath_obj)
		xmlXPathFreeObject(xpath_obj);

	gcal_destroy_entry(&extracted);
	clean_doc_tree(&doc);
}
Exemplo n.º 29
0
static int cx_handle_base_xpath(char const *plugin_instance, /* {{{ */
                                char const *host, xmlXPathContextPtr xpath_ctx,
                                const data_set_t *ds, char *base_xpath,
                                cx_xpath_t *xpath) {
  int total_nodes;

  xmlXPathObjectPtr base_node_obj = NULL;
  xmlNodeSetPtr base_nodes = NULL;

  value_list_t vl = VALUE_LIST_INIT;

  base_node_obj = cx_evaluate_xpath(xpath_ctx, BAD_CAST base_xpath);
  if (base_node_obj == NULL)
    return -1; /* error is logged already */

  base_nodes = base_node_obj->nodesetval;
  total_nodes = (base_nodes) ? base_nodes->nodeNr : 0;

  if (total_nodes == 0) {
    ERROR("curl_xml plugin: "
          "xpath expression \"%s\" doesn't match any of the nodes. "
          "Skipping the xpath block...",
          base_xpath);
    xmlXPathFreeObject(base_node_obj);
    return -1;
  }

  /* If base_xpath returned multiple results, then */
  /* Instance in the xpath block is required */
  if (total_nodes > 1 && xpath->instance == NULL) {
    ERROR("curl_xml plugin: "
          "InstanceFrom is must in xpath block since the base xpath expression "
          "\"%s\" "
          "returned multiple results. Skipping the xpath block...",
          base_xpath);
    return -1;
  }

  /* set the values for the value_list */
  vl.values_len = ds->ds_num;
  sstrncpy(vl.type, xpath->type, sizeof(vl.type));
  sstrncpy(vl.plugin, "curl_xml", sizeof(vl.plugin));
  sstrncpy(vl.host, host, sizeof(vl.host));
  if (plugin_instance != NULL)
    sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));

  for (int i = 0; i < total_nodes; i++) {
    int status;

    xpath_ctx->node = base_nodes->nodeTab[i];

    status = cx_handle_instance_xpath(xpath_ctx, xpath, &vl,
                                      /* is_table = */ (total_nodes > 1));
    if (status != 0)
      continue; /* An error has already been reported. */

    status = cx_handle_all_value_xpaths(xpath_ctx, xpath, ds, &vl);
    if (status != 0)
      continue; /* An error has been logged. */
  }             /* for (i = 0; i < total_nodes; i++) */

  /* free up the allocated memory */
  xmlXPathFreeObject(base_node_obj);

  return 0;
} /* }}} cx_handle_base_xpath */
Exemplo n.º 30
0
static gboolean
fetch_tweets(gpointer GOL_UNUSED_ARG(data)) {
  if (!enable) return FALSE;

  CURL* curl = NULL;
  CURLcode res = CURLE_OK;
  long http_status = 0;

  MEMFILE* mbody = NULL;
  char* body = NULL;

  xmlDocPtr doc = NULL;
  xmlNodeSetPtr nodes = NULL;
  xmlXPathContextPtr ctx = NULL;
  xmlXPathObjectPtr path = NULL;

  mbody = memfopen();
  curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  curl_easy_setopt(curl, CURLOPT_URL, "https://api.twitter.com/1/statuses/public_timeline.xml");
  curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, REQUEST_TIMEOUT);
  curl_easy_setopt(curl, CURLOPT_TIMEOUT, REQUEST_TIMEOUT);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, memfwrite);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, mbody);
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  res = curl_easy_perform(curl);
  if (res == CURLE_OK)
    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &http_status);
  curl_easy_cleanup(curl);

  body = memfstrdup(mbody);
  memfclose(mbody);

  if (res != CURLE_OK || http_status != 200) goto leave;

  doc = body ? xmlParseDoc((xmlChar*) body) : NULL;
  if (!doc) goto leave;
  ctx = xmlXPathNewContext(doc);
  if (!ctx) goto leave;
  path = xmlXPathEvalExpression((xmlChar*)"/statuses/status", ctx);
  if (!path || xmlXPathNodeSetIsEmpty(path->nodesetval)) goto leave;
  nodes = path->nodesetval;
  const size_t length = xmlXPathNodeSetGetLength(nodes);
  gchar* first_id = NULL;
  for (size_t n = 0; n < length; n++) {
    char* id = NULL;
    char* user_id = NULL;
    char* icon = NULL;
    char* user_name = NULL;
    char* text = NULL;

    xmlNodePtr status = nodes->nodeTab[n];
    if (status->type != XML_ATTRIBUTE_NODE && status->type != XML_ELEMENT_NODE && status->type != XML_CDATA_SECTION_NODE) continue;
    status = status->children;
    while(status) {
      if (!strcmp("id", (char*) status->name)) id = (char*) status->children->content;
      if (!strcmp("text", (char*) status->name)) {
        if (status->children) text = (char*) status->children->content;
      }
      /* user nodes */
      if (!strcmp("user", (char*) status->name)) {
        xmlNodePtr user = status->children;
        while(user) {
          if (!strcmp("id", (char*) user->name)) user_id = XML_CONTENT(user);
          if (!strcmp("screen_name", (char*) user->name)) user_name = XML_CONTENT(user);
          if (!strcmp("profile_image_url", (char*) user->name)) {
            icon = (char*) g_strchug(g_strchomp((gchar*) XML_CONTENT(user)));
          }
          user = user->next;
        }
      }
      status = status->next;
    }
    if (!first_id) first_id = id;
    if (id && last_id && !strcmp(id, last_id)) break;

    if (text && user_id) {
      NOTIFICATION_INFO* ni = g_new0(NOTIFICATION_INFO, 1);
      ni->title = g_strdup(user_name);
      ni->text = g_strdup(text);
      ni->icon = g_strdup(icon);
      g_timeout_add(1000 * (n+1), delay_show, ni);
    }
  }
  if (last_id) g_free(last_id);
  if (first_id) last_id = g_strdup(first_id);

leave:
  free(body);
  if (path) xmlXPathFreeObject(path);
  if (ctx) xmlXPathFreeContext(ctx);
  if (doc) xmlFreeDoc(doc);

  g_timeout_add(1000 * length, fetch_tweets, NULL);
  return FALSE;
}