Пример #1
0
int xml_config_for_each_obj(const xml_config_t *config, const char *pattern,
							xml_config_cb_t cb, void *arg1, void *arg2)
{
	xmlXPathObject *objs;
	xmlNode *node;
	int i, ret = 0;

	if (!(objs = xmlXPathEval(BAD_CAST pattern, config->xpc))) {
		return -1;
	}

	if (xmlXPathNodeSetIsEmpty(objs->nodesetval) == 0) {
		for (i = 0; i < xmlXPathNodeSetGetLength(objs->nodesetval); i++) {
			if (!(node = xmlXPathNodeSetItem(objs->nodesetval, i))) {
				continue;
			}

			if ((ret = cb(node, arg1, arg2)) < 0) {
				break;
			}
		}
	}

	xmlXPathFreeObject(objs);
	return ret;
}
Пример #2
0
char *
epp_getSubtree(void *pool,
		epp_command_data *cdata,
		const char *xpath_expr,
		int position)
{
	char	*subtree;
	xmlBufferPtr	 buf;
	xmlDocPtr	 doc;
	xmlNodePtr	 node;
	xmlXPathObjectPtr	 xpath_obj;
	xmlXPathContextPtr	 xpath_ctx;

	doc = (xmlDocPtr) cdata->parsed_doc;
	xpath_ctx = (xmlXPathContextPtr) cdata->xpath_ctx;

	xpath_obj = xmlXPathEvalExpression(BAD_CAST xpath_expr, xpath_ctx);
	if (xpath_obj == NULL)
		return NULL;
	/* correct position for non-list elements */
	if (position == 0) position++;
	if (xmlXPathNodeSetGetLength(xpath_obj->nodesetval) < position) {
		xmlXPathFreeObject(xpath_obj);
		/* return empty string if the node is not there */
		return epp_strdup(pool, "");
	}

	/*
	 * Get content of problematic tag. It's not so easy task. We have
	 * to declare namespaces defined higher in the tree which are relevant
	 * to the part of document being dumped. Fortunatelly there is a
	 * function from libxml library doing exactly that (xmlreconsiliatens).
	 */
	buf = xmlBufferCreate();
	if (buf == NULL)
		return NULL;
	node = xmlXPathNodeSetItem(xpath_obj->nodesetval, position - 1);
	if (node->ns != NULL) {
		xmlNsPtr	 nsdef;

		nsdef = xmlSearchNs(doc, node, node->ns->prefix);
		if (nsdef != NULL)
			xmlNewNs(node, nsdef->href, nsdef->prefix);
	}
	if (xmlNodeDump(buf, doc, node, 0, 0) < 0)
	{
		xmlXPathFreeObject(xpath_obj);
		xmlBufferFree(buf);
		return NULL;
	}
	subtree = epp_strdup(pool, (char *) buf->content);
	xmlXPathFreeObject(xpath_obj);
	xmlBufferFree(buf);
	return subtree;
}
Пример #3
0
static gboolean
xmms_xspf_check_valid_xspf (xmlDocPtr doc, xmlXPathContextPtr xpath,
                            xmms_error_t *error)
{
	xmlXPathObjectPtr obj;

	obj = xmlXPathEvalExpression (BAD_CAST "/xspf:playlist[@version<=1]",
	                              xpath);

	if (!obj) {
		xmms_error_set (error, XMMS_ERROR_INVAL,
		                "unable to evaluate xpath expression");
		return FALSE;
	}

	if (xmlXPathNodeSetGetLength (obj->nodesetval) != 1) {
		xmms_error_set (error, XMMS_ERROR_INVAL,
		                "xspf document doesn't contain a version 0 or 1 "
		                "playlist");
		xmlXPathFreeObject (obj);
		return FALSE;
	}

	xmlXPathFreeObject (obj);
	obj = xmlXPathEvalExpression (BAD_CAST "/xspf:playlist[@version<=1]/xspf:trackList",
	                              xpath);

	if (!obj) {
		xmms_error_set (error, XMMS_ERROR_INVAL,
		                "unable to evaluate xpath expression");
		return FALSE;
	}

	if (xmlXPathNodeSetGetLength (obj->nodesetval) != 1) {
		xmms_error_set (error, XMMS_ERROR_INVAL,
		                "invalid xspf: document doesn't contain exactly one trackList");
		xmlXPathFreeObject (obj);
		return FALSE;
	}

	return TRUE;
}
Пример #4
0
/* This one adds all namespaces defined in document to a cache, without anything
   associated with uri obviously.
   Unfortunately namespace:: axis implementation in libxml2 differs from what we need,
   it uses additional node type to describe namespace definition attribute while
   in msxml it's expected to be a normal attribute - as a workaround document is
   queried at libxml2 level here. */
