Beispiel #1
0
template <typename Traits> inline shared_ptr<typename detector_impl<Traits>::definition_type>
detector_impl<Traits>::parse_complex_definition(char const *name, xmlNodePtr node) const {

	typedef complex_definition<Traits> complex_type;
	shared_ptr<complex_type> parent(new complex_type(name));
	
	xml_elems elems(node, "pattern");
	for (xml_elems::const_iterator i = elems.begin(), end = elems.end(); i != end; ++i) {
		if (disabled(*i)) {
			continue;
		}
		char const *value = xml_attr_text(*i, "value"), *type = xml_attr_text(*i, "type");
		if (strncasecmp(type, "string", sizeof("string")) == 0) {
			parent->add(shared_ptr<definition_type>(new string_definition<Traits>(name, xml_node_text(*i), value)));
		}
		else if (strncasecmp(type, "regex", sizeof("regex")) == 0) {
			parent->add(shared_ptr<definition_type>(new regex_definition<Traits>(name, xml_node_text(*i), value)));
		}
		else {
			resource<xmlChar*, xml_string_traits> path(xmlGetNodePath(node));
			throw error("unknown pattern type %s in [%s]", type, (char const*) path.get());
		}
	}
	return parent->has_only_one() ? parent->release_child() : parent.template cast<definition_type>();
}
Beispiel #2
0
static void
debug_report_signature_error(xmlNode *node, lasso_error_t result) {
    xmlChar *path;

    path = xmlGetNodePath(node);
    debug("Could not check signature whose xpath is '%s': %s", path, lasso_strerror(result));
    lasso_release_xml_string(path);
}
Beispiel #3
0
string Node::Path() const
{
    xmlChar * path = xmlGetNodePath(_xml);
    if ( path == nullptr )
        return string();
    string r(path);
    xmlFree(path);
    return r;
}
gchar *
xml_tree_model_get_xpath_from_position (xmlTreeModel *model,
										gint position)
{
	xmlNodePtr node;
	node = xml_tree_model_get_node_from_position(model, position);
	g_return_val_if_fail(node != NULL, NULL);
	return (gchar *)xmlGetNodePath(node);
}
Beispiel #5
0
QString CSpmXml::GetPath(xmlNodePtr pNode)
{
	QString strRes;

	pNode = GetNode(pNode);
	if (0 == pNode)
		return strRes;

	return QString::fromUtf8((char *)xmlGetNodePath(pNode));
}
Beispiel #6
0
static void
nc_attr_show(noit_console_closure_t ncct, const char *name, xmlNodePtr cnode,
             xmlNodePtr anode, const char *value) {
  const char *cpath, *apath;
  cpath = cnode ? (char *)xmlGetNodePath(cnode) : "";
  apath = anode ? (char *)xmlGetNodePath(anode) : "";
  nc_printf(ncct, " %s: %s", name, value ? value : "[undef]");
  if(value && cpath && apath) {
    int clen = strlen(cpath);
    int plen = strlen("/noit/checks/");
    if(!strncmp(cpath, apath, clen) && apath[clen] == '/') {
      /* we have a match, which means it isn't inherited */
    }
    else {
      nc_printf(ncct, " [inherited from %s]",
                strlen(apath) > plen ? apath + plen : apath);
    }
  }
  nc_write(ncct, "\n", 1);
}
/*
 * call-seq:
 *  path
 *
 * Returns the path associated with this Node
 */
static VALUE path(VALUE self)
{
  xmlNodePtr node;
  xmlChar *path ;
  VALUE rval ;
  Data_Get_Struct(self, xmlNode, node);
  
  path = xmlGetNodePath(node);
  rval = rb_str_new2((char *)path);
  xmlFree(path);
  return rval ;
}
Beispiel #8
0
/*
 * call-seq:
 *    node.path -> path
 *
 * Obtain this node's path.
 */
static VALUE rxml_node_path(VALUE self)
{
  xmlNodePtr xnode;
  xmlChar *path;

  Data_Get_Struct(self, xmlNode, xnode);
  path = xmlGetNodePath(xnode);

  if (path == NULL)
    return (Qnil);
  else
    return (rxml_str_new2((const char*) path, xnode->doc ? xnode->doc->encoding : NULL));
}
Beispiel #9
0
/*
 * call-seq:
 *    node.path -> path
 *
 * Obtain this node's path.
 */
static VALUE rxml_node_path(VALUE self)
{
  xmlNodePtr xnode;
  xmlChar *path;

  xnode = rxml_get_xnode(self);
  path = xmlGetNodePath(xnode);

  if (path == NULL)
    return (Qnil);
  else
    return (rxml_new_cstr((const char*) path, NULL));
}
Beispiel #10
0
  //------------------------------------------------------------------------------    
  std::string Node::get_path() const
  {
    xmlChar* const path = xmlGetNodePath(cobj);
    if (path == NULL)
    {
      // WTF: How is this suposed to happen?
      throw exception("Node::get_path(): failed to allocated path");
    }

    std::string value(reinterpret_cast<const char*>(path));
    xmlFree(path);
    return value;
  }
Beispiel #11
0
template <typename Traits> inline shared_ptr<typename detector_impl<Traits>::definition_type>
detector_impl<Traits>::parse_definition(xmlNodePtr node) const {
	char const *name = xml_attr_text(node, "name"), *value = xml_attr_text(node, "value");
	if (static_cast<char const*>(0) == name) {
		resource<xmlChar*, xml_string_traits> path(xmlGetNodePath(node));
		throw error("definition without name in [%s]", (char const*) path.get());
	}
	else if (static_cast<char const*>(0) == value) {
		return parse_complex_definition(name, node);
	}
	else {
		return shared_ptr<definition_type>(new static_definition<Traits>(name, value));
	}
}
/**
 * xmlSchematronReportSuccess:
 * @ctxt:  the validation context
 * @test: the compiled test
 * @cur: the current node tested
 * @success: boolean value for the result
 *
 * called from the validation engine when an assert or report test have
 * been done.
 */