HRESULT cache_from_doc_ns(IXMLDOMSchemaCollection2 *iface, xmlnode *node)
{
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
    static const xmlChar query[] = "//*/namespace::*";
    xmlXPathObjectPtr nodeset;
    xmlXPathContextPtr ctxt;

    This->read_only = 1;

    ctxt = xmlXPathNewContext(node->node->doc);

    nodeset = xmlXPathEvalExpression(query, ctxt);
    xmlXPathFreeContext(ctxt);

    if (nodeset)
    {
        int pos = 0, len = xmlXPathNodeSetGetLength(nodeset->nodesetval);

        if (len == 0) return S_OK;

        while (pos < len)
        {
            xmlNodePtr node = xmlXPathNodeSetItem(nodeset->nodesetval, pos);
            if (node->type == XML_NAMESPACE_DECL)
            {
                static const xmlChar defns[] = "http://www.w3.org/XML/1998/namespace";
                xmlNsPtr ns = (xmlNsPtr)node;
                cache_entry *entry;

                /* filter out default uri */
                if (xmlStrEqual(ns->href, defns))
                {
                    pos++;
                    continue;
                }

                entry = heap_alloc(sizeof(cache_entry));
                entry->type = CacheEntryType_NS;
                entry->ref = 1;
                entry->schema = NULL;
                entry->doc = NULL;

                cache_add_entry(This, ns->href, entry);
            }
            pos++;
        }

        xmlXPathFreeObject(nodeset);
    }

    return S_OK;
}
Пример #5
0
static HRESULT WINAPI queryresult_get_length(
        IXMLDOMNodeList* iface,
        LONG* listLength)
{
    queryresult *This = impl_from_IXMLDOMNodeList( iface );

    TRACE("(%p)->(%p)\n", This, listLength);

    if(!listLength)
        return E_INVALIDARG;

    *listLength = xmlXPathNodeSetGetLength(This->result->nodesetval);
    return S_OK;
}
Пример #6
0
static HRESULT WINAPI domselection_get_length(
        IXMLDOMSelection* iface,
        LONG* listLength)
{
    domselection *This = impl_from_IXMLDOMSelection( iface );

    TRACE("(%p)->(%p)\n", This, listLength);

    if(!listLength)
        return E_INVALIDARG;

    *listLength = xmlXPathNodeSetGetLength(This->result->nodesetval);
    return S_OK;
}
Пример #7
0
static HRESULT queryresult_get_dispid(IUnknown *iface, BSTR name, DWORD flags, DISPID *dispid)
{
    queryresult *This = impl_from_IXMLDOMNodeList( (IXMLDOMNodeList*)iface );
    WCHAR *ptr;
    int idx = 0;

    for(ptr = name; *ptr && isdigitW(*ptr); ptr++)
        idx = idx*10 + (*ptr-'0');
    if(*ptr)
        return DISP_E_UNKNOWNNAME;

    if(idx >= xmlXPathNodeSetGetLength(This->result->nodesetval))
        return DISP_E_UNKNOWNNAME;

    *dispid = MSXML_DISPID_CUSTOM_MIN + idx;
    TRACE("ret %x\n", *dispid);
    return S_OK;
}
Пример #8
0
static int
noit_conf_mkcheck_under(const char *ppath, int argc, char **argv, uuid_t out) {
  int rv = -1;
  const char *path;
  char xpath[1024];
  xmlXPathContextPtr xpath_ctxt = NULL;
  xmlXPathObjectPtr pobj = NULL;
  xmlNodePtr node = NULL, newnode;

  /* attr val [or] no attr (sets of two) */
  if(argc % 2) goto out;

  mtev_conf_xml_xpath(NULL, &xpath_ctxt);
  path = strcmp(ppath, "/") ? ppath : "";
  snprintf(xpath, sizeof(xpath), "/noit%s", path);
  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET ||
     xmlXPathNodeSetGetLength(pobj->nodesetval) != 1) {
    goto out;
  }
  node = (mtev_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
  if((newnode = xmlNewChild(node, NULL, (xmlChar *)"check", NULL)) != NULL) {
    char outstr[37];
    uuid_generate(out);
    uuid_unparse_lower(out, outstr);
    xmlSetProp(newnode, (xmlChar *)"uuid", (xmlChar *)outstr);
    xmlSetProp(newnode, (xmlChar *)"disable", (xmlChar *)"true");

    /* No risk of running off the end (we checked this above) */
    if(noit_config_check_update_attrs(newnode, argc, argv)) {
      /* Something went wrong, remove the node */
      xmlUnlinkNode(newnode);
    }
    else {
      CONF_DIRTY(newnode);
      mtev_conf_mark_changed();
      rv = 0;
    }
  }
 out:
  if(pobj) xmlXPathFreeObject(pobj);
  return rv;
}
Пример #9
0
static HRESULT WINAPI domselection_nextNode(
        IXMLDOMSelection* iface,
        IXMLDOMNode** nextItem)
{
    domselection *This = impl_from_IXMLDOMSelection( iface );

    TRACE("(%p)->(%p)\n", This, nextItem );

    if(!nextItem)
        return E_INVALIDARG;

    *nextItem = NULL;

    if (This->resultPos >= xmlXPathNodeSetGetLength(This->result->nodesetval))
        return S_FALSE;

    *nextItem = create_node(xmlXPathNodeSetItem(This->result->nodesetval, This->resultPos));
    This->resultPos++;
    return S_OK;
}
Пример #10
0
static HRESULT WINAPI domselection_get_item(
        IXMLDOMSelection* iface,
        LONG index,
        IXMLDOMNode** listItem)
{
    domselection *This = impl_from_IXMLDOMSelection( iface );

    TRACE("(%p)->(%d %p)\n", This, index, listItem);

    if(!listItem)
        return E_INVALIDARG;

    *listItem = NULL;

    if (index < 0 || index >= xmlXPathNodeSetGetLength(This->result->nodesetval))
        return S_FALSE;

    *listItem = create_node(xmlXPathNodeSetItem(This->result->nodesetval, index));
    This->resultPos = index + 1;

    return S_OK;
}
Пример #11
0
HRESULT create_selection(xmlNodePtr node, xmlChar* query, IXMLDOMNodeList **out)
{
    domselection *This = heap_alloc(sizeof(domselection));
    xmlXPathContextPtr ctxt = xmlXPathNewContext(node->doc);
    HRESULT hr;

    TRACE("(%p, %s, %p)\n", node, wine_dbgstr_a((char const*)query), out);

    *out = NULL;
    if (!This || !ctxt || !query)
    {
        xmlXPathFreeContext(ctxt);
        heap_free(This);
        return E_OUTOFMEMORY;
    }

    This->IXMLDOMSelection_iface.lpVtbl = &domselection_vtbl;
    This->ref = 1;
    This->resultPos = 0;
    This->node = node;
    This->enumvariant = NULL;
    init_dispex(&This->dispex, (IUnknown*)&This->IXMLDOMSelection_iface, &domselection_dispex);
    xmldoc_add_ref(This->node->doc);

    ctxt->error = query_serror;
    ctxt->node = node;
    registerNamespaces(ctxt);

    if (is_xpathmode(This->node->doc))
    {
        xmlXPathRegisterAllFunctions(ctxt);
        This->result = xmlXPathEvalExpression(query, ctxt);
    }
    else
    {
        xmlChar* pattern_query = XSLPattern_to_XPath(ctxt, query);

        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"not", xmlXPathNotFunction);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"boolean", xmlXPathBooleanFunction);

        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"index", XSLPattern_index);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"end", XSLPattern_end);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"nodeType", XSLPattern_nodeType);

        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IEq", XSLPattern_OP_IEq);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_INEq", XSLPattern_OP_INEq);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_ILt", XSLPattern_OP_ILt);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_ILEq", XSLPattern_OP_ILEq);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IGt", XSLPattern_OP_IGt);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IGEq", XSLPattern_OP_IGEq);

        This->result = xmlXPathEvalExpression(pattern_query, ctxt);
        xmlFree(pattern_query);
    }

    if (!This->result || This->result->type != XPATH_NODESET)
    {
        hr = E_FAIL;
        goto cleanup;
    }

    *out = (IXMLDOMNodeList*)&This->IXMLDOMSelection_iface;
    hr = S_OK;
    TRACE("found %d matches\n", xmlXPathNodeSetGetLength(This->result->nodesetval));

cleanup:
    if (This && FAILED(hr))
        IXMLDOMSelection_Release( &This->IXMLDOMSelection_iface );
    xmlXPathFreeContext(ctxt);
    return hr;
}
Пример #12
0
static int
rest_show_check(mtev_http_rest_closure_t *restc,
                int npats, char **pats) {
  mtev_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 = NULL, *value = NULL;
  int rv, mod, mod_cnt, cnt, error_code = 500;
  mtev_hash_iter iter = MTEV_HASH_ITER_ZERO;
  const char *k;
  int klen;
  void *data;
  mtev_hash_table *configh;

  if(npats != 2 && npats != 3) goto error;

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

  mtev_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 = (mtev_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
  uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
  if(!uuid_conf || uuid_parse(uuid_conf, checkid)) goto error;

  if(npats == 3 && !strcmp(pats[2], ".json")) {
    return rest_show_check_json(restc, checkid);
  }

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

#define MYATTR(node,a,n,b) _mtev_conf_get_string(node, &(n), "@" #a, &(b))
#define INHERIT(node,a,n,b) \
  _mtev_conf_get_string(node, &(n), "ancestor-or-self::node()/@" #a, &(b))
#define SHOW_ATTR(parent, node, a) do { \
  char *_value = NULL; \
  INHERIT(node, a, anode, _value); \
  if(_value != NULL) { \
    int clen, plen;\
    char *_cpath, *_apath; \
    xmlNodePtr child; \
    _cpath = node ? (char *)xmlGetNodePath(node) : strdup(""); \
    _apath = anode ? (char *)xmlGetNodePath(anode) : strdup(""); \
    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); \
    free(_cpath); \
    free(_apath); \
    free(_value); \
  } \
} while(0)

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

  SHOW_ATTR(attr,node,uuid);
  SHOW_ATTR(attr,node,seq);

  /* 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);
  if(value) free(value);
  if(module) free(module);

  SHOW_ATTR(attr,node,module);
  SHOW_ATTR(attr,node,target);
  SHOW_ATTR(attr,node,resolve_rtype);
  SHOW_ATTR(attr,node,seq);
  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 = mtev_conf_get_hash(node, "config");
  while(mtev_hash_next(configh, &iter, &k, &klen, &data))
    NODE_CONTENT(config, k, data);
  mtev_hash_destroy(configh, free, free);
  free(configh);

  mod_cnt = noit_check_registered_module_cnt();
  for(mod=0; mod<mod_cnt; mod++) {
    xmlNsPtr ns;
    const char *nsname;
    char buff[256];

    nsname = noit_check_registered_module(mod);
 
    snprintf(buff, sizeof(buff), "noit://module/%s", nsname);
    ns = xmlSearchNs(root->doc, root, (xmlChar *)nsname);
    if(!ns) ns = xmlNewNs(root, (xmlChar *)buff, (xmlChar *)nsname);
    if(ns) {
      configh = mtev_conf_get_namespaced_hash(node, "config", nsname);
      if(configh) {
        memset(&iter, 0, sizeof(iter));
        while(mtev_hash_next(configh, &iter, &k, &klen, &data)) {
          NS_NODE_CONTENT(config, ns, "value", data,
            xmlSetProp(tmp, (xmlChar *)"name", (xmlChar *)k);
          );
        }
        mtev_hash_destroy(configh, free, free);
        free(configh);
      }
    }
  }
Пример #13
0
/* 
 * This function creates and setups the g_rn_machines global data structure of nodes
 */
void
rn_xml_topology()
{
	xmlXPathObjectPtr	obj;

	xmlNodePtr		node;

	unsigned int		i;
	//unsigned int		j;
	unsigned int		id;
	unsigned int		size;

	rn_as			*as;
	rn_area			*ar;
	rn_subnet		*sn;
	rn_machine		*m;

	size = 0;

	/* Environment */
	obj = xpath("//environment", ctxt);
	if(obj->nodesetval->nodeTab)
		g_rn_environment = *obj->nodesetval->nodeTab;
	xmlXPathFreeObject(obj);

	/* ASes */
	obj = xpath("/rossnet/as", ctxt);
	g_rn_nas = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nas > 0)
	{
		g_rn_as = (rn_as *) tw_calloc(TW_LOC, "", sizeof(rn_as), g_rn_nas);
		size += sizeof(rn_as) * g_rn_nas;
	}

	node = obj->nodesetval->nodeTab[0];
	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		g_rn_as[i].low = -1;
		g_rn_as[i].id = atoi(xml_getprop(node, "id"));	
		//g_rn_as[i].frequency = atoi(xml_getprop(node, "frequency"));	

#if WASTE_MEM
		if(0 == strcmp(xml_getprop(node, "name"), "name"))
			g_rn_as[i].name = (char *) xmlStrdup((xmlChar *) xml_getprop(node, "name"));
#endif

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	/* Areas */
	obj = xpath("/rossnet/as/area", ctxt);
	g_rn_nareas = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nareas > 0)
	{
		g_rn_areas = (rn_area *) tw_calloc(TW_LOC, "", sizeof(rn_area), g_rn_nareas);
		size += sizeof(rn_area) * g_rn_nareas;
	}

	node = obj->nodesetval->nodeTab[0];
	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		//g_rn_areas[i].root = INT_MAX;
		//g_rn_areas[i].root_lvl = 0xff;
		g_rn_areas[i].low = INT_MAX;
		g_rn_areas[i].id = atoi(xml_getprop(node, "id"));	
		g_rn_areas[i].as = &g_rn_as[atoi(xml_getprop(node->parent, "id"))];

		if(g_rn_areas[i].as->areas == NULL)
			g_rn_areas[i].as->areas = &g_rn_areas[i];

		if(i > 0 && g_rn_areas[i-1].as->id == g_rn_areas[i].as->id)
			g_rn_areas[i-1].next = &g_rn_areas[i];

		g_rn_areas[i].as->nareas++;

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	/* Subnets */
	obj = xpath("/rossnet/as/area/subnet", ctxt);
	g_rn_nsubnets = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nsubnets > 0)
	{
		g_rn_subnets = (rn_subnet *) tw_calloc(TW_LOC, "", sizeof(rn_subnet), g_rn_nsubnets);
		size += sizeof(rn_subnet) * g_rn_nsubnets;
	}

	node = *obj->nodesetval->nodeTab;
	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		g_rn_subnets[i].low = INT_MAX;
		g_rn_subnets[i].id = atoi(xml_getprop(node, "id"));	
		g_rn_subnets[i].area = &g_rn_areas[atoi(xml_getprop(node->parent, "id"))];

		if(g_rn_subnets[i].area->subnets == NULL)
			g_rn_subnets[i].area->subnets = &g_rn_subnets[i];

		if(i > 0 && g_rn_subnets[i-1].area->id == g_rn_subnets[i].area->id)
			g_rn_subnets[i-1].next = &g_rn_subnets[i];

		g_rn_subnets[i].area->nsubnets++;

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	/* Machines */
	obj = xpath("//node", ctxt);
	g_rn_nmachines = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nmachines)
	{
		g_rn_machines = tw_calloc(TW_LOC, "machines", 
					  sizeof(rn_machine), 
					  g_rn_nmachines);
		size += sizeof(rn_machine) * g_rn_nmachines;
	} else
		tw_error(TW_LOC, "No machines found in XML!");

	g_tw_nlp = ceil((double) obj->nodesetval->nodeNr / (double) tw_nnodes());

	node = *obj->nodesetval->nodeTab;

	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		id = atoi(xml_getprop(node, "id"));

		m = rn_getmachine(id);
		m->xml = node;
		m->conn = -1;
		m->id = id;
		m->nlinks = atoi(xml_getprop(node, "links"));	
		//m->level = atoi(xml_getprop(node, "lvl"));
		m->subnet = &g_rn_subnets[atoi(xml_getprop(node->parent, "id"))];

		if(0 != strcmp("", xml_getprop(node, "uid")))
			m->uid = atoi(xml_getprop(node, "uid"));
		else
			m->uid = -1;

		if(strcmp("c_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_router;
			g_rn_nrouters++;
		} else if(strcmp("c_ct_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_ct_router;
			g_rn_nrouters++;
		} else if(strcmp("c_og_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_og_router;
			g_rn_nrouters++;
		} else if(strcmp("c_co_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_co_router;
			g_rn_nrouters++;
		} else if(strcmp("c_ha_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_ha_router;
			g_rn_nrouters++;
		} else if(strcmp("c_host", xml_getprop(node, "type")) == 0)
			m->type = c_host;
		else
			tw_error(TW_LOC, "Unknown node type: %s", xml_getprop(node, "type"));

		if(m->subnet->machines == NULL)
			m->subnet->machines = &g_rn_machines[i];

#if 0
		if(id > 0 && 
		   g_rn_machines[id-1].subnet->id == g_rn_machines[id].subnet->id)
			g_rn_machines[id-1].next = &g_rn_machines[id];
#endif

		m->subnet->nmachines++;
		m->subnet->area->nmachines++;
		m->link = (rn_link *) tw_calloc(TW_LOC, "", sizeof(rn_link) * m->nlinks, 1);
		m->hash_link = rn_hash_create(m->nlinks);

		size += sizeof(rn_link) * m->nlinks;

		//printf("Init\'ing Machines id: %d \n", m->id);

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	xml_link_topology();

	/*
	 * Set up the global connection library
	 */
	obj = xpath("//connect", ctxt);

	if(obj->nodesetval->nodeNr)
	{
		node = *obj->nodesetval->nodeTab;

		for(i = 0; i < obj->nodesetval->nodeNr; )
		{
			m = rn_getmachine(atoll(xml_getprop(node, "src")));
			m->conn = atoll(xml_getprop(node, "dst"));

			// back link the connection
			//rn_getmachine(m->conn)->conn = m->id;

			node = obj->nodesetval->nodeTab[++i];
		}
	}

	xmlXPathFreeObject(obj);

	for(i = 0; i < g_rn_nmachines; i++)
	{
		m = rn_getmachine(i);

		sn = m->subnet;
		ar = sn->area;
		as = ar->as;

		if(i < sn->low)
		{
			sn->low = i;

			if(i < ar->low)
			{
				ar->low = i;

				if(0 && i < as->low)
					as->low = i;
			}
		}

		if(i > sn->high)
		{
			sn->high = i;

			if(i > ar->high)
			{
				ar->high = i;

				if(0 && i > as->high)
					as->high = i;
			}
		}

		if(m->type == c_host)
			continue;

		ar->g_ospf_nlsa = ar->nmachines + ar->as->nareas + g_rn_nas;

		if(ar->nmachines == 0)
			tw_error(TW_LOC, "No machines in Area %d!\n", ar->id);

#if 0
		m->ft = (int *) tw_calloc(TW_LOC, "", sizeof(int ) * ar->g_ospf_nlsa, 1);
		size += sizeof(int) * ar->g_ospf_nlsa;

		for(j = 0; j < ar->g_ospf_nlsa; j++)
			m->ft[j] = -1;
#endif

/*
		printf("mach %d: alloc FT of size: %d \n", 
			i, ar->nmachines + as->nareas + g_rn_nas);
*/
	}

	ar = NULL;
	as = NULL;
	while(NULL != (as = rn_nextas(as)))
	{
		while(NULL != (ar = rn_nextarea_onas(ar, as)))
		{
			if(as->low == -1)
				as->low = ar->id;
			as->high = ar->id;
		}

		//printf("AS %d: low %ld, high %ld \n", as->id, as->low, as->high);
	}

#if RN_XML_DEBUG || 1
	if(tw_ismaster())
	{
		printf("\n");
		printf("%-32s %11d \n", "ASes: ", g_rn_nas);
		printf("%-32s %11d \n", "Areas: ", g_rn_nareas);
		printf("%-32s %11d \n", "Subnets: ", g_rn_nsubnets);
		printf("%-32s %11d \n", "Machines: ", g_rn_nmachines);
		printf("%-32s %11d \n", "Links: ", g_rn_nlinks);
		printf("%-32s %11d bytes\n", "Total topology size: ", size);
		printf("\n");
	}
#endif

	//verify_topology();
}
Пример #14
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;
}
Пример #15
0
int
main(int argc, char* argv[]) {
    CURL* curl = NULL;
    CURLcode res;
    int status = 0;
    char error[CURL_ERROR_SIZE];
    char fname[256];
    char line[256];
    char cookie[2048];
    char query[2048];
    char* buf = NULL;
    char* ptr = NULL;
    char* tmp = NULL;
    char* id;
    FILE* fp = NULL;
    MEMFILE* mf; // mem file
    MEMFILE* hf; // mem file for header

    // usage
    if (argc != 2) {
        fputs("usage: nicodown [video_id]\n", stderr);
        goto leave;
    }

    if (!(ptr = getenv("HOME"))) {
#ifdef _WIN32
        if (!(ptr = getenv("USERPROFILE"))) {
            fprintf(stderr, "failed to get HOME directory\n");
            goto leave;
        }
#else
        fprintf(stderr, "failed to get HOME directory\n");
        goto leave;
#endif
    }

    sprintf(fname, "%s/.nicodownrc", ptr);
    fp = fopen(fname, "r");
    if (!fp || !fgets(line, sizeof(line), fp)) {
        if (fp) fclose(fp);
        fprintf(stderr, "failed to read ~/.nicodownrc\n");
        goto leave;
    }
    fclose(fp);
    tmp = strpbrk(line, "\r\n");
    if (tmp) *tmp = 0;
    ptr = strchr(line, ':');
    if (!ptr) {
        fprintf(stderr, "failed to parse ~/.nicodownrc\n");
        goto leave;
    }
    *ptr++ = 0;

    id = argv[1];
    if (!strncmp(id, WATCH_URL_BASE, strlen(WATCH_URL_BASE))) {
        id += strlen(WATCH_URL_BASE);
    }
    sprintf(query, "mail_tel=%s&password=%s&next_url=/watch/%s", line, ptr, id);

    // default filename
    sprintf(fname, "%s.flv", id);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, memfwrite);

    // login
    mf = memfopen();
    hf = memfopen();
    curl_easy_setopt(curl, CURLOPT_URL, "https://secure.nicovideo.jp/secure/login?site=niconico");
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, mf);
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, hf);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, memfwrite);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fputs(error, stderr);
        memfclose(mf);
        memfclose(hf);
        goto leave;
    }

    // parse cookie
    memset(cookie, 0, sizeof(cookie));
    buf = memfstrdup(hf);
    tmp = buf;
    while (tmp = strstr(tmp, "Set-Cookie: ")) {
        ptr = tmp;
        tmp = strpbrk(ptr, "\r\n;");
        if (tmp) *tmp = 0;
        strcpy(cookie, ptr + 12);
        if (strncmp(cookie, "user_session=user", 17) == 0) {
            curl_easy_setopt(curl, CURLOPT_COOKIE, cookie);
            break;
        }
        tmp++;
    }
    free(buf);

    memfclose(mf);
    memfclose(hf);
    mf = memfopen();
    hf = memfopen();
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, mf);
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, hf);

    // redirect
    sprintf(query, "http://www.nicovideo.jp/watch/%s", id);
    curl_easy_setopt(curl, CURLOPT_URL, query);
    curl_easy_setopt(curl, CURLOPT_POST, 0);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fputs(error, stderr);
        memfclose(mf);
        memfclose(hf);
        goto leave;
    }

    // parse cookie
    buf = memfstrdup(hf);
    ptr = NULL;
    tmp = buf;
    while (tmp = strstr(tmp, "Set-Cookie: ")) {
        ptr = tmp + 12;
        tmp = strpbrk(ptr, "\r\n;");
        if (tmp) *tmp = 0;
        strcat(cookie, ";");
        strcat(cookie, ptr);
        tmp++;
    }
    curl_easy_setopt(curl, CURLOPT_COOKIE, cookie);
    free(buf);

    // parse response body
    buf = memfstrdup(mf);
    if (buf && strstr(buf, "id=\"login_bar\"")) {
        free(buf);
        fprintf(stderr, "failed to login\n");
        memfclose(mf);
        memfclose(hf);
        goto leave;
    }
    free(buf);
    memfclose(hf);
    memfclose(mf);

    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, NULL);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);

    // get video query, and get filename
    sprintf(query, "http://www.nicovideo.jp/api/getthumbinfo?v=%s", id);
    mf = memfopen();
    curl_easy_setopt(curl, CURLOPT_URL, query);
    curl_easy_setopt(curl, CURLOPT_POST, 0);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, mf);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, memfwrite);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fputs(error, stderr);
        memfclose(mf);
        goto leave;
    }