static void
xmlSchematronReportSuccess(xmlSchematronValidCtxtPtr ctxt, 
		   xmlSchematronTestPtr test, xmlNodePtr cur, int success) {
    if ((ctxt == NULL) || (cur == NULL) || (test == NULL))
        return;
    /* if quiet and not SVRL report only failures */
    if ((ctxt->flags & XML_SCHEMATRON_OUT_QUIET) &&
        ((ctxt->flags & XML_SCHEMATRON_OUT_XML) == 0) &&
	(test->type == XML_SCHEMATRON_REPORT))
        return;
    if (ctxt->flags & XML_SCHEMATRON_OUT_XML) {
        TODO
    } else {
        xmlChar *path;
	char msg[1000];
	long line;
	const xmlChar *report = NULL;

        if (((test->type == XML_SCHEMATRON_REPORT) & (!success)) ||
	    ((test->type == XML_SCHEMATRON_ASSERT) & (success)))
	    return;
	line = xmlGetLineNo(cur);
	path = xmlGetNodePath(cur);
	if (path == NULL)
	    path = (xmlChar *) cur->name;
#if 0
	if ((test->report != NULL) && (test->report[0] != 0))
	    report = test->report;
#endif
	if (test->node != NULL)
            report = xmlSchematronFormatReport(ctxt, test->node, cur);
	if (report == NULL) {
	    if (test->type == XML_SCHEMATRON_ASSERT) {
		snprintf(msg, 999, "%s line %ld: node failed assert\n",
		         (const char *) path, line);
	    } else {
		snprintf(msg, 999, "%s line %ld: node failed report\n",
		         (const char *) path, line);
	    }
	} else {
	    snprintf(msg, 999, "%s line %ld: %s\n", (const char *) path,
		     line, (const char *) report);
	    xmlFree((char *) report);
	}
	xmlSchematronReportOutput(ctxt, cur, &msg[0]);
	if ((path != NULL) && (path != (xmlChar *) cur->name))
	    xmlFree(path);
    }
}
Beispiel #13
0
xmlNodePtr CSpmXml::MoveFirst(const QString& strXPathQuery, xmlNodePtr pParent, int* pnCount)
{
	if (strXPathQuery.isEmpty())
		return 0;

	pParent = GetNode(pParent);
	if (0 == pParent)
		return 0;

	QString strQuery;
	if (strXPathQuery.left(2) != "//") // локальный запрос
	{
		strQuery = (char *)xmlGetNodePath(pParent);
		strQuery += strXPathQuery;
	}
	else
		strQuery = strXPathQuery;

	xmlXPathContextPtr pContext = xmlXPathNewContext(m_pXMLDoc);
	if (0 == pContext)
		return 0;

	xmlXPathObjectPtr pQuery = xmlXPathEvalExpression(BAD_CAST strQuery.toUtf8().data(), pContext);
	xmlXPathFreeContext(pContext);

	if (0 == pQuery)
		return 0;

	if (m_pCurNodeSet)
	{
		xmlXPathFreeNodeSet(m_pCurNodeSet);
		m_pCurNodeSet	= 0;
	}

	m_nCurItem = 0;

	m_pCurNodeSet = pQuery->nodesetval;
	if (0 == m_pCurNodeSet)
		return 0;

	if (pnCount)
		*pnCount = m_pCurNodeSet->nodeNr;

	if (0 == m_pCurNodeSet->nodeNr)
		return 0;

	m_pCurNode = m_pCurNodeSet->nodeTab[m_nCurItem];
	return m_pCurNode;
}
Beispiel #14
0
static char *xml_conf_parse_file(xmlNode *element)
{
	char *ret = 0;

	for ( ; element; element = element->next) {

		if (element->parent && element->type == XML_ELEMENT_NODE && !strcmp((const char *) element->name, "section")) {
			xmlChar *name = xmlGetProp(element, (unsigned char *) "name");

			if (name) {
				char *parent_name = (char *) xmlGetNodePath(element->parent);
				char *full_name;
				int i;
				struct xml_conf_section *section = NULL;

#ifdef XML_CONF_DEBUG
				fprintf(stderr, "got a section: %s/%s\n", parent_name, name);
#endif
				full_name = alloca(strlen(parent_name) + strlen((char *) name) + 1 + 1);
				sprintf(full_name, "%s/%s", parent_name, (char *) name);

				xmlFree(parent_name);
				xmlFree(name);

				for (i = 0; i < xml_conf_sections_used; i++) {
					if (!strcmp(xml_conf_sections[i]->path, full_name)) {
						section = xml_conf_sections[i];
					}
				}

				if (section) { /* found a registered section */
					void *conf = section->conf();
					ret = xml_conf_parse_section(&conf, section, element->children);
					if (ret) break;
				}

			}
		}

		if (element->children) {
			ret = xml_conf_parse_file(element->children);
			if (ret) break;
		}
	}

	return ret;
}
Beispiel #15
0
char* XPathExpressionGetElementPath(TixiDocument* tixiDocument, const char* xPathExpression, int index)
{

  xmlDocPtr doc;
  xmlXPathObjectPtr xpathObject;
  xmlNodeSetPtr nodes = NULL;
  xmlNodePtr cur;
  int size = 0;

  /* Load XML document */
  doc = tixiDocument->docPtr;

  xpathObject = XPathEvaluateExpression(doc, xPathExpression);
  if (xpathObject == NULL) {
    return NULL;
  }

  nodes = xpathObject->nodesetval;

  size = (nodes) ? nodes->nodeNr : 0;
  if (size == 0) {
    printMsg(MESSAGETYPE_ERROR, "Error: XPath Expression '%s' returns 0 nodes.\n", xPathExpression);
    xmlXPathFreeObject(xpathObject);
    return NULL;
  }

  if (size < index) {
    printMsg(MESSAGETYPE_ERROR, "Error: Index number too high, XPath expression only returns %d nodes.\n", size);
    xmlXPathFreeObject(xpathObject);
    return NULL;
  }

  if (index <= 0) {
    printMsg(MESSAGETYPE_ERROR, "Error: Index number less or equal zero.\n");
    xmlXPathFreeObject(xpathObject);
    return NULL;
  }

  cur = nodes->nodeTab[--index];
  xmlXPathFreeObject(xpathObject);

  return (char*) xmlGetNodePath(cur);
}
Beispiel #16
0
static void simpleXpathMakeTag (xmlNode *node,
				const tagXpathMakeTagSpec *spec,
				const kindOption* const kinds,
				void *userData)
{
	tagEntryInfo tag;
	xmlChar* str;
	const kindOption *kind;
	char *path;

	str = xmlNodeGetContent(node);
	if (str == NULL)
		return;

	kind = kinds + spec->kind;

	if (spec->role == ROLE_INDEX_DEFINITION)
		initTagEntry (&tag, (char *)str, kind);
	else if (isXtagEnabled(XTAG_REFERENCE_TAGS))
		initRefTagEntry (&tag, (char *)str,
				 kind,
				 spec->role);
	else
		goto out;


	tag.lineNumber = xmlGetLineNo (node);
	tag.filePosition = getInputFilePositionForLine (tag.lineNumber);

	path = (char *)xmlGetNodePath (node);
	tag.extensionFields.xpath = path;

	if (spec->make)
		spec->make (node, spec, &tag, userData);
	else
		makeTagEntry (&tag);

	if (path)
		xmlFree (path);
out:
	xmlFree (str);
}
Beispiel #17
0
bool CSpmXml::DeleteNodes(const QString& strXPathQuery, xmlNodePtr pParent)
{
	if (strXPathQuery.isEmpty())
		return false;

	pParent = GetNode(pParent);
	if (0 == pParent)
		return false;

	QString strQuery;
	if (strXPathQuery.left(2) != "//") // локальный запрос
	{
		strQuery = (char *)xmlGetNodePath(pParent);
		strQuery += strXPathQuery;
	}
	else
		strQuery = strXPathQuery;

	xmlXPathContextPtr pContext = xmlXPathNewContext(m_pXMLDoc);
	if (0 == pContext)
		return false;

	xmlXPathObjectPtr pQuery = xmlXPathEvalExpression(BAD_CAST strQuery.toUtf8().data(), pContext);
	xmlXPathFreeContext(pContext);
	if (0 == pQuery)
		return false;

	xmlNodeSetPtr pNodeSet = pQuery->nodesetval;
	if ((0 == pNodeSet) || (0 == pNodeSet->nodeNr))
		return false;

	for (int i = 0; i < pNodeSet->nodeNr; i++)
	{
		xmlNodePtr pNode = pNodeSet->nodeTab[i];
		xmlUnlinkNode(pNode);
		SetModified();
	}

	xmlXPathFreeNodeSet(pNodeSet);
	return true;
}
Beispiel #18
0
template <typename Traits> inline shared_ptr<typename detector_impl<Traits>::branch_type>
detector_impl<Traits>::parse_branch(xmlNodePtr node) const {
	
	shared_ptr<branch_type> result(new branch_type());
	for (xmlNodePtr n = xmlFirstElementChild(node); 0 != n; n = xmlNextElementSibling(n)) {
		if (disabled(n)) {
			continue;
		}
		else if (xmlStrncasecmp(n->name, (xmlChar const*) "match", sizeof("match")) == 0) {
			xml_elems elems(n, "pattern");
			for (xml_elems::iterator i = elems.begin(), end = elems.end(); i != end; ++i) {
				if (disabled(*i)) {
					continue;
				}
				char const *type = xml_attr_text(*i, "type");
				if (strncasecmp(type, "string", sizeof("string")) == 0) {
					result->add_match(xml_node_text(*i));
				}
				else if (strncasecmp(type, "regex", sizeof("regex")) == 0) {
					result->add_regex_match(xml_node_text(*i));
				}
				else {
					resource<xmlChar*, xml_string_traits> path(xmlGetNodePath(*i));
					throw error("unknown pattern type %s in [%s]", type, (char const*) path.get());
				}
			}
		}
		else if (xmlStrncasecmp(n->name, (xmlChar const*) "branch", sizeof("branch")) == 0) {
			result->add_child(parse_branch(n));
		}
		else if (xmlStrncasecmp(n->name, (xmlChar const*) "define", sizeof("definition")) == 0) {
			result->add_definition(parse_definition(n));
		}
	}
	return result;
}
Beispiel #19
0
int
cib_process_modify(const char *op, int options, const char *section, xmlNode * req, xmlNode * input,
                   xmlNode * existing_cib, xmlNode ** result_cib, xmlNode ** answer)
{
    xmlNode *obj_root = NULL;

    crm_trace("Processing \"%s\" event", op);

    if (options & cib_xpath) {
        return cib_process_xpath(op, options, section, req, input,
                                 existing_cib, result_cib, answer);
    }

    if (input == NULL) {
        crm_err("Cannot perform modification with no data");
        return -EINVAL;
    }

    obj_root = get_object_root(section, *result_cib);
    if (obj_root == NULL) {
        xmlNode *tmp_section = NULL;
        const char *path = get_object_parent(section);

        if (path == NULL) {
            return -EINVAL;
        }

        tmp_section = create_xml_node(NULL, section);
        cib_process_xpath(CIB_OP_CREATE, 0, path, NULL, tmp_section, NULL, result_cib, answer);
        free_xml(tmp_section);

        obj_root = get_object_root(section, *result_cib);
    }

    CRM_CHECK(obj_root != NULL, return -EINVAL);

    if (update_xml_child(obj_root, input) == FALSE) {
        if (options & cib_can_create) {
            add_node_copy(obj_root, input);
        } else {
            return -ENXIO;
        }
    }

    if(options & cib_mixed_update) {
        int max = 0, lpc;
        xmlXPathObjectPtr xpathObj = xpath_search(*result_cib, "//@__delete__");

        if (xpathObj) {
            max = numXpathResults(xpathObj);
            crm_log_xml_trace(*result_cib, "Mixed result");
        }

        for (lpc = 0; lpc < max; lpc++) {
            xmlNode *match = getXpathResult(xpathObj, lpc);
            xmlChar *match_path = xmlGetNodePath(match);

            crm_debug("Destroying %s", match_path);
            free(match_path);
            free_xml(match);
        }

        freeXpathObject(xpathObj);
    }
    return pcmk_ok;
}
Beispiel #20
0
static int
noit_console_config_show(noit_console_closure_t ncct,
                         int argc, char **argv,
                         noit_console_state_t *state, void *closure) {
  noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
  const char *k;
  int klen;
  void *data;
  int i, cnt, titled = 0, cliplen = 0;
  const char *path = "", *basepath = NULL;
  char xpath[1024];
  noit_conf_t_userdata_t *info = NULL;
  noit_hash_table *config;
  xmlXPathObjectPtr pobj = NULL;
  xmlXPathContextPtr xpath_ctxt = NULL, current_ctxt;
  xmlDocPtr master_config = NULL;
  xmlNodePtr node = NULL;

  noit_conf_xml_xpath(&master_config, &xpath_ctxt);
  if(argc > 1) {
    nc_printf(ncct, "too many arguments\n");
    return -1;
  }

  info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
  if(info && info->path) path = basepath = info->path;
  if(!info && argc == 0) {
    nc_printf(ncct, "argument required when not in configuration mode\n");
    return -1;
  }

  if(argc == 1) path = argv[0];
  if(!basepath) basepath = path;

  /* { / } is a special case */
  if(!strcmp(basepath, "/")) basepath = "";
  if(!strcmp(path, "/")) path = "";

  if(!master_config) {
    nc_printf(ncct, "no config\n");
    return -1;
  }

  /* { / } is the only path that will end with a /
   * in XPath { / / * } means something _entirely different than { / * }
   * Ever notice how it is hard to describe xpath in C comments?
   */
  /* We don't want to show the root node */
  cliplen = strlen("/noit/");

  /* If we are in configuration mode
   * and we are without an argument or the argument is absolute,
   * clip the current path off */
  if(info && (argc == 0 || path[0] != '/')) cliplen += strlen(basepath);
  if(!path[0] || path[0] == '/') /* base only, or absolute path requested */
    snprintf(xpath, sizeof(xpath), "/noit%s/@*", path);
  else
    snprintf(xpath, sizeof(xpath), "/noit%s/%s/@*", basepath, path);

  current_ctxt = xpath_ctxt;
  pobj = xmlXPathEval((xmlChar *)xpath, current_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET) {
    nc_printf(ncct, "no such object\n");
    goto bad;
  }
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  titled = 0;
  for(i=0; i<cnt; i++) {
    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
    if(!strcmp((char *)node->name, "check")) continue;
    if(node->children && node->children == xmlGetLastChild(node) &&
      xmlNodeIsText(node->children)) {
      if(!titled++) nc_printf(ncct, "== Section Settings ==\n");
      nc_printf(ncct, "%s: %s\n", xmlGetNodePath(node) + cliplen,
                xmlXPathCastNodeToString(node->children));
    }
  }
  xmlXPathFreeObject(pobj);

  /* Print out all the config settings */
  if(!path[0] || path[0] == '/') /* base only, or absolute path requested */
    snprintf(xpath, sizeof(xpath), "/noit%s", path);
  else
    snprintf(xpath, sizeof(xpath), "/noit%s/%s", basepath, path);
  pobj = xmlXPathEval((xmlChar *)xpath, current_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET) {
    nc_printf(ncct, "no such object\n");
    goto bad;
  }
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  if(cnt > 0) {
    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
    titled = 0;
    config = noit_conf_get_hash(node, "config");
    while(noit_hash_next(config, &iter, &k, &klen, &data)) {
      if(!titled++) nc_printf(ncct, "== Section [Aggregated] Config ==\n");
      nc_printf(ncct, "config::%s: %s\n", k, (const char *)data);
    }
    noit_hash_destroy(config, free, free);
    free(config);
  }
  xmlXPathFreeObject(pobj);

  /* _shorten string_ turning last { / @ * } to { / * } */
  if(!path[0] || path[0] == '/') /* base only, or absolute path requested */
    snprintf(xpath, sizeof(xpath), "/noit%s/*", path);
  else
    snprintf(xpath, sizeof(xpath), "/noit%s/%s/*", basepath, path);
  pobj = xmlXPathEval((xmlChar *)xpath, current_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET) {
    nc_printf(ncct, "no such object\n");
    goto bad;
  }
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  titled = 0;
  for(i=0; i<cnt; i++) {
    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
    if(!strcmp((char *)node->name, "check")) continue;
    if(!strcmp((char *)node->name, "filterset")) continue;
    if(!strcmp((char *)xmlGetNodePath(node) + cliplen, "config")) continue;
    if(!(node->children && node->children == xmlGetLastChild(node) &&
         xmlNodeIsText(node->children))) {
      if(!titled++) nc_printf(ncct, "== Subsections ==\n");
      nc_printf(ncct, "%s\n", xmlGetNodePath(node) + cliplen);
    }
  }

  titled = 0;
  for(i=0; i<cnt; i++) {
    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
    if(!strcmp((char *)node->name, "filterset")) {
      xmlAttr *attr;
      char *filter_name = NULL;
      for(attr=node->properties; attr; attr = attr->next) {
        if(!strcmp((char *)attr->name, "name"))
          filter_name = (char *)xmlXPathCastNodeToString(attr->children);
      }
      if(filter_name) {
        nc_printf(ncct, "filterset[@name=\"%s\"]\n", filter_name);
        xmlFree(filter_name);
      }
      else nc_printf(ncct, "fitlerset\n");
    }
    else if(!strcmp((char *)node->name, "check")) {
      int busted = 1;
      xmlAttr *attr;
      char *uuid_str = "undefined";

      if(!titled++) nc_printf(ncct, "== Checks ==\n");

      for(attr=node->properties; attr; attr = attr->next) {
        if(!strcmp((char *)attr->name, "uuid"))
          uuid_str = (char *)xmlXPathCastNodeToString(attr->children);
      }
      if(uuid_str) {
        uuid_t checkid;
        nc_printf(ncct, "check[@uuid=\"%s\"] ", uuid_str);
        if(uuid_parse(uuid_str, checkid) == 0) {
          noit_check_t *check;
          check = noit_poller_lookup(checkid);
          if(check) {
            busted = 0;
            nc_printf(ncct, "%s`%s`%s", check->target, check->module, check->name);
          }
        }
      }
      else
        nc_printf(ncct, "%s ", xmlGetNodePath(node) + cliplen);
      if(busted) nc_printf(ncct, "[check not in running system]");
      nc_write(ncct, "\n", 1);
    }
  }
  xmlXPathFreeObject(pobj);
  return 0;
 bad:
  if(pobj) xmlXPathFreeObject(pobj);
  return -1;
}
Beispiel #21
0
static int
noit_console_config_nocheck(noit_console_closure_t ncct,
                            int argc, char **argv,
                            noit_console_state_t *state, void *closure) {
  int i, cnt;
  const char *err = "internal error";
  noit_conf_t_userdata_t *info;
  xmlXPathObjectPtr pobj = NULL;
  xmlXPathContextPtr xpath_ctxt = NULL;
  char xpath[1024];
  uuid_t checkid;

  noit_conf_xml_xpath(NULL, &xpath_ctxt);
  if(argc < 1) {
    nc_printf(ncct, "requires one argument\n");
    return -1;
  }

  info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
  if(noit_console_mkcheck_xpath(xpath, sizeof(xpath), info, argv[0])) {
    nc_printf(ncct, "could not find check '%s'\n", argv[0]);
    return -1;
  }
  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET ||
     xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
    err = "no checks found";
    goto bad;
  }
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  for(i=0; i<cnt; i++) {
    xmlNodePtr node;
    char *uuid_conf;
    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
    uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
    if(!uuid_conf || uuid_parse(uuid_conf, checkid)) {
      nc_printf(ncct, "%s has invalid or missing UUID!\n",
                (char *)xmlGetNodePath(node) + strlen("/noit"));
    }
    else {
      if(argc > 1) {
        int j;
        for(j=1;j<argc;j++)
          xmlUnsetProp(node, (xmlChar *)argv[j]);
      } else {
        nc_printf(ncct, "descheduling %s\n", uuid_conf);
        noit_poller_deschedule(checkid);
        xmlUnlinkNode(node);
      }
      noit_conf_mark_changed();
    }
  }
  if(argc > 1) {
    noit_poller_process_checks(xpath);
    noit_poller_reload(xpath);
  }
  nc_printf(ncct, "rebuilding causal map...\n");
  noit_poller_make_causal_map();
  if(pobj) xmlXPathFreeObject(pobj);
  return 0;
 bad:
  if(pobj) xmlXPathFreeObject(pobj);
  nc_printf(ncct, "%s\n", err);
  return -1;
}
Beispiel #22
0
static int
noit_console_show_check(noit_console_closure_t ncct,
                        int argc, char **argv,
                        noit_console_state_t *state, void *closure) {
  int i, cnt;
  noit_conf_t_userdata_t *info;
  char xpath[1024];
  xmlXPathObjectPtr pobj = NULL;
  xmlXPathContextPtr xpath_ctxt = NULL;

  noit_conf_xml_xpath(NULL, &xpath_ctxt);
  if(argc > 1) {
    nc_printf(ncct, "requires zero or one arguments\n");
    return -1;
  }

  info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
  /* We many not be in conf-t mode -- that's fine */
  if(noit_console_mkcheck_xpath(xpath, sizeof(xpath), info,
                                argc ? argv[0] : NULL)) {
    nc_printf(ncct, "could not find check '%s'\n", argv[0]);
    return -1;
  }

  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET ||
     xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
    nc_printf(ncct, "no checks found\n");
    goto out;
  }
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  if(info && cnt != 1) {
    nc_printf(ncct, "Ambiguous check specified\n");
    goto out;
  }
  for(i=0; i<cnt; i++) {
    noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
    const char *k;
    int klen;
    void *data;
    uuid_t checkid;
    noit_check_t *check;
    noit_hash_table *config;
    xmlNodePtr node, anode, mnode = NULL;
    char *uuid_conf;
    char *module, *value;

    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
    uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
    if(!uuid_conf || uuid_parse(uuid_conf, checkid)) {
      nc_printf(ncct, "%s has invalid or missing UUID!\n",
                (char *)xmlGetNodePath(node) + strlen("/noit"));
      continue;
    }
    nc_printf(ncct, "==== %s ====\n", uuid_conf);

#define MYATTR(a,n,b) _noit_conf_get_string(node, &(n), "@" #a, &(b))
#define INHERIT(a,n,b) \
  _noit_conf_get_string(node, &(n), "ancestor-or-self::node()/@" #a, &(b))
#define SHOW_ATTR(a) do { \
  anode = NULL; \
  value = NULL; \
  INHERIT(a, anode, value); \
  nc_attr_show(ncct, #a, node, anode, value); \
} while(0)

    if(!INHERIT(module, mnode, module)) module = NULL;
    if(MYATTR(name, anode, value))
      nc_printf(ncct, " name: %s\n", value);
    else
      nc_printf(ncct, " name: %s [from module]\n", module ? module : "[undef]");
    nc_attr_show(ncct, "module", node, mnode, module);
    SHOW_ATTR(target);
    SHOW_ATTR(period);
    SHOW_ATTR(timeout);
    SHOW_ATTR(oncheck);
    SHOW_ATTR(filterset);
    SHOW_ATTR(disable);
    /* Print out all the config settings */
    config = noit_conf_get_hash(node, "config");
    while(noit_hash_next(config, &iter, &k, &klen, &data)) {
      nc_printf(ncct, " config::%s: %s\n", k, (const char *)data);
    }
    noit_hash_destroy(config, free, free);
    free(config);

    check = noit_poller_lookup(checkid);
    if(!check) {
      nc_printf(ncct, " ERROR: not in running system\n");
    }
    else {
      int idx = 0;
      nc_printf(ncct, " currently: ");
      if(NOIT_CHECK_RUNNING(check)) nc_printf(ncct, "%srunning", idx++?",":"");
      if(NOIT_CHECK_KILLED(check)) nc_printf(ncct, "%skilled", idx++?",":"");
      if(!NOIT_CHECK_CONFIGURED(check)) nc_printf(ncct, "%sunconfig", idx++?",":"");
      if(NOIT_CHECK_DISABLED(check)) nc_printf(ncct, "%sdisabled", idx++?",":"");
      if(!idx) nc_printf(ncct, "idle");
      nc_write(ncct, "\n", 1);
      if(check->stats.current.whence.tv_sec == 0) {
        nc_printf(ncct, " last run: never\n");
      }
      else {
        stats_t *c = &check->stats.current;
        struct timeval now, diff;
        gettimeofday(&now, NULL);
        sub_timeval(now, c->whence, &diff);
        nc_printf(ncct, " last run: %0.3f seconds ago\n",
                  diff.tv_sec + (diff.tv_usec / 1000000.0));
        nc_printf(ncct, " availability/state: %s/%s\n",
                  noit_check_available_string(c->available),
                  noit_check_state_string(c->state));
        nc_printf(ncct, " status: %s\n", c->status ? c->status : "[[null]]");
        nc_printf(ncct, " metrics:\n");
        memset(&iter, 0, sizeof(iter));
        while(noit_hash_next(&c->metrics, &iter, &k, &klen, &data)) {
          char buff[256];
          noit_boolean filtered;
          noit_stats_snprint_metric(buff, sizeof(buff), (metric_t *)data);
          filtered = !noit_apply_filterset(check->filterset, check, (metric_t *)data);
          nc_printf(ncct, "  %c%s\n", filtered ? '*' : ' ', buff);
        }
      }
    }
  }
 out:
  if(pobj) xmlXPathFreeObject(pobj);
  return 0;
}
Beispiel #23
0
static int
noit_console_watch_check(noit_console_closure_t ncct,
                         int argc, char **argv,
                         noit_console_state_t *state, void *closure) {
  int i, cnt;
  int adding = (int)(vpsized_int)closure;
  int period = 0;
  char xpath[1024];
  xmlXPathObjectPtr pobj = NULL;
  xmlXPathContextPtr xpath_ctxt = NULL;

  noit_conf_xml_xpath(NULL, &xpath_ctxt);
  if(argc < 1 || argc > 2) {
    nc_printf(ncct, "requires one or two arguments\n");
    return -1;
  }
  /* An alternate period */
  if(argc == 2) period = atoi(argv[1]);

  if(noit_console_mkcheck_xpath(xpath, sizeof(xpath), NULL,
                                argc ? argv[0] : NULL)) {
    nc_printf(ncct, "ERROR: could not find check '%s'\n", argv[0]);
    return -1;
  }

  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET ||
     xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
    nc_printf(ncct, "no checks found\n");
    goto out;
  }
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  for(i=0; i<cnt; i++) {
    uuid_t checkid;
    noit_check_t *check;
    xmlNodePtr node;
    char *uuid_conf;

    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
    uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
    if(!uuid_conf || uuid_parse(uuid_conf, checkid)) {
      nc_printf(ncct, "%s has invalid or missing UUID!\n",
                (char *)xmlGetNodePath(node) + strlen("/noit"));
      continue;
    }
    if(period == 0) {
      check = noit_poller_lookup(checkid);
      if(!check) continue;
      if(adding) noit_check_transient_add_feed(check, ncct->feed_path);
      else noit_check_transient_remove_feed(check, ncct->feed_path);
    }
    else {
      if(adding) {
        check = noit_check_watch(checkid, period);
        /* This check must be watched from the console */
        noit_check_transient_add_feed(check, ncct->feed_path);
        /* Note the check */
        noit_check_log_check(check);
        /* kick it off, if it isn't running already */
        if(!NOIT_CHECK_LIVE(check)) noit_check_activate(check);
      }
      else {
        check = noit_check_get_watch(checkid, period);
        if(check) noit_check_transient_remove_feed(check, ncct->feed_path);
      }
    }
  }
 out:
  if(pobj) xmlXPathFreeObject(pobj);
  return 0;
}
Beispiel #24
0
static int
noit_console_check(noit_console_closure_t ncct,
                   int argc, char **argv,
                   noit_console_state_t *state, void *closure) {
  int cnt;
  noit_conf_t_userdata_t *info;
  char xpath[1024], newuuid_str[37];
  char *uuid_conf, *wanted;
  uuid_t checkid;
  xmlXPathContextPtr xpath_ctxt = NULL;
  xmlXPathObjectPtr pobj = NULL;
  xmlNodePtr node = NULL;
  noit_boolean creating_new = noit_false;

  if(closure) {
    char *fake_argv[1] = { ".." };
    noit_console_state_pop(ncct, 0, argv, NULL, NULL);
    noit_console_config_cd(ncct, 1, fake_argv, NULL, NULL);
  }

  noit_conf_xml_xpath(NULL, &xpath_ctxt);
  if(argc < 1) {
    nc_printf(ncct, "requires at least one argument\n");
    return -1;
  }
  if(argc % 2 == 0) {
    nc_printf(ncct, "wrong number of arguments\n");
    return -1;
  } 

  info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
  wanted = strcmp(argv[0], "new") ? argv[0] : NULL;
  if(info && !wanted) {
    /* We are creating a new node */
    uuid_t out;
    creating_new = noit_true;
    if(strncmp(info->path, "/checks/", strlen("/checks/")) &&
       strcmp(info->path, "/checks")) {
      nc_printf(ncct, "New checks must be under /checks/\n");
      return -1;
    }
    if(noit_conf_mkcheck_under(info->path, argc - 1, argv + 1, out)) {
      nc_printf(ncct, "Error creating new check\n");
      return -1;
    }
    newuuid_str[0] = '\0';
    uuid_unparse_lower(out, newuuid_str);
    wanted = newuuid_str;
  }
  /* We many not be in conf-t mode -- that's fine */
  if(noit_console_mkcheck_xpath(xpath, sizeof(xpath), info, wanted)) {
    nc_printf(ncct, "could not find check '%s'\n", wanted);
    return -1;
  }

  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET ||
     xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
    nc_printf(ncct, "no checks found for '%s'\n", wanted);
    goto out;
  }
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  if(info && cnt != 1) {
    nc_printf(ncct, "Ambiguous check specified\n");
    goto out;
  }
  node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
  uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
  if(!uuid_conf || uuid_parse(uuid_conf, checkid)) {
    nc_printf(ncct, "%s has invalid or missing UUID!\n",
              (char *)xmlGetNodePath(node) + strlen("/noit"));
    goto out;
  }
  if(argc > 1 && !creating_new)
    if(noit_config_check_update_attrs(node, argc - 1, argv + 1))
      nc_printf(ncct, "Partially successful, error setting some attributes\n");

  if(info) {
    if(info->path) free(info->path);
    info->path = strdup((char *)xmlGetNodePath(node) + strlen("/noit"));
    uuid_copy(info->current_check, checkid);
    if(argc > 1) refresh_subchecks(ncct, info);
    if(state) {
      noit_console_state_push_state(ncct, state);
      noit_console_state_init(ncct);
    }
    goto out;
  }
 out:
  if(pobj) xmlXPathFreeObject(pobj);
  return 0;
}
Beispiel #25
0
int
cib_process_xpath(const char *op, int options, const char *section, xmlNode * req, xmlNode * input,
                  xmlNode * existing_cib, xmlNode ** result_cib, xmlNode ** answer)
{
    int lpc = 0;
    int max = 0;
    int rc = pcmk_ok;
    gboolean is_query = safe_str_eq(op, CIB_OP_QUERY);

    xmlXPathObjectPtr xpathObj = NULL;

    crm_trace("Processing \"%s\" event", op);

    if (is_query) {
        xpathObj = xpath_search(existing_cib, section);
    } else {
        xpathObj = xpath_search(*result_cib, section);
    }

    max = numXpathResults(xpathObj);

    if (max < 1 && safe_str_eq(op, CIB_OP_DELETE)) {
        crm_debug("%s was already removed", section);

    } else if (max < 1) {
        crm_debug("%s: %s does not exist", op, section);
        rc = -ENXIO;

    } else if (is_query) {
        if (max > 1) {
            *answer = create_xml_node(NULL, "xpath-query");
        }
    }

    if (safe_str_eq(op, CIB_OP_DELETE) && (options & cib_multiple)) {
        dedupXpathResults(xpathObj);
    }

    for (lpc = 0; lpc < max; lpc++) {
        xmlChar *path = NULL;
        xmlNode *match = getXpathResult(xpathObj, lpc);

        if (match == NULL) {
            continue;
        }

        path = xmlGetNodePath(match);
        crm_debug("Processing %s op for %s (%s)", op, section, path);
        free(path);

        if (safe_str_eq(op, CIB_OP_DELETE)) {
            if (match == *result_cib) {
                /* Attempting to delete the whole "/cib" */
                crm_warn("Cannot perform %s for %s: The xpath is addressing the whole /cib", op, section);
                rc = -EINVAL;
                break;
            }

            free_xml(match);
            if ((options & cib_multiple) == 0) {
                break;
            }

        } else if (safe_str_eq(op, CIB_OP_MODIFY)) {
            if (update_xml_child(match, input) == FALSE) {
                rc = -ENXIO;
            } else if ((options & cib_multiple) == 0) {
                break;
            }

        } else if (safe_str_eq(op, CIB_OP_CREATE)) {
            add_node_copy(match, input);
            break;

        } else if (safe_str_eq(op, CIB_OP_QUERY)) {

            if (options & cib_no_children) {
                const char *tag = TYPE(match);
                xmlNode *shallow = create_xml_node(*answer, tag);

                copy_in_properties(shallow, match);

                if (*answer == NULL) {
                    *answer = shallow;
                }

            } else if (options & cib_xpath_address) {

                int path_len = 0;
                char *path = NULL;
                xmlNode *parent = match;

                while (parent && parent->type == XML_ELEMENT_NODE) {
                    int extra = 1;
                    char *new_path = NULL;
                    const char *id = crm_element_value(parent, XML_ATTR_ID);

                    extra += strlen((const char *)parent->name);
                    if (id) {
                        extra += 8;     /* [@id=""] */
                        extra += strlen(id);
                    }

                    path_len += extra;
                    new_path = malloc(path_len + 1);
                    if(new_path == NULL) {
                        break;

                    } else if (id) {
                        snprintf(new_path, path_len + 1, "/%s[@id='%s']%s", parent->name, id,
                                 path ? path : "");
                    } else {
                        snprintf(new_path, path_len + 1, "/%s%s", parent->name, path ? path : "");
                    }
                    free(path);
                    path = new_path;
                    parent = parent->parent;
                }
                crm_trace("Got: %s\n", path);

                if (*answer == NULL) {
                    *answer = create_xml_node(NULL, "xpath-query");
                }
                parent = create_xml_node(*answer, "xpath-query-path");
                crm_xml_add(parent, XML_ATTR_ID, path);
                free(path);

            } else if (*answer) {
                add_node_copy(*answer, match);

            } else {
                *answer = match;
            }

        } else if (safe_str_eq(op, CIB_OP_REPLACE)) {
            xmlNode *parent = match->parent;

            free_xml(match);
            if (input != NULL) {
                add_node_copy(parent, input);
            }

            if ((options & cib_multiple) == 0) {
                break;
            }
        }
    }

    freeXpathObject(xpathObj);
    return rc;
}
Beispiel #26
0
ReturnCode saveExternalFiles(xmlNodePtr aNodePtr, TixiDocument* aTixiDocument)
{
  TixiDocumentHandle handle = aTixiDocument->handle;
  xmlNodePtr cur_node = NULL;
  xmlNodePtr copiedNode = NULL;
  char* externalDataDirectory = NULL;
  char* externalFileName = NULL;
  char* fullExternalFileName = NULL;
  char* externalDataNodePath = NULL;
  char* fullExternalDataNodePath = NULL;
  xmlDocPtr xmlDocument = NULL;

  /* find external data nodes */
  for (cur_node = aNodePtr; cur_node; cur_node = cur_node->next) {

    /* recurse down with the next element */
    saveExternalFiles(cur_node->children, aTixiDocument);

    if( checkExternalNode( cur_node ) != SUCCESS) {
      continue;
    }

    if ( cur_node->type == XML_ELEMENT_NODE ) {
      char* dirResolved = NULL;
      char* includetNodeName = (char*) xmlGetNodePath(cur_node);

      /* collect node information - externalFileName */
      tixiGetTextAttribute(handle, includetNodeName,
                           EXTERNAL_DATA_XML_ATTR_FILENAME, &externalFileName);

      /* collect node information - externalDataDirectory */
      tixiGetTextAttribute(handle, includetNodeName,
                           EXTERNAL_DATA_XML_ATTR_DIRECTORY, &externalDataDirectory);

      /* collect node information - externalDataNodePath */
      tixiGetTextAttribute(handle, includetNodeName,
                           EXTERNAL_DATA_XML_ATTR_NODEPATH, &externalDataNodePath);

      free(includetNodeName);


      /* remove attributes */
      xmlUnsetProp(cur_node, (xmlChar*) EXTERNAL_DATA_XML_ATTR_FILENAME);
      xmlUnsetProp(cur_node, (xmlChar*) EXTERNAL_DATA_XML_ATTR_DIRECTORY);
      xmlUnsetProp(cur_node, (xmlChar*) EXTERNAL_DATA_XML_ATTR_NODEPATH);


      /* create new document */
      xmlDocument = xmlNewDoc((xmlChar*) "1.0");
      if (!xmlDocument) {
        printMsg(MESSAGETYPE_ERROR, "Error in TIXI::saveExternalFiles ==> Could not create new document.\n");
        return FAILED;
      }

      /* deep copy of nodes from external files */
      copiedNode = xmlDocCopyNode(cur_node, xmlDocument, 1);

      xmlDocSetRootElement(xmlDocument, copiedNode);

      dirResolved = resolveDirectory(aTixiDocument->dirname, externalDataDirectory);

      /* only save to local paths */
      if(string_startsWith(dirResolved, "file://") == 0) {
        char* externalDataDirectoryNotUrl = uriToLocalPath(dirResolved);
        assert(externalDataDirectoryNotUrl);

        fullExternalFileName = buildString("%s%s", externalDataDirectoryNotUrl, externalFileName);
        xmlSaveFormatFileEnc(fullExternalFileName, xmlDocument, "utf-8", 1);
        free(fullExternalFileName);
        free(externalDataDirectoryNotUrl);
      }
      free(dirResolved);
      xmlFreeDoc(xmlDocument);

      /* create external data node structure */
      fullExternalDataNodePath = buildString("%s/%s", externalDataNodePath, EXTERNAL_DATA_NODE_NAME);

      /* add parent node if not exists */
      if(tixiCheckElement(handle, fullExternalDataNodePath) != SUCCESS) {
        tixiAddTextElement(handle, externalDataNodePath, EXTERNAL_DATA_NODE_NAME, "");
        tixiAddTextElement(handle, fullExternalDataNodePath, EXTERNAL_DATA_NODE_NAME_PATH, externalDataDirectory);
      }

      /* add node for external reference */
      tixiAddTextElement(handle, fullExternalDataNodePath, EXTERNAL_DATA_NODE_NAME_FILENAME, externalFileName);

      /* remove the copied nodes from document*/
      copiedNode = cur_node->prev;
      xmlUnlinkNode(cur_node);
      xmlFreeNode(cur_node);
      free(fullExternalDataNodePath);
      cur_node = copiedNode;
    }
  }
  return SUCCESS;
}
Beispiel #27
0
ReturnCode openExternalFiles(TixiDocument* aTixiDocument, int* number)
{
  int iNode = 0;
  int handle = aTixiDocument->handle;
  xmlNodePtr cur = NULL;
  ReturnCode error = SUCCESS;

  assert(aTixiDocument != NULL);
  *number = 0;

  while(1) {
    // loop until there are no externaldata nodes included

    xmlXPathObjectPtr xpathObject = XPathEvaluateExpression(aTixiDocument->docPtr, "//externaldata");
    xmlNodeSetPtr nodeset = NULL;
    char* externalDataNodeXPath, *externalDataDirectoryXPath, *externalDataDirectory, *resolvedDirectory;
    int externalFileCount = 0;

    if (!xpathObject) {
      // no more external data, stop
      break;
    }

    nodeset = xpathObject->nodesetval;
    if (!nodeset || nodeset->nodeNr < 1) {
      break;
    }

    // goto the first node that is an element
    for (iNode = 0; iNode < nodeset->nodeNr; ++iNode) {
      cur = nodeset->nodeTab[iNode];
      if (cur->type == XML_ELEMENT_NODE) {
        break; // for loop
      }
    }
    if (iNode == nodeset->nodeNr) {
      // no element node found
      xmlXPathFreeObject(xpathObject);
      break; // while loop
    }

    // found external data node
    xmlXPathFreeObject(xpathObject);

    /* get nodes XPath */
    externalDataNodeXPath = (char*) xmlGetNodePath(cur);


    /* now get the subdirectory */
    externalDataDirectoryXPath = buildString("%s/%s", externalDataNodeXPath, EXTERNAL_DATA_NODE_NAME_PATH);

    error = tixiGetTextElement(handle, externalDataDirectoryXPath, &externalDataDirectory);
    free(externalDataDirectoryXPath);
    if (error) {
      printMsg(MESSAGETYPE_ERROR, "Error: openExternalFiles returns %d. No path defined in externaldata node!\n", error);
      xmlFree(externalDataNodeXPath);
      return OPEN_FAILED;
    }

    // resolv data directory (in case of relative paths)
    resolvedDirectory = resolveDirectory(aTixiDocument->dirname, externalDataDirectory);

    /* now get number and names of all external files */
    tixiGetNamedChildrenCount(handle, externalDataNodeXPath, EXTERNAL_DATA_NODE_NAME_FILENAME, &externalFileCount);
    if (externalFileCount == 0) {
      printMsg(MESSAGETYPE_ERROR, "Error: no filename nodes defined in externalData node.\n");
      xmlFree(externalDataNodeXPath);
      free(resolvedDirectory);
      return OPEN_FAILED;
    }

    for (iNode = 1; iNode <= externalFileCount; iNode++) {
      char* externalFileName, *externalFullFileName, *newDocumentString, *fileNameXPath;
      xmlDocPtr xmlDocument = NULL;

      fileNameXPath = buildString("%s/filename[%d]", externalDataNodeXPath, iNode);

      tixiGetTextElement(handle, fileNameXPath, &externalFileName);
      free(fileNameXPath);

      /* Build complete filename */
      externalFullFileName = buildString("%s%s", resolvedDirectory, externalFileName);

      /* open files */
      newDocumentString = loadExternalFileToString(externalFullFileName);
      if (newDocumentString == NULL) {
        printMsg(MESSAGETYPE_ERROR, "\nError in fetching external file \"%s\".\n", externalFullFileName);
        free(externalFullFileName);
        xmlFree(externalDataNodeXPath);
        free(resolvedDirectory);
        return OPEN_FAILED;
      }

      /* now parse the file to DOM */
      xmlDocument = xmlReadMemory(newDocumentString, (int) strlen(newDocumentString), "urlResource", NULL, 0);
      free(newDocumentString);

      if (xmlDocument) {
        xmlNodePtr rootToInsert = xmlDocGetRootElement(xmlDocument);

        xmlNodePtr parent = cur->parent;
        if (parent) {
          xmlChar* nodePathNew = NULL;
          char* dataURI = localPathToURI(externalDataDirectory);
          xmlNodePtr nodeToInsert = xmlDocCopyNode(rootToInsert, aTixiDocument->docPtr, 1);

          /* add metadata to node, to allow saving external node data */
          xmlSetProp(nodeToInsert, (xmlChar*) EXTERNAL_DATA_XML_ATTR_FILENAME, (xmlChar*) externalFileName);

          /* save the sub-directory */
          xmlSetProp(nodeToInsert, (xmlChar*) EXTERNAL_DATA_XML_ATTR_DIRECTORY, (xmlChar*) dataURI);
          free(dataURI);

          /* save the external data node position */
          nodePathNew = xmlGetNodePath(parent);
          xmlSetProp(nodeToInsert, (xmlChar*) EXTERNAL_DATA_XML_ATTR_NODEPATH, nodePathNew);
          xmlFree(nodePathNew);

          /* replace externalData node with xml file's content */
          xmlReplaceNode(cur, nodeToInsert);

          /* file could be loaded and parsed, increase the counter */
          (*number)++;
        }

        xmlFreeDoc(xmlDocument);
      }
      else {
        printMsg(MESSAGETYPE_WARNING,
                 "Document %s will be ignored. No valid XML document!\n",
                 externalFullFileName);

        /* remove external data node */
        xmlUnlinkNode(cur);
      }
      free(externalFullFileName);
    } /* end for files */

    free(resolvedDirectory);
    free(externalDataNodeXPath);
    xmlFreeNode(cur);
  }


  if (*number == 0) {
    printMsg(MESSAGETYPE_WARNING, "WARNING: Unable to load any externaldata files.\n");
  }

  return SUCCESS;
}
Beispiel #28
0
/**
 * xmlSchematronReportSuccess:
 * @ctxt:  the validation context
 * @test: the compiled test
 * @cur: the current node tested
 * @success: boolean value for the result
 *
 * called from the validation engine when an assert or report test have
 * been done.
 */
static void
xmlSchematronReportSuccess(xmlSchematronValidCtxtPtr ctxt, 
		   xmlSchematronTestPtr test, xmlNodePtr cur, xmlSchematronPatternPtr pattern, int success) {
    if ((ctxt == NULL) || (cur == NULL) || (test == NULL))
        return;
    /* if quiet and not SVRL report only failures */
    if ((ctxt->flags & XML_SCHEMATRON_OUT_QUIET) &&
        ((ctxt->flags & XML_SCHEMATRON_OUT_XML) == 0) &&
	(test->type == XML_SCHEMATRON_REPORT))
        return;
    if (ctxt->flags & XML_SCHEMATRON_OUT_XML) {
        TODO
    } else {
        xmlChar *path;
	char msg[1000];
	long line;
	const xmlChar *report = NULL;

        if (((test->type == XML_SCHEMATRON_REPORT) & (!success)) ||
	    ((test->type == XML_SCHEMATRON_ASSERT) & (success)))
	    return;
	line = xmlGetLineNo(cur);
	path = xmlGetNodePath(cur);
	if (path == NULL)
	    path = (xmlChar *) cur->name;
#if 0
	if ((test->report != NULL) && (test->report[0] != 0))
	    report = test->report;
#endif
	if (test->node != NULL)
            report = xmlSchematronFormatReport(ctxt, test->node, cur);
	if (report == NULL) {
	    if (test->type == XML_SCHEMATRON_ASSERT) {
            report = xmlStrdup((const xmlChar *) "node failed assert");
	    } else {
            report = xmlStrdup((const xmlChar *) "node failed report");
	    }
	    }
	    snprintf(msg, 999, "%s line %ld: %s\n", (const char *) path,
		     line, (const char *) report);

    if (ctxt->flags & XML_SCHEMATRON_OUT_ERROR) {
        xmlStructuredErrorFunc schannel = NULL;
        xmlGenericErrorFunc channel = NULL;
        void *data = NULL;

        if (ctxt != NULL) {
            if (ctxt->serror != NULL)
                schannel = ctxt->serror;
            else
                channel = ctxt->error;
            data = ctxt->userData;
	}

        __xmlRaiseError(schannel, channel, data,
                        NULL, cur, XML_FROM_SCHEMATRONV,
                        (test->type == XML_SCHEMATRON_ASSERT)?XML_SCHEMATRONV_ASSERT:XML_SCHEMATRONV_REPORT,
                        XML_ERR_ERROR, NULL, line,
                        (pattern == NULL)?NULL:((const char *) pattern->name),
                        (const char *) path,
                        (const char *) report, 0, 0,
                        msg);
    } else {
	xmlSchematronReportOutput(ctxt, cur, &msg[0]);
    }

    xmlFree((char *) report);

	if ((path != NULL) && (path != (xmlChar *) cur->name))
	    xmlFree(path);
    }
}
Beispiel #29
0
gboolean loadConfig(const gchar *filename, CfgFile *lcfg) {
    /* Parse hosts.xml document. */
    xmlDocPtr xcfg = xmlParseFile(filename);
    if(xcfg == NULL)
      return(FALSE);

    /* Handle Xincludes. */
    xmlSetGenericErrorFunc(NULL, xmlErrIgnoreHandler);
    xmlXIncludeProcess(xcfg);
    handleXMLError( xmlGetLastError() );
    xmlSetGenericErrorFunc(NULL, NULL);

    /* Validate against DTD. */
    xmlValidCtxtPtr xval = xmlNewValidCtxt();
    if(xmlValidateDocument(xval, xcfg) == 0) {
      xmlFreeValidCtxt(xval);
      return(FALSE);
    }
    xmlFreeValidCtxt(xval);

    /* Allocate XPath context. */
    xmlXPathContextPtr xctx = xmlXPathNewContext(xcfg);
    if(!xctx) {
      g_error("%s: xmlXPathNewContext failed!\n", filename);
      return(FALSE);
    }

    xmlNodePtr s_ssh[2] = {getXNode(xctx, "/apt-dater/ssh"), NULL};
    xmlNodePtr s_path[2] = {getXNode(xctx, "/apt-dater/paths"), NULL};
#ifdef FEAT_TMUX
    xmlNodePtr s_tmux[2] = {getXNode(xctx, "/apt-dater/tmux"), NULL};
#else
    xmlNodePtr s_screen[2] = {getXNode(xctx, "/apt-dater/screen"), NULL};
#endif
    xmlNodePtr s_appearance[2] = {getXNode(xctx, "/apt-dater/appearance"), NULL};
    xmlNodePtr s_notify[2] = {getXNode(xctx, "/apt-dater/notify"), NULL};
    xmlNodePtr s_hooks[2] = {getXNode(xctx, "/apt-dater/hooks"), NULL};
#ifdef FEAT_AUTOREF
    xmlNodePtr s_autoref[2] = {getXNode(xctx, "/apt-dater/auto-ref"), NULL};
#endif
#ifdef FEAT_HISTORY
    xmlNodePtr s_history[2] = {getXNode(xctx, "/apt-dater/history"), NULL};
#endif
#ifdef FEAT_TCLFILTER
    xmlNodePtr s_tclfilter[2] = {getXNode(xctx, "/apt-dater/tcl-filter"), NULL};
#endif

    lcfg->ssh_optflags = getXPropStr(s_ssh, "opt-cmd-flags", "-t");
    lcfg->ssh_cmd = getXPropStr(s_ssh, "cmd", "/usr/bin/ssh");
    lcfg->sftp_cmd = getXPropStr(s_ssh, "sftp-cmd", "/usr/bin/sftp");

    lcfg->umask = getXPropInt(s_path, "umask", S_IRWXG | S_IRWXO);
    umask(lcfg->umask);

    lcfg->hostsfile = getXPropStr(s_path, "hosts-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "hosts.xml"));
    lcfg->statsdir = getXPropStr(s_path, "stats-dir", g_strdup_printf("%s/%s/%s", g_get_user_cache_dir(), PROG_NAME, "stats"));
    if(g_mkdir_with_parents(lcfg->statsdir, S_IRWXU | S_IRWXG) == -1) {
      g_warning("Failed to create %s: %s", lcfg->statsdir, g_strerror(errno));
      exit(1);
    }

#ifdef FEAT_TMUX
    lcfg->tmuxconffile = getXPropStr(s_tmux, "conf-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "tmux.conf"));
    lcfg->tmuxsockpath = getXPropStr(s_tmux, "socket-path", g_strdup_printf("%s/%s/%s", g_get_user_cache_dir(), PROG_NAME, "tmux"));
    if(g_mkdir_with_parents(lcfg->tmuxsockpath, S_IRWXU | S_IRWXG) == -1) {
      g_warning("Failed to create %s: %s", lcfg->tmuxsockpath, g_strerror(errno));
      exit(1);
    }
#else
    lcfg->screenrcfile = getXPropStr(s_screen, "rc-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "screenrc"));
    lcfg->screentitle = getXPropStr(s_screen, "title", g_strdup("%m # %U%H"));
#endif

    lcfg->ssh_agent = getXPropBool(s_ssh, "spawn-agent", FALSE);

    xmlNodeSetPtr s_addkeys = getXNodes(xctx, "/apt-dater/ssh/add-key");
    if(!xmlXPathNodeSetIsEmpty(s_addkeys)) {
      lcfg->ssh_add = g_new0(char*, s_addkeys->nodeNr + 1);
      int i;
      for(i = 0; i < s_addkeys->nodeNr; i++) {
	lcfg->ssh_add[i] = g_strdup((gchar *)xmlGetProp(s_addkeys->nodeTab[i], BAD_CAST("name")));
	xmlChar *c = xmlGetProp(s_addkeys->nodeTab[i], BAD_CAST("fn"));
	if(!c) {
	    g_printerr(_("Empty SSH key filename (%s/@fn) in configuration."), xmlGetNodePath(s_addkeys->nodeTab[i]));
	    exit(1);
	}
	lcfg->ssh_add[i] = g_strdup((gchar *)c);
      }
      lcfg->ssh_numadd = s_addkeys->nodeNr;
    }
Beispiel #30
0
static int
noit_console_filter_configure(noit_console_closure_t ncct,
                              int argc, char **argv,
                              noit_console_state_t *state,
                              void *closure) {
  xmlNodePtr parent, fsnode = NULL;
  int rv = -1;
  noit_conf_t_userdata_t *info;
  char xpath[1024];

  info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
  if(!info) {
    nc_printf(ncct, "internal error\n");
    goto cleanup;
  }
  if(strncmp(info->path, "/filtersets/", strlen("/filtersets/")) &&
     strcmp(info->path, "/filtersets")) {
    nc_printf(ncct, "filterset only allows inside /filtersets (not %s)\n",
              info->path);
    goto cleanup;
  }
  if(argc != 1) {
    nc_printf(ncct, "filterset requires one argument\n");
    goto cleanup;
  }
  snprintf(xpath, sizeof(xpath), "/%s", info->path);
  parent = noit_conf_get_section(NULL, xpath);
  if(!parent) {
    nc_printf(ncct, "internal error, can't final current working path\n");
    goto cleanup;
  }
  snprintf(xpath, sizeof(xpath), "filterset[@name=\"%s\"]", argv[0]);
  fsnode = noit_conf_get_section(parent, xpath);
  if(closure) {
    int removed;
    removed = noit_filter_remove(fsnode);
    nc_printf(ncct, "%sremoved filterset '%s'\n",
              removed ? "" : "failed to ", argv[0]);
    if(removed) {
      xmlUnlinkNode(fsnode);
      xmlFreeNode(fsnode);
    }
    rv = !removed;
    goto cleanup;
  }
  if(!fsnode) {
    void *vfs;
    nc_printf(ncct, "Cannot find filterset '%s'\n", argv[0]);
    LOCKFS();
    if(noit_hash_retrieve(filtersets, argv[0], strlen(argv[0]), &vfs)) {
      UNLOCKFS();
      nc_printf(ncct, "filter of the same name already exists\n");
      goto cleanup;
    }
    UNLOCKFS();
    /* Fine the parent path */
    fsnode = xmlNewNode(NULL, (xmlChar *)"filterset");
    xmlSetProp(fsnode, (xmlChar *)"name", (xmlChar *)argv[0]);
    xmlAddChild(parent, fsnode);
    nc_printf(ncct, "created new filterset\n");
  }

  if(info) {
    char *xmlpath = NULL;
    if(info->path) free(info->path);
    xmlpath = (char *)xmlGetNodePath(fsnode);
    info->path = strdup(xmlpath + strlen("/noit"));
    free(xmlpath);
    strlcpy(info->filter_name, argv[0], sizeof(info->filter_name));
    if(state) {
      noit_console_state_push_state(ncct, state);
      noit_console_state_init(ncct);
    }
  }
 cleanup:
  return rv;
}