#ifdef USE_LIBXML
    // parse title node
    {
        xmlDocPtr doc = NULL;
        xmlXPathContextPtr xpathctx;
        xmlXPathObjectPtr xpathobj;

        doc = xmlParseMemory(mf->data, mf->size);
        xpathctx = doc ? xmlXPathNewContext(doc) : NULL;
        xpathobj = xpathctx ? xmlXPathEvalExpression((xmlChar*) "//title", xpathctx) : NULL;
        if (xpathobj) {
            int n;
            xmlNodeSetPtr nodes = xpathobj->nodesetval;
            for(n = 0; nodes && n < xmlXPathNodeSetGetLength(nodes); n++) {
                xmlNodePtr node = nodes->nodeTab[n];
                if(node->type != XML_ATTRIBUTE_NODE && node->type != XML_ELEMENT_NODE && node->type != XML_CDATA_SECTION_NODE) continue;
                if (node->type == XML_CDATA_SECTION_NODE)
                    sprintf(fname, "%s.flv", (char*) node->content);
                else
                    if (node->children)
                        sprintf(fname, "%s.flv", (char*) node->children->content);
                break;
            }
        }
        if (xpathobj ) xmlXPathFreeObject(xpathobj);
        if (xpathctx) xmlXPathFreeContext(xpathctx);
        if (doc) xmlFreeDoc(doc);
    }
#else
    buf = memfstrdup(mf);
    ptr = buf ? strstr(buf, "<title>") : NULL;
    if (ptr) {
        ptr += 7;
        tmp = strstr(ptr, "</title>");
        if (*tmp) {
            *tmp = 0;
            sprintf(fname, "%s.flv", ptr);
        }
    }
    if (buf) free(buf);
#endif

    memfclose(mf);

#ifdef _WIN32
    {
        UINT codePage;
        size_t wcssize;
        wchar_t* wcsstr;
        size_t mbssize;
        char* mbsstr;

        codePage = CP_UTF8;
        wcssize = MultiByteToWideChar(codePage, 0, fname, -1,  NULL, 0);
        wcsstr = (wchar_t*) malloc(sizeof(wchar_t) * (wcssize + 1));
        wcssize = MultiByteToWideChar(codePage, 0, fname, -1, wcsstr, wcssize + 1);
        wcsstr[wcssize] = 0;
        codePage = GetACP();
        mbssize = WideCharToMultiByte(codePage, 0, (LPCWSTR) wcsstr,-1,NULL,0,NULL,NULL);
        mbsstr = (char*) malloc(mbssize+1);
        mbssize = WideCharToMultiByte(codePage, 0, (LPCWSTR) wcsstr, -1, mbsstr, mbssize, NULL, NULL);
        mbsstr[mbssize] = 0;
        strcpy(fname, mbsstr);
        free(mbsstr);
        free(wcsstr);
    }
#endif

    // get video query
    sprintf(query, "http://flapi.nicovideo.jp/api/getflv?v=%s", id);
    mf = memfopen();
    curl_easy_setopt(curl, CURLOPT_URL, query);
    curl_easy_setopt(curl, CURLOPT_POST, 0);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, mf);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, memfwrite);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fputs(error, stderr);
        memfclose(mf);
        goto leave;
    }
    buf = memfstrdup(mf);
    ptr = strstr(buf, "url=");
    if (!ptr) {
        if (buf) free(buf);
        fprintf(stderr, "failed to get video info\n");
        memfclose(mf);
        goto leave;
    }
    tmp = strstr(ptr, "&");
    if (tmp) *tmp = 0;
    tmp = ptr;
    while(*tmp) {
        if (IS_QUOTED(tmp)) {
            unsigned int num = 0;
            sscanf(tmp+1, "%02x", &num);
            *tmp = (char)num;
            strcpy(tmp + 1, tmp + 3);
        }
        tmp++;
    }
    strcpy(query, ptr + 4);
    printf("URL: %s\n", query);
    free(buf);
    memfclose(mf);

    // sanitize filename
    ptr = fname;
    while (*ptr) {
        if (strchr("\\/|:<>\"?*", *ptr)) *ptr = '_';
        ptr++;
    }

    // download video
    fp = fopen(fname, "wb");
    if (!fp) {
        fprintf(stderr, "failed to open file: %s\n", fname);
        goto leave;
    }
    curl_easy_setopt(curl, CURLOPT_URL, query);
    curl_easy_setopt(curl, CURLOPT_POST, 0);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress);
    curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, (void*)fname);
    curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, BUFSIZ);
    /* curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); */
    res = curl_easy_perform(curl);
    fclose(fp);
    if (res != CURLE_OK) {
        fputs(error, stderr);
        goto leave;
    }

leave:
    if (curl) curl_easy_cleanup(curl);
    printf("\n");

    return 0;
}
Пример #16
0
flickcurl_video*
flickcurl_build_video(flickcurl* fc, xmlXPathContextPtr xpathCtx,
                      const xmlChar* xpathExpr)
{
  flickcurl_video* v = NULL;
  int nodes_count;
  int i;
  xmlXPathObjectPtr xpathObj = NULL;
  xmlNodeSetPtr nodes;
  int count = 0;
  
  /* Now do video */
  xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
  if(!xpathObj) {
    flickcurl_error(fc, "Unable to evaluate XPath expression \"%s\"", 
                    xpathExpr);
    fc->failed = 1;
    goto tidy;
  }
  
  nodes = xpathObj->nodesetval;
  /* This is a max size - it can include nodes that are CDATA */
  nodes_count = xmlXPathNodeSetGetLength(nodes);
  
  v = (flickcurl_video*)calloc(1, sizeof(flickcurl_video));
  if(!v) {
    flickcurl_error(fc, "Unable to allocate the memory needed for video.");
    fc->failed = 1;
    goto tidy;
  }

  

  for(i = 0; i < nodes_count; i++) {
    xmlNodePtr node = nodes->nodeTab[i];
    xmlAttr* attr;
    const char *node_name = (const char*)node->name;
    
    if(node->type != XML_ELEMENT_NODE) {
      flickcurl_error(fc, "Got unexpected node type %d", node->type);
      fc->failed = 1;
      break;
    }
    
    if(strcmp(node_name, "video"))
      continue;
    
    count++;
    
    for(attr = node->properties; attr; attr = attr->next) {
      const char *attr_name = (const char*)attr->name;
      int attr_value = atoi((const char*)attr->children->content);
      if(!strcmp(attr_name, "ready"))
        v->ready = attr_value;
      else if(!strcmp(attr_name, "failed"))
        v->failed = attr_value;
      else if(!strcmp(attr_name, "pending"))
        v->pending = attr_value;
      else if(!strcmp(attr_name, "duration"))
        v->duration = attr_value;
      else if(!strcmp(attr_name, "width"))
        v->width = attr_value;
      else if(!strcmp(attr_name, "height"))
        v->height = attr_value;
    }

  } /* for nodes */

  if(!count) {
    flickcurl_free_video(v);
    v = NULL;
  } 
#if FLICKCURL_DEBUG > 1
else {
    fprintf(stderr, "video: ready %d  failed %d  pending %d  duration %d  width %d  height %d\n",
            v->ready, v->failed, v->pending, v->duration,
            v->width, v->height);
  }
#endif
  
 tidy:
  if(xpathObj)
    xmlXPathFreeObject(xpathObj);

  return v;
}
Пример #17
0
static void
proxy_call_browse_grlnet_async_cb (GObject *source_object,
                                   GAsyncResult *res,
                                   gpointer user_data)
{
  RaitvOperation    *op = (RaitvOperation *) user_data;
  xmlDocPtr           doc = NULL;
  xmlXPathContextPtr  xpath = NULL;
  xmlXPathObjectPtr   obj = NULL;
  gint i, nb_items = 0;
  gsize length;


  GRL_DEBUG ("Response id=%u", op->operation_id);

  GError *wc_error = NULL;
  GError *error = NULL;
  gchar *content = NULL;

  if (g_cancellable_is_cancelled (op->cancellable)) {
    goto finalize;
  }


  if (!grl_net_wc_request_finish (GRL_NET_WC (source_object),
                                  res,
                                  &content,
                                  &length,
                                  &wc_error)) {
    error = g_error_new (GRL_CORE_ERROR,
                         GRL_CORE_ERROR_SEARCH_FAILED,
                         _("Failed to browse: %s"),
                         wc_error->message);

    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  error);

    g_error_free (wc_error);
    g_error_free (error);

    return;
  }

  doc = xmlRecoverMemory (content, (gint) length);

  if (!doc) {
    GRL_DEBUG ("Doc failed");
    goto finalize;
  }

  xpath = xmlXPathNewContext (doc);
  if (!xpath) {
    GRL_DEBUG ("Xpath failed");
    goto finalize;
  }

  gchar* xquery=NULL;
  switch (classify_media_id (op->container_id))
    {
    case RAITV_MEDIA_TYPE_POPULAR_THEME:
      xquery = "/CLASSIFICAVISTI/content";
      break;
    case RAITV_MEDIA_TYPE_RECENT_THEME:
      xquery = "/INFORMAZIONICONTENTS/content";
      break;
    default:
      goto finalize;
    }

  obj = xmlXPathEvalExpression ((xmlChar *) xquery, xpath);
  if (obj)
    {
      nb_items = xmlXPathNodeSetGetLength (obj->nodesetval);
      xmlXPathFreeObject (obj);
    }

  if (nb_items < op->count)
    op->count = nb_items;

  op->category_info->count = nb_items;

  for (i = 0; i < nb_items; i++)
    {

      //Skip
      if(op->skip>0) {
        op->skip--;
        continue;
      }

      GrlRaitvSource *source = GRL_RAITV_SOURCE (op->source);
      GList *mapping = source->priv->raitv_browse_mappings;
      GrlMedia *media = grl_media_video_new ();

      while (mapping)
        {
          gchar *str;
          gchar *strvalue;

          RaitvAssoc *assoc = (RaitvAssoc *) mapping->data;
          str = g_strdup_printf ("string(%s[%i]/%s)",
                                 xquery,i + 1, assoc->exp);


          obj = xmlXPathEvalExpression ((xmlChar *) str, xpath);
          if (obj)
            {
              if (obj->stringval && obj->stringval[0] != '\0')
                {
                  strvalue = 	g_strdup((gchar *) obj->stringval);
                  //Sometimes GRL_METADATA_KEY_THUMBNAIL doesn't report complete url
                  if(assoc->grl_key == GRL_METADATA_KEY_THUMBNAIL && !g_str_has_prefix(strvalue,"http://www.rai.tv/")) {
                    strvalue = g_strdup_printf("http://www.rai.tv%s",obj->stringval);
                  }

                  GType _type;
                  _type = grl_metadata_key_get_type (assoc->grl_key);
                  switch (_type)
                    {
                    case G_TYPE_STRING:
                      grl_data_set_string (GRL_DATA (media),
                                           assoc->grl_key,
                                           strvalue);
                      break;

                    case G_TYPE_INT:
                      grl_data_set_int (GRL_DATA (media),
                                        assoc->grl_key,
                                        (gint) atoi (strvalue));
                      break;

                    case G_TYPE_FLOAT:
                      grl_data_set_float (GRL_DATA (media),
                                          assoc->grl_key,
                                          (gfloat) atof (strvalue));
                      break;

                    default:
                      /* G_TYPE_DATE_TIME is not a constant, so this has to be
                       * in "default:" */
                      if (_type == G_TYPE_DATE_TIME) {
                        int year,month,day,hour,minute,seconds;
                        sscanf((const char*)obj->stringval, "%02d/%02d/%04d %02d:%02d:%02d",
                               &day, &month, &year, &hour,&minute, &seconds);
                        GDateTime *date = g_date_time_new_local (year, month, day, hour,minute, seconds);
                        grl_data_set_boxed (GRL_DATA (media),
                                            assoc->grl_key, date);
                        if(date) g_date_time_unref (date);
                      } else {
                        GRL_DEBUG ("\tUnexpected data type: %s",
                                   g_type_name (_type));
                      }
                      break;
                    }
                  g_free (strvalue);
                }
              xmlXPathFreeObject (obj);
            }

          g_free (str);

          mapping = mapping->next;
        }

      op->callback (op->source,
                    op->operation_id,
                    media,
                    --op->count,
                    op->user_data,
                    NULL);

      if (op->count == 0) {
        break;
      }
    }

 finalize:
  g_clear_pointer (&xpath, xmlXPathFreeContext);
  g_clear_pointer (&doc, xmlFreeDoc);

  /* Signal the last element if it was not already signaled */
  if (nb_items == 0) {
    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  NULL);
  }
  else {
    //Continue the search
    if(op->count>0) {
      //Skip the ones already read
      op->skip +=  nb_items;
      op->offset +=  nb_items;
      switch (classify_media_id (op->container_id))
		  {
        case RAITV_MEDIA_TYPE_POPULAR_THEME:
          produce_from_popular_theme(op);
          break;
        case RAITV_MEDIA_TYPE_RECENT_THEME:
          produce_from_recent_theme(op);
          break;
        default:
          g_assert_not_reached ();
          break;
		  }

    }
  }

}
Пример #18
0
static int
replace_config(noit_console_closure_t ncct,
               noit_conf_t_userdata_t *info, const char *name,
               const char *value) {
  int i, cnt, rv = -1, active = 0;
  xmlXPathObjectPtr pobj = NULL;
  xmlXPathContextPtr xpath_ctxt = NULL;
  xmlNodePtr node, confignode;
  char xpath[1024], *path;

  path = info->path;
  if(!strcmp(path, "/")) path = "";

  noit_conf_xml_xpath(NULL, &xpath_ctxt);

  /* Only if checks will fixate this attribute shall we check for
   * child <check> nodes.
   * NOTE: this return nothing and "seems" okay if we are _in_
   *       a <check> node.  That case is handled below.
   */
  snprintf(xpath, sizeof(xpath), "/noit/%s//check[@uuid]", path);
  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET) goto out;
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  for(i=0; i<cnt; i++) {
    uuid_t checkid;
    node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
    if(noit_conf_get_uuid(node, "@uuid", checkid)) {
      noit_check_t *check;
      check = noit_poller_lookup(checkid);
      if(check && NOIT_CHECK_LIVE(check)) active++;
    }
  }
  if(pobj) xmlXPathFreeObject(pobj);

#ifdef UNSAFE_RECONFIG
  snprintf(xpath, sizeof(xpath), "/noit/%s", path);
  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET) goto out;
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  if(cnt != 1) {
    nc_printf(ncct, "Internal error: context node disappeared\n");
    goto out;
  }
  node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
  if(strcmp((const char *)node->name, "check")) {
    uuid_t checkid;
    /* Detect if  we are actually a <check> node and attempting to
     * change something we shouldn't.
     * This is the counterpart noted above.
     */
    if(noit_conf_get_uuid(node, "@uuid", checkid)) {
      noit_check_t *check;
      check = noit_poller_lookup(checkid);
      if(NOIT_CHECK_LIVE(check)) active++;
    }
  }
  if(active) {
    nc_printf(ncct, "Cannot set '%s', it would effect %d live check(s)\n",
              name, active);
    goto out;
  }
  if(pobj) xmlXPathFreeObject(pobj);
#endif

  /* Here we want to remove /noit/path/config/name */
  snprintf(xpath, sizeof(xpath), "/noit/%s/config/%s", path, name);
  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET) goto out;
  if(xmlXPathNodeSetGetLength(pobj->nodesetval) > 0) {
    xmlNodePtr toremove;
    toremove = xmlXPathNodeSetItem(pobj->nodesetval, 0);
    xmlUnlinkNode(toremove);
  }
  /* TODO: if there are no more children of config, remove config? */
  if(value) {
    if(pobj) xmlXPathFreeObject(pobj);
    /* He we create config if needed and place a child node under it */
    snprintf(xpath, sizeof(xpath), "/noit/%s/config", path);
    pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
    if(!pobj || pobj->type != XPATH_NODESET) goto out;
    if(xmlXPathNodeSetGetLength(pobj->nodesetval) == 0) {
      if(pobj) xmlXPathFreeObject(pobj);
      snprintf(xpath, sizeof(xpath), "/noit/%s", path);
      pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
      if(!pobj || pobj->type != XPATH_NODESET) goto out;
      if(xmlXPathNodeSetGetLength(pobj->nodesetval) != 1) {
        nc_printf(ncct, "Node disappeared from under you!\n");
        goto out;
      }
      confignode = xmlNewChild(xmlXPathNodeSetItem(pobj->nodesetval, 0),
                               NULL, (xmlChar *)"config", NULL);
      if(confignode == NULL) {
        nc_printf(ncct, "Error creating config child node.\n");
        goto out;
      }
    }
    else confignode = xmlXPathNodeSetItem(pobj->nodesetval, 0);

    assert(confignode);
    /* Now we create a child */
    xmlNewChild(confignode, NULL, (xmlChar *)name, (xmlChar *)value);
  }
  noit_conf_mark_changed();
  rv = 0;
 out:
  if(pobj) xmlXPathFreeObject(pobj);
  return rv;
}
Пример #19
0
static int
replace_attr(noit_console_closure_t ncct,
             noit_conf_t_userdata_t *info, struct _valid_attr_t *attrinfo,
             const char *value) {
  int i, cnt, rv = -1, active = 0;
  xmlXPathObjectPtr pobj = NULL;
  xmlXPathContextPtr xpath_ctxt = NULL;
  xmlNodePtr node;
  char xpath[1024], *path;

  path = info->path;
  if(!strcmp(path, "/")) path = "";

  noit_conf_xml_xpath(NULL, &xpath_ctxt);
  if(attrinfo->checks_fixate) {
    /* Only if checks will fixate this attribute shall we check for
     * child <check> nodes.
     * NOTE: this return nothing and "seems" okay if we are _in_
     *       a <check> node.  That case is handled below.
     */
    snprintf(xpath, sizeof(xpath), "/noit/%s//check[@uuid]", path);
    pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
    if(!pobj || pobj->type != XPATH_NODESET) goto out;
    cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
    for(i=0; i<cnt; i++) {
      uuid_t checkid;
      node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
      if(noit_conf_get_uuid(node, "@uuid", checkid)) {
        noit_check_t *check;
        check = noit_poller_lookup(checkid);
        if(check && NOIT_CHECK_LIVE(check)) active++;
      }
    }
    if(pobj) xmlXPathFreeObject(pobj);
  }
  snprintf(xpath, sizeof(xpath), "/noit/%s", path);
  pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
  if(!pobj || pobj->type != XPATH_NODESET) goto out;
  cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
  if(cnt != 1) {
    nc_printf(ncct, "Internal error: context node disappeared\n");
    goto out;
  }
  node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
  if(attrinfo->checks_fixate &&
     !strcmp((const char *)node->name, "check")) {
    uuid_t checkid;
    /* Detect if  we are actually a <check> node and attempting to
     * change something we shouldn't.
     * This is the counterpart noted above.
     */
    if(noit_conf_get_uuid(node, "@uuid", checkid)) {
      noit_check_t *check;
      check = noit_poller_lookup(checkid);
      if(check && NOIT_CHECK_LIVE(check)) active++;
    }
  }
  if(active) {
    nc_printf(ncct, "Cannot set '%s', it would effect %d live check(s)\n",
              attrinfo->name, active);
    goto out;
  }
  xmlUnsetProp(node, (xmlChar *)attrinfo->name);
  if(value)
    xmlSetProp(node, (xmlChar *)attrinfo->name, (xmlChar *)value);
  noit_conf_mark_changed();
  rv = 0;
 out:
  if(pobj) xmlXPathFreeObject(pobj);
  return rv;
}
Пример #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;
}
Пример #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;
}
Пример #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;
}
Пример #23
0
static gboolean
_lt_ext_ldml_u_lookup_key(lt_ext_ldml_u_data_t  *data,
			  const gchar           *subtag,
			  GError               **error)
{
	gint i, j, n;
	lt_xml_t *xml = lt_xml_new();
	gboolean retval = FALSE;

	for (i = LT_XML_CLDR_BCP47_BEGIN; i <= LT_XML_CLDR_BCP47_END; i++) {
		xmlDocPtr doc = lt_xml_get_cldr(xml, i);
		xmlXPathContextPtr xctxt = NULL;
		xmlXPathObjectPtr xobj = NULL;

		xctxt = xmlXPathNewContext(doc);
		if (!xctxt) {
			g_set_error(error, LT_ERROR, LT_ERR_OOM,
				    "Unable to create an instance of xmlXPathContextPtr.");
			goto bail1;
		}
		xobj = xmlXPathEvalExpression((const xmlChar *)"/ldmlBCP47/keyword/key", xctxt);
		if (!xobj) {
			g_set_error(error, LT_ERROR, LT_ERR_FAIL_ON_XML,
				    "No valid elements for %s",
				    doc->name);
			goto bail1;
		}
		n = xmlXPathNodeSetGetLength(xobj->nodesetval);

		for (j = 0; j < n; j++) {
			xmlNodePtr ent = xmlXPathNodeSetItem(xobj->nodesetval, j);
			xmlChar *name;

			if (!ent) {
				g_set_error(error, LT_ERROR, LT_ERR_FAIL_ON_XML,
					    "Unable to obtain the xml node via XPath.");
				goto bail1;
			}
			name = xmlGetProp(ent, (const xmlChar *)"name");
			if (g_ascii_strcasecmp((const gchar *)name, subtag) == 0) {
				data->current_type = i;
				data->state = STATE_TYPE;
				xmlFree(name);
				retval = TRUE;
				goto bail1;
			}
			xmlFree(name);
		}
	  bail1:
		if (xobj)
			xmlXPathFreeObject(xobj);
		if (xctxt)
			xmlXPathFreeContext(xctxt);
		if (*error || retval)
			goto bail;
	}
	g_set_error(error, LT_ERROR, LT_ERR_FAIL_ON_SCANNER,
		    "Invalid key for -u- extension: %s",
		    subtag);
  bail:
	lt_xml_unref(xml);

	return *error == NULL;
}
Пример #24
0
flickcurl_location*
flickcurl_build_location(flickcurl* fc, xmlXPathContextPtr xpathCtx,
                         const xmlChar* xpathExpr)
{
  flickcurl_location* location = NULL;
  int nodes_count;
  int i;
  xmlXPathObjectPtr xpathObj = NULL;
  xmlNodeSetPtr nodes;
  
  /* Now do location */
  xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
  if(!xpathObj) {
    flickcurl_error(fc, "Unable to evaluate XPath expression \"%s\"", 
                    xpathExpr);
    fc->failed = 1;
    goto tidy;
  }
  
  nodes = xpathObj->nodesetval;
  /* This is a max size - it can include nodes that are CDATA */
  nodes_count = xmlXPathNodeSetGetLength(nodes);
  
  for(i = 0; i < nodes_count; i++) {
    xmlNodePtr node = nodes->nodeTab[i];
    xmlAttr* attr;
    
    if(node->type != XML_ELEMENT_NODE) {
      flickcurl_error(fc, "Got unexpected node type %d", node->type);
      fc->failed = 1;
      break;
    }
    
    location = (flickcurl_location*)calloc(sizeof(flickcurl_location), 1);
    
    for(attr = node->properties; attr; attr = attr->next) {
      const char *attr_name = (const char*)attr->name;
      char *attr_value;
      size_t attr_value_len = strlen((const char*)attr->children->content);
      
      attr_value = (char*)malloc(attr_value_len + 1);
      memcpy(attr_value, attr->children->content, attr_value_len + 1);
      
      if(!strcmp(attr_name, "latitude"))
        location->latitude = atof(attr_value);
      else if(!strcmp(attr_name, "longitude"))
        location->longitude = atof(attr_value);
      else if(!strcmp(attr_name, "accuracy"))
        location->accuracy = atoi(attr_value);

      free(attr_value);
    }

    
#if FLICKCURL_DEBUG > 1
    fprintf(stderr, "location: lat %f long %f accuracy %d\n",
            location->latitude, location->longitude, location->accuracy);
#endif

    /* Handle only first perm */
    break;
  } /* for nodes */

 tidy:
  if(xpathObj)
    xmlXPathFreeObject(xpathObj);

  return location;
}
Пример #25
0
static gboolean
_lt_ext_ldml_u_lookup_type(lt_ext_ldml_u_data_t  *data,
			   const gchar           *subtag,
			   GError               **error)
{
	lt_xml_t *xml = NULL;
	xmlDocPtr doc;
	xmlXPathContextPtr xctxt = NULL;
	xmlXPathObjectPtr xobj = NULL;
	gint i, n;
	gchar key[4], *xpath_string = NULL;
	GList *l;
	GString *s;
	gboolean retval = FALSE;

	g_return_val_if_fail (data->current_type > 0, FALSE);

	l = g_list_last(data->tags);
	if (l == NULL) {
		g_set_error(error, LT_ERROR, LT_ERR_FAIL_ON_SCANNER,
			    "Invalid internal state. failed to find a key container.");
		goto bail;
	}
	s = l->data;
	strncpy(key, s->str, 2);
	key[2] = 0;

	xml = lt_xml_new();
	doc = lt_xml_get_cldr(xml, data->current_type);
	xctxt = xmlXPathNewContext(doc);
	if (!xctxt) {
		g_set_error(error, LT_ERROR, LT_ERR_OOM,
			    "Unable to create an instance of xmlXPathContextPtr.");
		goto bail;
	}
	xpath_string = g_strdup_printf("/ldmlBCP47/keyword/key[@name = '%s']", key);
	xobj = xmlXPathEvalExpression((const xmlChar *)xpath_string, xctxt);
	if (!xobj) {
		g_set_error(error, LT_ERROR, LT_ERR_FAIL_ON_XML,
			    "No valid elements for %s: %s",
			    doc->name, xpath_string);
		goto bail;
	}
	n = xmlXPathNodeSetGetLength(xobj->nodesetval);

	for (i = 0; i < n; i++) {
		xmlNodePtr ent = xmlXPathNodeSetItem(xobj->nodesetval, i);
		xmlNodePtr cnode;
		xmlChar *name;

		if (!ent) {
			g_set_error(error, 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 *)"type") == 0) {
				name = xmlGetProp(cnode, (const xmlChar *)"name");
				if (name && g_ascii_strcasecmp((const gchar *)name, subtag) == 0) {
					retval = TRUE;
					xmlFree(name);
					goto bail;
				} else if (g_strcmp0((const gchar *)name, "CODEPOINTS") == 0) {
					gsize len = strlen(subtag), j;
					static const gchar *hexdigit = "0123456789abcdefABCDEF";
					gchar *p;
					guint64 x;

					/* an exception to deal with the unicode code point. */
					if (len >= 4 && len <= 6) {
						for (j = 0; j < len; j++) {
							if (!strchr(hexdigit, subtag[j]))
								goto bail2;
						}
						x = g_ascii_strtoull(subtag, &p, 16);
						if (p && p[0] == 0 && x <= 0x10ffff) {
							retval = TRUE;
							xmlFree(name);
							goto bail;
						}
					}
				  bail2:;
				}
				xmlFree(name);
			} else if (xmlStrcmp(cnode->name, (const xmlChar *)"text") == 0) {
				/* ignore */
			} else {
				g_warning("Unknown node under /ldmlBCP47/keyword/key: %s", cnode->name);
			}
			cnode = cnode->next;
		}
	}
  bail:
	g_free(xpath_string);
	if (xobj)
		xmlXPathFreeObject(xobj);
	if (xctxt)
		xmlXPathFreeContext(xctxt);
	if (xml)
		lt_xml_unref(xml);

	return retval;
}
Пример #26
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;
}
Пример #27
0
static gboolean
fetch_tweets(gpointer 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) {
    goto leave;
  }
  if (http_status == 304) {
    goto leave;
  }
  if (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;
  int n, length = xmlXPathNodeSetGetLength(nodes);
  gchar* first_id = NULL;
  for(n = 0; n < length; n++) {
    char* id = NULL;
    char* user_id = NULL;
    char* icon = NULL;
    char* real = NULL;
    char* user_name = NULL;
    char* text = NULL;
    char* date = 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("created_at", (char*) status->name)) date = (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("name", (char*) user->name)) real = XML_CONTENT(user);
          if (!strcmp("screen_name", (char*) user->name)) user_name = XML_CONTENT(user);
          if (!strcmp("profile_image_url", (char*) user->name)) {
            icon = XML_CONTENT(user);
            icon = (char*) g_strchomp((gchar*) icon);
            icon = (char*) g_strchug((gchar*) icon);
          }
          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:
  if (body) free(body);
  if (path) xmlXPathFreeObject(path);
  if (ctx) xmlXPathFreeContext(ctx);
  if (doc) xmlFreeDoc(doc);
   
  g_timeout_add(1000 * length, fetch_tweets, NULL);
  return FALSE;
}
Пример #28
0
HRESULT queryresult_create(xmlNodePtr node, xmlChar* szQuery, IXMLDOMNodeList **out)
{
    queryresult *This = heap_alloc_zero(sizeof(queryresult));
    xmlXPathContextPtr ctxt = xmlXPathNewContext(node->doc);
    HRESULT hr;

    TRACE("(%p, %s, %p)\n", node, wine_dbgstr_a((char const*)szQuery), out);

    *out = NULL;
    if (This == NULL || ctxt == NULL || szQuery == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto cleanup;
    }

    This->lpVtbl = &queryresult_vtbl;
    This->ref = 1;
    This->resultPos = 0;
    This->node = node;
    xmldoc_add_ref(This->node->doc);

    ctxt->error = query_serror;
    ctxt->node = node;
    registerNamespaces(ctxt);

    if (is_xpathmode(This->node->doc))
    {
        xmlXPathRegisterAllFunctions(ctxt);
        This->result = xmlXPathEvalExpression(szQuery, ctxt);
    }
    else
    {
        xmlChar* xslpQuery = XSLPattern_to_XPath(ctxt, szQuery);

        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"not", xmlXPathNotFunction);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"boolean", xmlXPathBooleanFunction);

        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"index", XSLPattern_index);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"end", XSLPattern_end);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"nodeType", XSLPattern_nodeType);

        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IEq", XSLPattern_OP_IEq);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_INEq", XSLPattern_OP_INEq);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_ILt", XSLPattern_OP_ILt);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_ILEq", XSLPattern_OP_ILEq);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IGt", XSLPattern_OP_IGt);
        xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IGEq", XSLPattern_OP_IGEq);

        This->result = xmlXPathEvalExpression(xslpQuery, ctxt);
        xmlFree(xslpQuery);
    }

    if (!This->result || This->result->type != XPATH_NODESET)
    {
        hr = E_FAIL;
        goto cleanup;
    }

    init_dispex(&This->dispex, (IUnknown*)&This->lpVtbl, &queryresult_dispex);

    *out = (IXMLDOMNodeList *) &This->lpVtbl;
    hr = S_OK;
    TRACE("found %d matches\n", xmlXPathNodeSetGetLength(This->result->nodesetval));

cleanup:
    if (This != NULL && FAILED(hr))
        IXMLDOMNodeList_Release( (IXMLDOMNodeList*) &This->lpVtbl );
    xmlXPathFreeContext(ctxt);
    return hr;
}
Пример #29
0
int
__xmlXPathNodeSetGetLength(const xmlNodeSet * ns)

{
	return xmlXPathNodeSetGetLength(ns);
}
Пример #30
0
static gboolean
xmms_xspf_browse_add_entries (xmms_xform_t *xform, xmlDocPtr doc,
                              xmms_error_t *error)
{
	int i;
	xmlXPathContextPtr xpath;
	xmlXPathObjectPtr obj;
	const xmlChar *playlist_image = NULL;

	xpath = xmlXPathNewContext (doc);
	xmlXPathRegisterNs (xpath,
	                    BAD_CAST "xspf",
	                    BAD_CAST "http://xspf.org/ns/0/");

	if (!xmms_xspf_check_valid_xspf (doc, xpath, error)) {
		xmlXPathFreeContext (xpath);
		return FALSE;
	}

	obj = xmlXPathEvalExpression (BAD_CAST "/xspf:playlist[@version<=1]/xspf:image/text()/..",
	                              xpath);

	if (!obj) {
		xmms_error_set (error, XMMS_ERROR_INVAL,
		                "unable to evaluate xpath expression");
		xmlXPathFreeContext (xpath);
		return FALSE;
	}

	if (xmlXPathNodeSetGetLength (obj->nodesetval) == 1) {
		playlist_image = xmlXPathNodeSetItem (obj->nodesetval, 0)->children->content;
	}

	xmlXPathFreeObject (obj);
	obj = xmlXPathEvalExpression (BAD_CAST "/xspf:playlist[@version<=1]/xspf:trackList/xspf:track/xspf:location/text()/../..",
	                              xpath);

	if (!obj) {
		xmms_error_set (error, XMMS_ERROR_INVAL,
		                "unable to evaluate xpath expression");
		xmlXPathFreeContext (xpath);
		return FALSE;
	}

	for (i = 0; i < xmlXPathNodeSetGetLength (obj->nodesetval); i++) {
		xmms_xspf_track_t *track;
		GList *attr;

		track = xmms_xspf_parse_track_node (xform,
		                                    xmlXPathNodeSetItem (obj->nodesetval, i),
		                                    error);

		if (!track) {
			continue;
		}

		xmms_xform_browse_add_symlink (xform, NULL, track->location);

		if (playlist_image) {
			xmms_xform_browse_add_entry_property_str (xform, "image", (char *)playlist_image);
		}

		for (attr = track->attrs; attr; attr = g_list_next (attr)) {
			xmms_xform_browse_add_entry_property (xform,
			                                      ((xmms_xspf_track_attr_t *)attr->data)->key,
			                                      ((xmms_xspf_track_attr_t *)attr->data)->value);
		}

		g_list_free (track->attrs);
		g_free (track);
	}

	xmlXPathFreeObject (obj);
	xmlXPathFreeContext (xpath);
	return TRUE;
}