Exemplo n.º 1
0
/**
 * xsltDocumentFunction:
 * @ctxt:  the XPath Parser context
 * @nargs:  the number of arguments
 *
 * Implement the document() XSLT function
 *   node-set document(object, node-set?)
 */
void
xsltDocumentFunction(xmlXPathParserContextPtr ctxt, int nargs){
    xsltDocumentPtr doc;
    xmlXPathObjectPtr obj, obj2 = NULL;
    xmlChar *base = NULL, *URI;


    if ((nargs < 1) || (nargs > 2)) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
        xsltGenericError(xsltGenericErrorContext,
		"document() : invalid number of args %d\n", nargs);
	ctxt->error = XPATH_INVALID_ARITY;
	return;
    }
    if (ctxt->value == NULL) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
	xsltGenericError(xsltGenericErrorContext,
	    "document() : invalid arg value\n");
	ctxt->error = XPATH_INVALID_TYPE;
	return;
    }

    if (nargs == 2) {
	if (ctxt->value->type != XPATH_NODESET) {
	    xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt),
		                  NULL, NULL);
	    xsltGenericError(xsltGenericErrorContext,
		"document() : invalid arg expecting a nodeset\n");
	    ctxt->error = XPATH_INVALID_TYPE;
	    return;
	}

	obj2 = valuePop(ctxt);
    }

    if (ctxt->value->type == XPATH_NODESET) {
	int i;
	xmlXPathObjectPtr newobj, ret;

	obj = valuePop(ctxt);
	ret = xmlXPathNewNodeSet(NULL);

	if (obj->nodesetval) {
	    for (i = 0; i < obj->nodesetval->nodeNr; i++) {
		valuePush(ctxt,
			  xmlXPathNewNodeSet(obj->nodesetval->nodeTab[i]));
		xmlXPathStringFunction(ctxt, 1);
		if (nargs == 2) {
		    valuePush(ctxt, xmlXPathObjectCopy(obj2));
		} else {
		    valuePush(ctxt,
			      xmlXPathNewNodeSet(obj->nodesetval->nodeTab[i]));
		}
		xsltDocumentFunction(ctxt, 2);
		newobj = valuePop(ctxt);
		ret->nodesetval = xmlXPathNodeSetMerge(ret->nodesetval,
						       newobj->nodesetval);
		xmlXPathFreeObject(newobj);
	    }
	}

	xmlXPathFreeObject(obj);
	if (obj2 != NULL)
	    xmlXPathFreeObject(obj2);
	valuePush(ctxt, ret);
	return;
    }
    /*
     * Make sure it's converted to a string
     */
    xmlXPathStringFunction(ctxt, 1);
    if (ctxt->value->type != XPATH_STRING) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
	xsltGenericError(xsltGenericErrorContext,
	    "document() : invalid arg expecting a string\n");
	ctxt->error = XPATH_INVALID_TYPE;
	if (obj2 != NULL)
	    xmlXPathFreeObject(obj2);
	return;
    }
    obj = valuePop(ctxt);
    if (obj->stringval == NULL) {
	valuePush(ctxt, xmlXPathNewNodeSet(NULL));
    } else {
	if ((obj2 != NULL) && (obj2->nodesetval != NULL) &&
	    (obj2->nodesetval->nodeNr > 0) &&
	    IS_XSLT_REAL_NODE(obj2->nodesetval->nodeTab[0])) {
	    xmlNodePtr target;

	    target = obj2->nodesetval->nodeTab[0];
	    if (target->type == XML_ATTRIBUTE_NODE) {
		target = ((xmlAttrPtr) target)->parent;
	    }
	    base = xmlNodeGetBase(target->doc, target);
	} else {
	    xsltTransformContextPtr tctxt;
	    
	    tctxt = xsltXPathGetTransformContext(ctxt);
	    if ((tctxt != NULL) && (tctxt->inst != NULL)) {
		base = xmlNodeGetBase(tctxt->inst->doc, tctxt->inst);
	    } else if ((tctxt != NULL) && (tctxt->style != NULL) &&
		       (tctxt->style->doc != NULL)) {
		base = xmlNodeGetBase(tctxt->style->doc, 
			              (xmlNodePtr) tctxt->style->doc);
	    }
	}
	URI = xmlBuildURI(obj->stringval, base);
	if (base != NULL)
	    xmlFree(base);
        if (URI == NULL) {
	    valuePush(ctxt, xmlXPathNewNodeSet(NULL));
	} else {
	    xsltTransformContextPtr tctxt;

	    tctxt = xsltXPathGetTransformContext(ctxt);
	    if (tctxt == NULL) {
		xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt),
			              NULL, NULL);
		xsltGenericError(xsltGenericErrorContext,
			"document() : internal error tctxt == NULL\n");
		valuePush(ctxt, xmlXPathNewNodeSet(NULL));
	    } else {
                if (xmlStrEqual(tctxt->style->doc->URL, URI)) {
                    valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr)tctxt->style->doc));
                }
                else {
		    doc = xsltLoadDocument(tctxt, URI);
		    if (doc == NULL)
		        valuePush(ctxt, xmlXPathNewNodeSet(NULL));
		    else {
		        /* TODO: use XPointer of HTML location for fragment ID */
		        /* pbm #xxx can lead to location sets, not nodesets :-) */
		        valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) doc->doc));
		    }
                }
	    }
	    xmlFree(URI);
	}
    }
    xmlXPathFreeObject(obj);
    if (obj2 != NULL)
	xmlXPathFreeObject(obj2);
}
Exemplo n.º 2
0
static GConfValue*
schema_node_extract_value(xmlNodePtr node, const gchar** locales)
{
  GConfValue* value = NULL;
  gchar* owner_str;
  gchar* stype_str;
  gchar* list_type_str;
  gchar* car_type_str;
  gchar* cdr_type_str;
  GConfSchema* sc;
  xmlNodePtr iter;
  guint i;
  xmlNodePtr* localized_nodes;
  xmlNodePtr best = NULL;
  
  /* owner, type are for all locales;
     default value, descriptions are per-locale
  */

  owner_str = my_xmlGetProp(node, "owner");
  stype_str = my_xmlGetProp(node, "stype");
  list_type_str = my_xmlGetProp(node, "list_type");
  car_type_str = my_xmlGetProp(node, "car_type");
  cdr_type_str = my_xmlGetProp(node, "cdr_type");

  sc = gconf_schema_new();

  if (owner_str)
    {
      gconf_schema_set_owner(sc, owner_str);
      xmlFree(owner_str);
    }
  if (stype_str)
    {
      GConfValueType stype;
      stype = gconf_value_type_from_string(stype_str);
      gconf_schema_set_type(sc, stype);
      xmlFree(stype_str);
    }
  if (list_type_str)
    {
      GConfValueType type;
      type = gconf_value_type_from_string(list_type_str);
      gconf_schema_set_list_type(sc, type);
      xmlFree(list_type_str);
    }
  if (car_type_str)
    {
      GConfValueType type;
      type = gconf_value_type_from_string(car_type_str);
      gconf_schema_set_car_type(sc, type);
      xmlFree(car_type_str);
    }
  if (cdr_type_str)
    {
      GConfValueType type;
      type = gconf_value_type_from_string(cdr_type_str);
      gconf_schema_set_cdr_type(sc, type);
      xmlFree(cdr_type_str);
    }  
  
  if (locales != NULL && locales[0])
    {
      /* count the number of possible locales */
      int n_locales;
      
      n_locales = 0;
      while (locales[n_locales])
        ++n_locales;
      
      localized_nodes = g_new0(xmlNodePtr, n_locales);
      
      /* Find the node for each possible locale */
      iter = node->xmlChildrenNode;
      
      while (iter != NULL)
        {
          if (iter->type == XML_ELEMENT_NODE &&
              strcmp((char *)iter->name, "local_schema") == 0)
            {
              char* locale_name;
              
              locale_name = my_xmlGetProp(iter, "locale");
              
              if (locale_name != NULL)
                {
                  i = 0;
                  while (locales[i])
                    {
                      if (strcmp(locales[i], locale_name) == 0)
                        {
                          localized_nodes[i] = iter;
                          break;
                        }
                      ++i;
                    }

                  xmlFree(locale_name);
                  
                  /* Quit as soon as we have the best possible locale */
                  if (localized_nodes[0] != NULL)
                    break;
                }
            }
          
          iter = iter->next;
        }

      /* See which is the best locale we managed to load, they are in
         order of preference. */
      
      i = 0;
      best = localized_nodes[i];
      while (best == NULL && i < n_locales)
        {
          best = localized_nodes[i];
          ++i;
        }
      
      g_free(localized_nodes);
    }

  /* If no locale matched, try picking the the null localization,
   * and then try picking the first node
   */
  if (best == NULL)
    best = find_schema_subnode_by_locale (node, NULL);

  if (best == NULL)
    {
      best = node->xmlChildrenNode;
      while (best && best->type != XML_ELEMENT_NODE)
        best = best->next;
    }
  
  /* Extract info from the best locale node */
  if (best != NULL)
    schema_subnode_extract_data(best, sc); 
  
  /* Create a GConfValue with this schema and return it */
  value = gconf_value_new(GCONF_VALUE_SCHEMA);
      
  gconf_value_set_schema_nocopy(value, sc);

  return value;
}
Exemplo n.º 3
0
static Log4gAppender *
parse_appender(Log4gConfigurator *base, xmlNodePtr node)
{
	xmlChar *name = NULL;
	Log4gAppender *appender = NULL;
	struct Private *priv = GET_PRIVATE(base);
	xmlChar *type = xmlGetProp(node, (const xmlChar *)"type");
	if (type) {
		GType gtype = g_type_from_name((const gchar *)type);
		if (!gtype) {
			log4g_log_error(Q_("%s: invalid `type'"), type);
			goto exit;
		}
		if (!G_TYPE_IS_INSTANTIATABLE(gtype)) {
			log4g_log_error(Q_("%s: is a non-instantiable type"),
					type);
			goto exit;
		}
		appender = g_object_new(gtype, NULL);
		if (!appender) {
			log4g_log_error(Q_("%s: g_object_new() returned NULL"),
					type);
			goto exit;
		}
		if (!LOG4G_IS_APPENDER(appender)) {
			log4g_log_error(Q_("%s: not an instance of "
						"Log4gAppender"), type);
			g_object_unref(appender);
			appender = NULL;
			goto exit;
		}
	}
	name = xmlGetProp(node, (const xmlChar *)"name");
	if (appender) {
		if (name) {
			g_object_ref(appender);
			g_hash_table_insert(priv->appenders, name, appender);
			name = NULL;
		}
	} else {
		if (name) {
			appender = LOG4G_APPENDER(g_hash_table_lookup(
						priv->appenders, name));
			if (!appender) {
				log4g_log_error(Q_("%s: no such appender"),
						name);
				goto exit;
			}
			g_object_ref(appender);
		} else {
			log4g_log_error(Q_("appenders without a `type' must "
						"have a `name'"));
			goto exit;
		}
	}
	node = node->xmlChildrenNode;
	while (node) {
		if (!xmlStrcmp(node->name, (const xmlChar *)"property")) {
			parse_property(base, node, appender);
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"layout")) {
			Log4gLayout *layout = parse_layout(base, node);
			if (layout) {
				log4g_appender_set_layout(appender, layout);
				g_object_unref(layout);
			}
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"filter")) {
			Log4gFilter *filter = parse_filter(base, node);
			if (filter) {
				log4g_appender_add_filter(appender, filter);
				g_object_unref(filter);
			}
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"appender")) {
			if (LOG4G_IS_APPENDER_ATTACHABLE(appender)) {
				Log4gAppender *child =
					parse_appender(base, node);
				if (child) {
					log4g_appender_attachable_add_appender(
							LOG4G_APPENDER_ATTACHABLE(appender),
							child);
					g_object_unref(child);
				}
			} else {
				log4g_log_error(Q_("%s: does not implement "
							"log4g_appender_attachable"),
						type);
			}
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"text")) {
			log4g_log_warn(Q_("invalid text element"));
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"comment")) {
			/* do nothing */
		} else {
			log4g_log_warn(Q_("%s: invalid element"), node->name);
		}
		node = node->next;
	}
	if (log4g_appender_requires_layout(appender)
			&& !log4g_appender_get_layout(appender)) {
		log4g_log_error(Q_("%s: appender requires a layout"), type);
		g_hash_table_remove(priv->appenders,
				log4g_appender_get_name(appender));
		g_object_unref(appender);
		appender = NULL;
		goto exit;
	}
	log4g_appender_activate_options(appender);
exit:
	if (type) {
		xmlFree(type);
	}
	if (name) {
		xmlFree(name);
	}
	return appender;
}
Exemplo n.º 4
0
int main(int argc, char **argv)
{
    char logpath[FILENAME_MAX];
    int log;

    if (argc != 2) 
    {
        fprintf(stderr, PACKAGE_STRING "\n"
                "  (c) Copyright 2001-2004 The IceS Development Team <*****@*****.**>\n"
                "        Michael Smith <*****@*****.**>\n"
                "        Karl Heyes    <*****@*****.**>\n"
                "        and others\n"
                "\n"
                "Usage: \"ices config.xml\"\n");
        return 1;
    }

    config_initialize();

    if (config_read(argv[1]) <= 0) 
    {
        fprintf(stderr, "Failed to read config file \"%s\"\n", argv[1]);
        goto fail;
    }
    if (ices_config->background)
    {
        int ret = 0;
        /* Start up new session, to lose old session and process group */
        switch (fork())
        {
        case 0: break; /* child continues */
        case -1: perror ("fork"); ret = -1;
        default:
            exit (ret);
        }

        /* Disassociate process group and controlling terminal */ 
        setsid();

        /* Become a NON-session leader so that a */
        /* control terminal can't be reacquired */
        switch (fork())
        {
        case 0: break; /* child continues */
        case -1: perror ("fork"); ret = -1;
        default:
            exit (ret);
        }
    }
    
    log_initialize();
    thread_initialize();
    shout_init();
    encode_init();
    signals_setup();

    snprintf(logpath, FILENAME_MAX, "%s/%s", ices_config->logpath, 
            ices_config->logfile);
    if(ices_config->log_stderr)
        log = log_open_file(stderr);
    else
    {
        log = log_open(logpath);
        if (log < 0)
            fprintf (stderr, "unable to open log %s\n", logpath);
        log_set_trigger (log, ices_config->logsize);
    }
    /* Set the log level, if requested - defaults to 2 (WARN) otherwise */
    if (ices_config->loglevel)
        log_set_level(log, ices_config->loglevel);

    ices_config->log_id = log;

    LOG_INFO0(PACKAGE_STRING " started...");
    if (ices_config->pidfile != NULL)
    {
        FILE *f = fopen (ices_config->pidfile, "w");
        if (f)
        {
            fprintf (f, "%i", getpid());
            fclose (f);
        }
        else
        {
            LOG_WARN1("pidfile \"%s\" cannot be written to", ices_config->pidfile);
            xmlFree (ices_config->pidfile);
            ices_config->pidfile = NULL;
        }
    }

    /* Start the core streaming loop */
    input_loop();

    if (ices_config->pidfile)
        remove (ices_config->pidfile);

    LOG_INFO0("Shutdown complete");

    log_close(log);

 fail:
    encode_close();
    shout_shutdown();
    config_shutdown();
    thread_shutdown();
    log_shutdown();

    return 0;
}
Exemplo n.º 5
0
static void
node_set_value(xmlNodePtr node, GConfValue* value)
{
  const gchar* type;
  gchar* value_str;

  g_return_if_fail(node != NULL);
  g_return_if_fail(value != NULL);
  g_return_if_fail(value->type != GCONF_VALUE_INVALID);
  
  type = gconf_value_type_to_string(value->type);

  g_assert(type != NULL);
  
  my_xmlSetProp(node, "type", type);

  switch (value->type)
    {
    case GCONF_VALUE_INT:
    case GCONF_VALUE_FLOAT:
    case GCONF_VALUE_BOOL:
      free_childs(node);
      
      value_str = gconf_value_to_string(value);
  
      my_xmlSetProp(node, "value", value_str);

      g_free(value_str);
      break;
    case GCONF_VALUE_STRING:
      {
        xmlChar* encoded;
        
        free_childs(node);

        encoded = xmlEncodeEntitiesReentrant(node->doc,
                                             (xmlChar *)gconf_value_get_string(value));
        
        xmlNewChild(node, NULL, (xmlChar *)"stringvalue",
                    encoded);
        xmlFree(encoded);
      }
      break;      
    case GCONF_VALUE_SCHEMA:
      {
        node_set_schema_value(node, value);
      }
      break;
    case GCONF_VALUE_LIST:
      {
        GSList* list;

        free_childs(node);

        my_xmlSetProp(node, "ltype",
                      gconf_value_type_to_string(gconf_value_get_list_type(value)));
        
        /* Add a new child for each node */
        list = gconf_value_get_list(value);

        while (list != NULL)
          {
            xmlNodePtr child;
            /* this is O(1) because libxml saves the list tail */
            child = xmlNewChild(node, NULL, (xmlChar *)"li", NULL);

            g_return_if_fail(list->data != NULL);
            
            node_set_value(child, (GConfValue*)list->data);
            
            list = g_slist_next(list);
          }
      }
      break;
      
    case GCONF_VALUE_PAIR:
      {
        xmlNodePtr car, cdr;

        free_childs(node);

        car = xmlNewChild(node, NULL, (xmlChar *)"car", NULL);
        cdr = xmlNewChild(node, NULL, (xmlChar *)"cdr", NULL);

        g_return_if_fail(gconf_value_get_car(value) != NULL);
        g_return_if_fail(gconf_value_get_cdr(value) != NULL);
        
        node_set_value(car, gconf_value_get_car(value));
        node_set_value(cdr, gconf_value_get_cdr(value));
      }
      break;
      
    default:
      g_assert_not_reached();
      break;
    }
}
Exemplo n.º 6
0
void timer_send_notify(unsigned int ticks,void *param)
{
	db_key_t query_cols[2], update_cols[1], result_cols[7];
	db_val_t query_vals[2], update_vals[1];
	int did_col, resource_uri_col, auth_state_col, reason_col,
		body_col, ctype_col;
	int n_result_cols= 0, i;
	db_res_t *result= NULL;
	char* prev_did= NULL, * curr_did= NULL;
	db_row_t *row;	
	db_val_t *row_vals;
	char* resource_uri;
	str body;
	str callid, to_tag, from_tag;
	xmlDocPtr rlmi_doc= NULL;
	xmlNodePtr list_node= NULL, instance_node= NULL, resource_node;
	unsigned int hash_code= 0;
	int len;
	int size= BUF_REALLOC_SIZE, buf_len= 0;
	char* buf= NULL, *auth_state= NULL;
	int contor= 0, auth_state_flag;
	str bstr= {0, 0};
	str rlmi_cont= {0, 0}, multi_cont;
	subs_t* s, *dialog= NULL;
	char* rl_uri= NULL;
	char* str_aux = NULL;
	str ctype, cid;
	int add_len;

	query_cols[0]= &str_updated_col;
	query_vals[0].type = DB_INT;
	query_vals[0].nul = 0;
	query_vals[0].val.int_val= UPDATED_TYPE; 

	result_cols[did_col= n_result_cols++]= &str_rlsubs_did_col;
	result_cols[resource_uri_col= n_result_cols++]= &str_resource_uri_col;
	result_cols[auth_state_col= n_result_cols++]= &str_auth_state_col;
	result_cols[ctype_col= n_result_cols++]= &str_content_type_col;
	result_cols[reason_col= n_result_cols++]= &str_reason_col;
	result_cols[body_col= n_result_cols++]= &str_presence_state_col;

	/* query in alfabetical order after rlsusbs_did 
	 * (resource list Subscribe dialog indentifier)*/

	if (rls_dbf.use_table(rls_db, &rlpres_table) < 0) 
	{
		LM_ERR("in use_table\n");
		goto done;
	}

	if(rls_dbf.query(rls_db, query_cols, 0, query_vals, result_cols,
					1, n_result_cols, &str_rlsubs_did_col, &result)< 0)
	{
		LM_ERR("in sql query\n");
		goto done;
	}
	if(result== NULL || result->n<= 0)
		goto done;

	/* update the rlpres table */
	update_cols[0]= &str_updated_col;
	update_vals[0].type = DB_INT;
	update_vals[0].nul = 0;
	update_vals[0].val.int_val= NO_UPDATE_TYPE; 

	if (rls_dbf.use_table(rls_db, &rlpres_table) < 0) 
	{
		LM_ERR("in use_table\n");
		goto error;
	}
	if(rls_dbf.update(rls_db, query_cols, 0, query_vals, update_cols,
					update_vals, 1, 1)< 0)
	{
		LM_ERR("in sql update\n");
		goto error;
	}

	/* generate the boundary string */

	bstr.s= generate_string((int)time(NULL), BOUNDARY_STRING_LEN);
	if(bstr.s == NULL)
	{
		LM_ERR("failed to generate random string\n");
		goto error;
	}
	bstr.len= strlen(bstr.s);

	/* for the multipart body , use here also an initial allocated
	 * and reallocated on need buffer */
	buf= pkg_malloc(size);
	if(buf== NULL)
	{
		ERR_MEM(PKG_MEM_STR);
	}

	LM_DBG("found %d records with updated state\n", result->n);
	for(i= 0; i< result->n; i++)
	{
		row = &result->rows[i];
		row_vals = ROW_VALUES(row);
		
		curr_did=     (char*)row_vals[did_col].val.string_val;
		resource_uri= (char*)row_vals[resource_uri_col].val.string_val;
		auth_state_flag=     row_vals[auth_state_col].val.int_val;
		body.s=   (char*)row_vals[body_col].val.string_val;
		body.len= strlen(body.s);
		ctype.s = (char*)row_vals[ctype_col].val.string_val;
		ctype.len = strlen(ctype.s);

		/* if all the info for one dialog have been collected -> send notify */
		/* the 'dialog' variable must be filled with the dialog info */
		/* 'buf' must contain the body */
		if(prev_did!= NULL && strcmp(prev_did, curr_did)) 
		{
			xmlDocDumpMemory(rlmi_doc,(xmlChar**)(void*)&rlmi_cont.s,
				&rlmi_cont.len);
		
			multi_cont.s= buf;
			multi_cont.len= buf_len;
			 
			if(agg_body_sendn_update(&dialog->pres_uri, bstr, &rlmi_cont, 
						 (buf_len==0)?NULL:&multi_cont, dialog, hash_code)<0)
			 {
				 LM_ERR("in function agg_body_sendn_update\n");
				 goto error;
			 }
			xmlFree(rlmi_cont.s);

			xmlFreeDoc(rlmi_doc);
			rlmi_doc= NULL;
			pkg_free(rl_uri);
			rl_uri= NULL;
			pkg_free(dialog);
			dialog= NULL;
		}

		/* for the new dialog -> search the dialog info and 
		 * fill the dialog structure and start a new rlmi document */
		if(prev_did== NULL || strcmp(prev_did, curr_did)) 
		{
			/* search the subscription in rlsubs_table*/
			if( parse_rlsubs_did(curr_did, &callid, &from_tag, &to_tag)< 0)
			{
				LM_ERR("bad format for "
					"resource list Subscribe dialog indentifier(rlsubs did)\n");
				prev_did = NULL;
				continue;

			}
			hash_code= core_hash(&callid, &to_tag, hash_size);
		
			lock_get(&rls_table[hash_code].lock);
			s= pres_search_shtable(rls_table,callid,to_tag,from_tag,hash_code);
			if(s== NULL)
			{
				LM_DBG("record not found in hash_table [rlsubs_did]= %s\n",
						curr_did);
				LM_DBG("callid= %.*s\tfrom_tag= %.*s\tto_tag= %.*s\n",
						callid.len, callid.s,from_tag.len,from_tag.s,
						to_tag.len,to_tag.s);
				lock_release(&rls_table[hash_code].lock);
				prev_did = NULL;
				continue;
			}
			LM_DBG("Found rl-subs record in hash table\n");
					
			/* save dialog info and rl_uri*/
			dialog= pres_copy_subs(s, PKG_MEM_TYPE);
			if(dialog== NULL)
			{	
				LM_ERR("while copying subs_t structure\n");
				lock_release(&rls_table[hash_code].lock);
				goto done;
			}
			dialog->expires-= (int)time(NULL);
			lock_release(&rls_table[hash_code].lock);

			/* make new rlmi and multipart documents */
			rlmi_doc= xmlNewDoc(BAD_CAST "1.0");
			if(rlmi_doc== NULL)
			{
				LM_ERR("when creating new xml doc\n");
				goto done;
			}
			list_node= xmlNewNode(NULL, BAD_CAST "list");
			if(list_node== NULL)
			{
				LM_ERR("while creating new xml node\n");
				goto done;
			}
			rl_uri= (char*)pkg_malloc((dialog->pres_uri.len+ 1)* sizeof(char));
			if(rl_uri==  NULL)
			{
				ERR_MEM(PKG_MEM_STR);
			}
			memcpy(rl_uri, dialog->pres_uri.s, dialog->pres_uri.len);
			rl_uri[dialog->pres_uri.len]= '\0';

			xmlNewProp(list_node, BAD_CAST "uri", BAD_CAST rl_uri);
			xmlNewProp(list_node, BAD_CAST "xmlns", BAD_CAST "urn:ietf:params:xml:ns:rlmi");
			xmlNewProp(list_node, BAD_CAST "version", BAD_CAST int2str(dialog->version, &len));
			xmlNewProp(list_node, BAD_CAST "fullState", BAD_CAST "false");

			xmlDocSetRootElement(rlmi_doc, list_node);
			buf_len= 0;

			/* !!!! for now I will include the auth state without checking if 
			 * it has changed - > in future chech if it works */		
		}		

		/* add a node in rlmi_doc and if any presence state registered add 
		 * it in the buffer */
		
		resource_node= xmlNewChild(list_node,NULL,BAD_CAST "resource", NULL);
		if(resource_node== NULL)
		{
			LM_ERR("when adding resource child\n");
			goto done;
		}
		xmlNewProp(resource_node, BAD_CAST "uri", BAD_CAST resource_uri);
			
		/* there might be more records with the same uri- more instances-
		 * search and add them all */
		
		contor= 0;
		while(1)
		{
			contor++;
			cid.s= NULL;
			instance_node= xmlNewChild(resource_node, NULL, 
					BAD_CAST "instance", NULL);
			if(instance_node== NULL)
			{
				LM_ERR("while adding instance child\n");
				goto error;
			}
			str_aux = generate_string(contor, 8);
			if(str_aux == NULL)
			{
				LM_ERR("failed to create random string\n");
				goto error;
			}
			xmlNewProp(instance_node, BAD_CAST "id",
					BAD_CAST str_aux);
			pkg_free(str_aux);

			auth_state= get_auth_string(auth_state_flag);
			if(auth_state== NULL)
			{
				LM_ERR("bad authorization status flag\n");
				goto error;
			}
			xmlNewProp(instance_node, BAD_CAST "state", BAD_CAST auth_state);
		
			if(auth_state_flag & ACTIVE_STATE)
			{
				cid.s= generate_cid(resource_uri, strlen(resource_uri));
				cid.len = strlen(cid.s);
				xmlNewProp(instance_node, BAD_CAST "cid", BAD_CAST cid.s);
			}
			else
			if(auth_state_flag & TERMINATED_STATE)
			{
				xmlNewProp(instance_node, BAD_CAST "reason",
					BAD_CAST row_vals[resource_uri_col].val.string_val);
			}
		
			/* add in the multipart buffer */
			if(cid.s)
			{
				APPEND_MULTIPART_BODY();
				pkg_free(cid.s);
				cid.s = NULL;
			}

			i++;
			if(i== result->n)
			{
				i--;
				break;
			}

			row = &result->rows[i];
			row_vals = ROW_VALUES(row);
	
			if(strncmp(row_vals[resource_uri_col].val.string_val,resource_uri,
					strlen(resource_uri)) || strncmp(curr_did, 
					row_vals[did_col].val.string_val, strlen(curr_did)))
			{
				i--;
				break;
			}
			resource_uri= (char*)row_vals[resource_uri_col].val.string_val;
			auth_state_flag=     row_vals[auth_state_col].val.int_val;
			body.s=   (char*)row_vals[body_col].val.string_val;
			body.len = strlen(body.s);
		}

		prev_did= curr_did;
	}

	if(rlmi_doc)
	{
		xmlDocDumpMemory( rlmi_doc,(xmlChar**)(void*)&rlmi_cont.s,
		&rlmi_cont.len);
		
		multi_cont.s= buf;
		multi_cont.len= buf_len;
	
		 if(agg_body_sendn_update(&dialog->pres_uri, bstr, &rlmi_cont, 
			 (buf_len==0)?NULL:&multi_cont, dialog, hash_code)<0)
		 {
			 LM_ERR("in function agg_body_sendn_update\n");
			 goto error;
		}
		xmlFree(rlmi_cont.s);
		pkg_free(rl_uri);
		rl_uri= NULL;
		pkg_free(dialog);
		dialog= NULL;
	}

error:
done:
	if(result)
		rls_dbf.free_result(rls_db, result);
	if(rlmi_doc)
		xmlFreeDoc(rlmi_doc);
	if(rl_uri)
		pkg_free(rl_uri);
	if(bstr.s)
		pkg_free(bstr.s);
		
	if(buf)
		pkg_free(buf);
	if(dialog)
		pkg_free(dialog);
	return;
}
Exemplo n.º 7
0
static int
xmlSecTransformXPath2NodeRead(xmlSecTransformPtr transform, xmlNodePtr node, xmlSecTransformCtxPtr transformCtx) {
    xmlSecPtrListPtr dataList;
    xmlSecXPathDataPtr data;
    xmlNodePtr cur;
    xmlChar* op;
    int ret;

    xmlSecAssert2(xmlSecTransformCheckId(transform, xmlSecTransformXPath2Id), -1);
    xmlSecAssert2(node != NULL, -1);
    xmlSecAssert2(transformCtx != NULL, -1);

    dataList = xmlSecXPathTransformGetDataList(transform);
    xmlSecAssert2(xmlSecPtrListCheckId(dataList, xmlSecXPathDataListId), -1);
    xmlSecAssert2(xmlSecPtrListGetSize(dataList) == 0, -1);

    /* There are only xpath nodes */
    cur = xmlSecGetNextElementNode(node->children);
    while((cur != NULL) && xmlSecCheckNodeName(cur, xmlSecNodeXPath2, xmlSecXPath2Ns)) {
        /* read information from the node */
        data = xmlSecXPathDataCreate(xmlSecXPathDataTypeXPath2);
        if(data == NULL) {
            xmlSecInternalError("xmlSecXPathDataCreate",
                                xmlSecTransformGetName(transform));
            return(-1);
        }

        ret = xmlSecXPathDataNodeRead(data, cur);
        if(ret < 0) {
            xmlSecInternalError("xmlSecXPathDataNodeRead",
                                xmlSecTransformGetName(transform));
            xmlSecXPathDataDestroy(data);
            return(-1);
        }

        /* append it to the list */
        ret = xmlSecPtrListAdd(dataList, data);
        if(ret < 0) {
            xmlSecInternalError("xmlSecPtrListAdd",
                                xmlSecTransformGetName(transform));
            xmlSecXPathDataDestroy(data);
            return(-1);
        }

        /* set correct node set type and operation */
        data->nodeSetType = xmlSecNodeSetTree;
        op = xmlGetProp(cur, xmlSecAttrFilter);
        if(op == NULL) {
            xmlSecInvalidNodeAttributeError(cur, xmlSecAttrFilter,
                                            xmlSecTransformGetName(transform),
                                            "empty");
            return(-1);
        }
        if(xmlStrEqual(op, xmlSecXPath2FilterIntersect)) {
            data->nodeSetOp = xmlSecNodeSetIntersection;
        } else if(xmlStrEqual(op, xmlSecXPath2FilterSubtract)) {
            data->nodeSetOp = xmlSecNodeSetSubtraction;
        } else if(xmlStrEqual(op, xmlSecXPath2FilterUnion)) {
            data->nodeSetOp = xmlSecNodeSetUnion;
        } else {
            xmlSecInvalidNodeAttributeError(cur, xmlSecAttrFilter,
                                            xmlSecTransformGetName(transform),
                                            "unknown");
            xmlFree(op);
            return(-1);
        }
        xmlFree(op);

        cur = xmlSecGetNextElementNode(cur->next);
    }

    /* check that we have nothing else */
    if(cur != NULL) {
        xmlSecUnexpectedNodeError(cur, xmlSecTransformGetName(transform));
        return(-1);
    }
    return(0);
}
/**
 * xsltAttributeInternal:
 * @ctxt:  a XSLT process context
 * @node:  the node in the source tree.
 * @inst:  the xsl:attribute element
 * @comp:  precomputed information
 * @fromAttributeSet:  the attribute comes from an attribute-set
 *
 * Process the xslt attribute node on the source node
 */
static void
xsltAttributeInternal(xsltTransformContextPtr ctxt, xmlNodePtr node,
                      xmlNodePtr inst,
		      xsltStylePreCompPtr castedComp,
                      int fromAttributeSet) {
#ifdef XSLT_REFACTORED
    xsltStyleItemAttributePtr comp =
	(xsltStyleItemAttributePtr) castedComp;
    /*
    * TODO: Change the fields of the compiled struct:
    *  1) @name (char)
    *  2) @nameType (String, AVT)
    *  3) @nsName (char)
    *  4) nsNameType (None, String, AVT)
    */
#else
    xsltStylePreCompPtr comp = castedComp;
#endif
    xmlNodePtr targetElem;
    xmlChar *prop = NULL;    
    const xmlChar *name = NULL, *prefix = NULL, *nsName = NULL;
    xmlChar *value = NULL;
    xmlNsPtr ns = NULL;
    xmlAttrPtr attr;    

    if ((ctxt == NULL) || (node == NULL) || (inst == NULL))
        return;
    /*
    * BIG NOTE: This previously used xsltGetSpecialNamespace() and
    *  xsltGetNamespace(), but since both are not appropriate, we
    *  will process namespace lookup here to avoid adding yet another
    *  ns-lookup function to namespaces.c.
    */
    /*
    * SPEC XSLT 1.0: Error cases:
    * - Creating nodes other than text nodes during the instantiation of
    *   the content of the xsl:attribute element; implementations may
    *   either signal the error or ignore the offending nodes."
    */

    if (comp == NULL) {
        xsltTransformError(ctxt, NULL, inst,
	    "Internal error in xsltAttributeInternal(): "
	    "The instruction was no compiled.\n");
        return;
    }    
    /*
    * TODO: Shouldn't ctxt->insert == NULL be treated as an internal error?
    *   So report an internal error?
    */
    if (ctxt->insert == NULL)
        return;    
    /*
    * SPEC XSLT 1.0:
    *  "Adding an attribute to a node that is not an element;
    *  implementations may either signal the error or ignore the attribute."
    *
    * TODO: I think we should signal such errors in the future, and maybe
    *  provide an option to ignore such errors.
    */
    targetElem = ctxt->insert;
    if (targetElem->type != XML_ELEMENT_NODE)
	return;
    
    /*
    * SPEC XSLT 1.0:
    * "Adding an attribute to an element after children have been added
    *  to it; implementations may either signal the error or ignore the
    *  attribute."
    *
    * TODO: We should decide whether not to report such errors or
    *  to ignore them; note that we *ignore* if the parent is not an
    *  element, but here we report an error.
    */
    if (targetElem->children != NULL) {
	/*
	* NOTE: Ah! This seems to be intended to support streamed
	*  result generation!.
	*/
        xsltTransformError(ctxt, NULL, inst,
	    "xsl:attribute: Cannot add attributes to an "
	    "element if children have been already added "
	    "to the element.\n");
        return;
    }

    /*
    * Process the name
    * ----------------
    */
    if (!comp->has_name) /* TODO: raise error */
        return;

#ifdef WITH_DEBUGGER
    if (ctxt->debugStatus != XSLT_DEBUG_NONE)
        xslHandleDebugger(inst, node, NULL, ctxt);
#endif

    if (comp->name == NULL) {
	/* TODO: fix attr acquisition wrt to the XSLT namespace */
        prop = xsltEvalAttrValueTemplate(ctxt, inst,
	    (const xmlChar *) "name", XSLT_NAMESPACE);
        if (prop == NULL) {
            xsltTransformError(ctxt, NULL, inst,
		"xsl:attribute: The attribute 'name' is missing.\n");
            goto error;
        }
	if (xmlValidateQName(prop, 0)) {
	    xsltTransformError(ctxt, NULL, inst,
		"xsl:attribute: The effective name '%s' is not a "
		"valid QName.\n", prop);
	    /* we fall through to catch any further errors, if possible */
	}
	name = xsltSplitQName(ctxt->dict, prop, &prefix);
	xmlFree(prop);
    } else {
	name = xsltSplitQName(ctxt->dict, comp->name, &prefix);
    }

    if (!xmlStrncasecmp(prefix, (xmlChar *) "xmlns", 5)) {
#ifdef WITH_XSLT_DEBUG_PARSING
        xsltGenericDebug(xsltGenericDebugContext,
	    "xsltAttribute: xmlns prefix forbidden\n");
#endif
	/*
	* SPEC XSLT 1.0:
	*  "It is an error if the string that results from instantiating
	*  the attribute value template is not a QName or is the string
	*  xmlns. An XSLT processor may signal the error; if it does not
	*  signal the error, it must recover by not adding the attribute
	*  to the result tree."
	* TODO: Decide which way to go here.
	*/
        goto error;
    }
    /*
    * Process namespace semantics
    * ---------------------------
    *
    * Evaluate the namespace name.
    */
    if (comp->has_ns) {	 
	if (comp->ns != NULL) {
	    if (comp->ns[0] != 0)
		nsName = comp->ns;
	} else {
	    xmlChar *tmpNsName;
	    /*
	    * Eval the AVT.
	    */
	    /* TODO: check attr acquisition wrt to the XSLT namespace */
	    tmpNsName = xsltEvalAttrValueTemplate(ctxt, inst,
		(const xmlChar *) "namespace", XSLT_NAMESPACE);	
	    /*
	    * This fixes bug #302020: The AVT might also evaluate to the 
	    * empty string; this means that the empty string also indicates
	    * "no namespace".
	    * SPEC XSLT 1.0:
	    *  "If the string is empty, then the expanded-name of the
	    *  attribute has a null namespace URI."
	    */
	    if ((tmpNsName != NULL) && (tmpNsName[0] != 0))
		nsName = xmlDictLookup(ctxt->dict, BAD_CAST tmpNsName, -1);
	    xmlFree(tmpNsName);		
	};	    
    } else if (prefix != NULL) {
	/*
	* SPEC XSLT 1.0:
	*  "If the namespace attribute is not present, then the QName is
	*  expanded into an expanded-name using the namespace declarations
	*  in effect for the xsl:attribute element, *not* including any
	*  default namespace declaration."
	*/	
	ns = xmlSearchNs(inst->doc, inst, prefix);
	if (ns == NULL) {
	    /*
	    * Note that this is treated as an error now (checked with
	    *  Saxon, Xalan-J and MSXML).
	    */
	    xsltTransformError(ctxt, NULL, inst,
		"xsl:attribute: The effective prefix '%s', has no "
		"namespace binding in scope in the stylesheet; "
		"this is an error, since the namespace was not "
		"specified by the instruction itself.\n", prefix);
	} else
	    nsName = ns->href;	
    }

    if (fromAttributeSet) {
	/*
	* I think this tries to ensure that xsl:attribute(s) coming
	* from an xsl:attribute-set won't override attribute of
	* literal result elements or of explicit xsl:attribute(s).
	*/
	attr = xmlHasNsProp(targetElem, name, nsName);
	if (attr != NULL)
	    return;
    }

    /*
    * Something about ns-prefixes:
    * SPEC XSLT 1.0:
    *  "XSLT processors may make use of the prefix of the QName specified
    *  in the name attribute when selecting the prefix used for outputting
    *  the created attribute as XML; however, they are not required to do
    *  so and, if the prefix is xmlns, they must not do so"
    */        
    /*
    * Find/create a matching ns-decl in the result tree.
    */
    ns = NULL;
#if 0
    if (0) {	
	/*
	* OPTIMIZE TODO: How do we know if we are adding to a
	*  fragment or not?
	*
	* If we are adding to a result tree fragment (i.e., not to the
	* actual result tree), we'll don't bother searching for the
	* ns-decl, but just store it in the dummy-doc of the result
	* tree fragment.
	*/
	if (nsName != NULL) {
	    ns = xsltTreeAcquireStoredNs(ctxt->document->doc, nsName,
		prefix);
	}
    }
#endif
    if (nsName != NULL) {
	/*
	* The owner-element might be in the same namespace.
	*/
	if ((targetElem->ns != NULL) &&
	    (targetElem->ns->prefix != NULL) &&	    
	    xmlStrEqual(targetElem->ns->href, nsName))
	{
	    ns = targetElem->ns;
	    goto namespace_finished;
	}
	if (prefix != NULL) {
	    /*
	    * Search by ns-prefix.
	    */
	    ns = xmlSearchNs(targetElem->doc, targetElem, prefix);
	    if ((ns != NULL) && (xmlStrEqual(ns->href, nsName))) {
		goto namespace_finished;
	    }
	}
	/*
	* Fallback to a search by ns-name.
	*/	
	ns = xmlSearchNsByHref(targetElem->doc, targetElem, nsName);
	if ((ns != NULL) && (ns->prefix != NULL)) {
	    goto namespace_finished;
	}
	/*
	* OK, we need to declare the namespace on the target element.
	*/
	if (prefix) {
	    if (targetElem->nsDef != NULL) {
		ns = targetElem->nsDef;
		do {
		    if ((ns->prefix) && xmlStrEqual(ns->prefix, prefix)) {
			/*
			* The prefix is aready occupied.
			*/
			break;
		    }
		    ns = ns->next;
		} while (ns != NULL);
		if (ns == NULL) {
		    ns = xmlNewNs(targetElem, nsName, prefix);
		    goto namespace_finished;
		}
	    }
	}
	/*
	* Generate a new prefix.
	*/
	{
	    const xmlChar *basepref = prefix;
	    xmlChar pref[30];
	    int counter = 1;
	    
	    if (prefix != NULL)
		basepref = prefix;
	    else
		basepref = xmlStrdup(BAD_CAST "ns");
	    
	    do {
		snprintf((char *) pref, 30, "%s%d",
		    basepref, counter++);
		ns = xmlSearchNs(targetElem->doc, targetElem, BAD_CAST pref);
		if (counter > 1000) {
		    xsltTransformError(ctxt, NULL, inst,
		    	"Namespace fixup error: Failed to compute a "
			"new unique ns-prefix for the generated attribute "
			"{%s}%s'.\n", nsName, name);		    			
		    ns = NULL;
		    break;
		}
	    } while (ns != NULL);
	    if (basepref != prefix)
		xmlFree((xmlChar *)basepref);
	    ns = xmlNewNs(targetElem, nsName, BAD_CAST pref);
	}

namespace_finished:

	if (ns == NULL) {
	    xsltTransformError(ctxt, NULL, inst,
		"Namespace fixup error: Failed to acquire an in-scope "
		"namespace binding of the generated attribute '{%s}%s'.\n",
		nsName, name);
	    /*
	    * TODO: Should we just stop here?
	    */
	}
    }
    /*
    * Construction of the value
    * -------------------------
    */
    if (inst->children == NULL) {
	/*
	* No content.
	* TODO: Do we need to put the empty string in ?
	*/
	attr = xmlSetNsProp(ctxt->insert, ns, name, (const xmlChar *) "");
    } else if ((inst->children->next == NULL) && 
	    ((inst->children->type == XML_TEXT_NODE) ||
	     (inst->children->type == XML_CDATA_SECTION_NODE)))
    {
	xmlNodePtr origTxt = inst->children, copyTxt;
	/*
	* Optimization: if the content is just 1 text node, then
	* just need to copy it over, or just assign it to the result
	* if the string is shared.
	*/
	attr = xmlSetNsProp(ctxt->insert, ns, name, NULL);
	if (attr == NULL) /* TODO: report error ? */
	    goto error;
	/*
	* This was taken over from xsltCopyText() (transform.c).
	*/
	if (ctxt->internalized &&
	    (ctxt->insert->doc != NULL) &&
	    (ctxt->insert->doc->dict == ctxt->dict))
	{
	    copyTxt = xmlNewText(NULL);
	    if (copyTxt == NULL) /* TODO: report error */
		goto error;
	    /*
	    * This is a safe scenario where we don't need to lookup
	    * the dict.
	    */
	    copyTxt->content = origTxt->content;
	    /*
	    * Copy "disable-output-escaping" information.
	    * TODO: Does this have any effect for attribute values
	    *  anyway?
	    */
	    if (origTxt->name == xmlStringTextNoenc)
		copyTxt->name = xmlStringTextNoenc;
	} else {
	    /*
	    * Copy the value.
	    */
	    copyTxt = xmlNewText(origTxt->content);
	    if (copyTxt == NULL) /* TODO: report error */
		goto error;
	    /*
	    * Copy "disable-output-escaping" information.
	    * TODO: Does this have any effect for attribute values
	    *  anyway?
	    */
	    if (origTxt->name == xmlStringTextNoenc)
		copyTxt->name = xmlStringTextNoenc;
	}
	if (copyTxt != NULL) {
	    copyTxt->doc = attr->doc;
	    xmlAddChild((xmlNodePtr) attr, copyTxt);
	}
    } else {
	/*
	* The sequence constructor might be complex, so instantiate it.
	*/
	value = xsltEvalTemplateString(ctxt, node, inst);
	if (value != NULL) {
	    attr = xmlSetNsProp(ctxt->insert, ns, name, value);
	    xmlFree(value);
	} else {
	    /*
	    * TODO: Do we have to add the empty string to the attr?
	    */
	    attr = xmlSetNsProp(ctxt->insert, ns, name,
		(const xmlChar *) "");
	}
    }

error:
    return;    
}
Exemplo n.º 9
0
static void
parse_rdf_item (GbBookmarkSet *set,
		GbFolder *root,
		GList **folders,
		xmlNodePtr node)
{
	xmlChar *title = NULL;
	xmlChar *link = NULL;
	xmlChar *smartlink = NULL;
	GList *subjects = NULL, *l;
	xmlNodePtr child;
	GbBookmark *bmk;

	child = node->children;

	while (child != NULL)
	{
		if (xmlStrEqual (child->name, (const xmlChar*)"title"))
		{
			title = xmlNodeGetContent (child);
		}
		else if (xmlStrEqual (child->name, (const xmlChar*)"link"))
		{
			link = xmlNodeGetContent (child);
		}
		else if (xmlStrEqual (child->name, (const xmlChar*)"subject"))
		{
			parse_rdf_subjects (child, &subjects);
		}
		else if (xmlStrEqual (child->name, (const xmlChar*)"smartlink"))
		{
			smartlink = xmlNodeGetContent (child);
		}

		child = child->next;
	}

	bmk = bookmark_add (set, (char*)title, (char*)link, (char*)smartlink);
	g_return_if_fail (bmk != NULL);

	for (l = subjects; l != NULL; l = l->next)
	{
		const char *title = (char *) l->data;
		GbFolder *folder;
		GList *item;

		item = g_list_find_custom (*folders, title, (GCompareFunc) find_folder);

		if (item)
		{
			folder = GB_FOLDER (item->data);
		}
		else
		{
			/* create folder from subject */
			folder = gb_folder_new (set, title);
			gb_folder_add_child (root, GB_BOOKMARK (folder), -1);

			*folders = g_list_prepend (*folders, folder);
		}

		gb_bookmark_add_alias_under (bmk, folder);
	}

	if (subjects == NULL)
	{
		/* "Uncategorised" bookmark, add to root folder */
		gb_folder_add_child (root, bmk, -1);
	}

	xmlFree (title);
	xmlFree (link);
	xmlFree (smartlink);

	g_list_foreach (subjects, (GFunc) xmlFree, NULL);
	g_list_free (subjects);
}
/**
 * xsltFreeAttrElem:
 * @attr:  an XSLT AttrElem
 *
 * Free up the memory allocated by @attr
 */
static void
xsltFreeAttrElem(xsltAttrElemPtr attr) {
    xmlFree(attr);
}
void
xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) {
    const xmlChar *ncname;
    const xmlChar *prefix;
    xmlChar *value;
    xmlNodePtr child;
    xsltAttrElemPtr attrItems;

    if ((cur == NULL) || (style == NULL))
	return;

    value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL);
    if (value == NULL) {
	xsltGenericError(xsltGenericErrorContext,
	     "xsl:attribute-set : name is missing\n");
	return;
    }

    ncname = xsltSplitQName(style->dict, value, &prefix);
    xmlFree(value);
    value = NULL;

    if (style->attributeSets == NULL) {
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
	xsltGenericDebug(xsltGenericDebugContext,
	    "creating attribute set table\n");
#endif
	style->attributeSets = xmlHashCreate(10);
    }
    if (style->attributeSets == NULL)
	return;

    attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix);

    /*
    * Parse the content. Only xsl:attribute elements are allowed.
    */
    child = cur->children;
    while (child != NULL) {
	/*
	* Report invalid nodes.
	*/
	if ((child->type != XML_ELEMENT_NODE) ||
	    (child->ns == NULL) ||
	    (! IS_XSLT_ELEM(child)))
	{
	    if (child->type == XML_ELEMENT_NODE)
		xsltTransformError(NULL, style, child,
			"xsl:attribute-set : unexpected child %s\n",
		                 child->name);
	    else
		xsltTransformError(NULL, style, child,
			"xsl:attribute-set : child of unexpected type\n");
	} else if (!IS_XSLT_NAME(child, "attribute")) {
	    xsltTransformError(NULL, style, child,
		"xsl:attribute-set : unexpected child xsl:%s\n",
		child->name);
	} else {
#ifdef XSLT_REFACTORED
	    xsltAttrElemPtr nextAttr, curAttr;

	    /*
	    * Process xsl:attribute
	    * ---------------------
	    */

#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
	    xsltGenericDebug(xsltGenericDebugContext,
		"add attribute to list %s\n", ncname);
#endif
	    /*
	    * The following was taken over from
	    * xsltAddAttrElemList().
	    */
	    if (attrItems == NULL) {
		attrItems = xsltNewAttrElem(child);
	    } else {
		curAttr = attrItems;
		while (curAttr != NULL) {
		    nextAttr = curAttr->next;
		    if (curAttr->attr == child) {
			/*
			* URGENT TODO: Can somebody explain
			*  why attrItems is set to curAttr
			*  here? Is this somehow related to
			*  avoidance of recursions?
			*/
			attrItems = curAttr;
			goto next_child;
		    }
		    if (curAttr->next == NULL)			
			curAttr->next = xsltNewAttrElem(child);
		    curAttr = nextAttr;
		}
	    }
	    /*
	    * Parse the xsl:attribute and its content.
	    */
	    xsltParseAnyXSLTElem(XSLT_CCTXT(style), child);
#else
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
	    xsltGenericDebug(xsltGenericDebugContext,
		"add attribute to list %s\n", ncname);
#endif
	    /*
	    * OLD behaviour:
	    */
	    attrItems = xsltAddAttrElemList(attrItems, child);
#endif
	}

#ifdef XSLT_REFACTORED
next_child:
#endif
	child = child->next;
    }

    /*
    * Process attribue "use-attribute-sets".
    */
    /* TODO check recursion */    
    value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets",
	NULL);
    if (value != NULL) {
	const xmlChar *curval, *endval;
	curval = value;
	while (*curval != 0) {
	    while (IS_BLANK(*curval)) curval++;
	    if (*curval == 0)
		break;
	    endval = curval;
	    while ((*endval != 0) && (!IS_BLANK(*endval))) endval++;
	    curval = xmlDictLookup(style->dict, curval, endval - curval);
	    if (curval) {
		const xmlChar *ncname2 = NULL;
		const xmlChar *prefix2 = NULL;
		xsltAttrElemPtr refAttrItems;
		
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
		xsltGenericDebug(xsltGenericDebugContext,
		    "xsl:attribute-set : %s adds use %s\n", ncname, curval);
#endif
		ncname2 = xsltSplitQName(style->dict, curval, &prefix2);
		refAttrItems = xsltNewAttrElem(NULL);
		if (refAttrItems != NULL) {
		    refAttrItems->set = ncname2;
		    refAttrItems->ns = prefix2;
		    attrItems = xsltMergeAttrElemList(style,
			attrItems, refAttrItems);
		    xsltFreeAttrElem(refAttrItems);
		}
	    }
	    curval = endval;
	}
	xmlFree(value);
	value = NULL;
    }

    /*
     * Update the value
     */
    /*
    * TODO: Why is this dummy entry needed.?
    */
    if (attrItems == NULL)
	attrItems = xsltNewAttrElem(NULL);
    xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL);
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
    xsltGenericDebug(xsltGenericDebugContext,
	"updated attribute list %s\n", ncname);
#endif
}
Exemplo n.º 12
0
/**
 * xsltElementAvailableFunction:
 * @ctxt:  the XPath Parser context
 * @nargs:  the number of arguments
 *
 * Implement the element-available() XSLT function
 *   boolean element-available(string)
 */
void
xsltElementAvailableFunction(xmlXPathParserContextPtr ctxt, int nargs){
    xmlXPathObjectPtr obj;
    xmlChar *prefix, *name;
    const xmlChar *nsURI = NULL;
    xsltTransformContextPtr tctxt;

    if (nargs != 1) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
        xsltGenericError(xsltGenericErrorContext,
		"element-available() : expects one string arg\n");
	ctxt->error = XPATH_INVALID_ARITY;
	return;
    }
    if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
	xsltGenericError(xsltGenericErrorContext,
	    "element-available() : invalid arg expecting a string\n");
	ctxt->error = XPATH_INVALID_TYPE;
	return;
    }
    obj = valuePop(ctxt);
    tctxt = xsltXPathGetTransformContext(ctxt);
    if (tctxt == NULL) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
	xsltGenericError(xsltGenericErrorContext,
		"element-available() : internal error tctxt == NULL\n");
	xmlXPathFreeObject(obj);
	valuePush(ctxt, xmlXPathNewBoolean(0));
	return;
    }


    name = xmlSplitQName2(obj->stringval, &prefix);
    if (name == NULL) {
	xmlNsPtr ns;

	name = xmlStrdup(obj->stringval);
	ns = xmlSearchNs(tctxt->inst->doc, tctxt->inst, NULL);
	nsURI = xmlStrdup(ns->href);
    } else {
	nsURI = xmlXPathNsLookup(ctxt->context, prefix);
	if (nsURI == NULL) {
	    xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt),
				  NULL, NULL);
	    xsltGenericError(xsltGenericErrorContext,
		"element-available() : prefix %s is not bound\n", prefix);
	}
    }

    if (xsltExtElementLookup(tctxt, name, nsURI) != NULL) {
	valuePush(ctxt, xmlXPathNewBoolean(1));
    } else {
	valuePush(ctxt, xmlXPathNewBoolean(0));
    }

    xmlXPathFreeObject(obj);
    if (name != NULL)
	xmlFree(name);
    if (prefix != NULL)
	xmlFree(prefix);
}
Exemplo n.º 13
0
/**
 * xsltSystemPropertyFunction:
 * @ctxt:  the XPath Parser context
 * @nargs:  the number of arguments
 *
 * Implement the system-property() XSLT function
 *   object system-property(string)
 */
void
xsltSystemPropertyFunction(xmlXPathParserContextPtr ctxt, int nargs){
    xmlXPathObjectPtr obj;
    xmlChar *prefix, *name;
    const xmlChar *nsURI = NULL;

    if (nargs != 1) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
        xsltGenericError(xsltGenericErrorContext,
		"system-property() : expects one string arg\n");
	ctxt->error = XPATH_INVALID_ARITY;
	return;
    }
    if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
	xsltGenericError(xsltGenericErrorContext,
	    "system-property() : invalid arg expecting a string\n");
	ctxt->error = XPATH_INVALID_TYPE;
	return;
    }
    obj = valuePop(ctxt);
    if (obj->stringval == NULL) {
	valuePush(ctxt, xmlXPathNewString((const xmlChar *)""));
    } else {
	name = xmlSplitQName2(obj->stringval, &prefix);
	if (name == NULL) {
	    name = xmlStrdup(obj->stringval);
	} else {
	    nsURI = xmlXPathNsLookup(ctxt->context, prefix);
	    if (nsURI == NULL) {
		xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt),
			              NULL, NULL);
		xsltGenericError(xsltGenericErrorContext,
		    "system-property() : prefix %s is not bound\n", prefix);
	    }
	}

	if (xmlStrEqual(nsURI, XSLT_NAMESPACE)) {
#ifdef DOCBOOK_XSL_HACK
	    if (xmlStrEqual(name, (const xmlChar *)"vendor")) {
		xsltStylesheetPtr sheet;
		xsltTransformContextPtr tctxt;

		tctxt = xsltXPathGetTransformContext(ctxt);
		if ((tctxt != NULL) && (tctxt->inst != NULL) &&
		    (xmlStrEqual(tctxt->inst->name, BAD_CAST "variable")) &&
		    (tctxt->inst->parent != NULL) &&
		    (xmlStrEqual(tctxt->inst->parent->name,
				 BAD_CAST "template")))
		    sheet = tctxt->style;
		else
		    sheet = NULL;
		if ((sheet != NULL) && (sheet->doc != NULL) &&
		    (sheet->doc->URL != NULL) &&
		    (xmlStrstr(sheet->doc->URL,
			       (const xmlChar *)"chunk") != NULL)) {
		    valuePush(ctxt, xmlXPathNewString(
			(const xmlChar *)"libxslt (SAXON 6.2 compatible)"));

		} else {
		    valuePush(ctxt, xmlXPathNewString(
			(const xmlChar *)XSLT_DEFAULT_VENDOR));
		}
	    } else
#else
	    if (xmlStrEqual(name, (const xmlChar *)"vendor")) {
		valuePush(ctxt, xmlXPathNewString(
			  (const xmlChar *)XSLT_DEFAULT_VENDOR));
	    } else
#endif
	    if (xmlStrEqual(name, (const xmlChar *)"version")) {
		valuePush(ctxt, xmlXPathNewString(
		    (const xmlChar *)XSLT_DEFAULT_VERSION));
	    } else if (xmlStrEqual(name, (const xmlChar *)"vendor-url")) {
		valuePush(ctxt, xmlXPathNewString(
		    (const xmlChar *)XSLT_DEFAULT_URL));
	    } else {
		valuePush(ctxt, xmlXPathNewString((const xmlChar *)""));
	    }
	}
	if (name != NULL)
	    xmlFree(name);
	if (prefix != NULL)
	    xmlFree(prefix);
    }
    xmlXPathFreeObject(obj);
}
Exemplo n.º 14
0
/**
 * xsltKeyFunction:
 * @ctxt:  the XPath Parser context
 * @nargs:  the number of arguments
 *
 * Implement the key() XSLT function
 *   node-set key(string, object)
 */
void
xsltKeyFunction(xmlXPathParserContextPtr ctxt, int nargs){
    xmlNodeSetPtr nodelist;
    xmlXPathObjectPtr obj1, obj2;
    xmlChar *key = NULL, *value;
    const xmlChar *keyURI;
    xsltTransformContextPtr tctxt;

    if (nargs != 2) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
        xsltGenericError(xsltGenericErrorContext,
		"key() : expects two arguments\n");
	ctxt->error = XPATH_INVALID_ARITY;
	return;
    }

    obj2 = valuePop(ctxt);
    if ((obj2 == NULL) ||
	(ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) {
	xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt), NULL, NULL);
	xsltGenericError(xsltGenericErrorContext,
	    "key() : invalid arg expecting a string\n");
	ctxt->error = XPATH_INVALID_TYPE;
	xmlXPathFreeObject(obj2);

	return;
    }
    obj1 = valuePop(ctxt);

    if (obj2->type == XPATH_NODESET) {
	int i;
	xmlXPathObjectPtr newobj, ret;

	ret = xmlXPathNewNodeSet(NULL);

	if (obj2->nodesetval != NULL) {
	    for (i = 0; i < obj2->nodesetval->nodeNr; i++) {
		valuePush(ctxt, xmlXPathObjectCopy(obj1));
		valuePush(ctxt,
			  xmlXPathNewNodeSet(obj2->nodesetval->nodeTab[i]));
		xmlXPathStringFunction(ctxt, 1);
		xsltKeyFunction(ctxt, 2);
		newobj = valuePop(ctxt);
		ret->nodesetval = xmlXPathNodeSetMerge(ret->nodesetval,
						       newobj->nodesetval);
		xmlXPathFreeObject(newobj);
	    }
	}
	valuePush(ctxt, ret);
    } else {
	xmlChar *qname, *prefix;

	/*
	 * Get the associated namespace URI if qualified name
	 */
	qname = obj1->stringval;
	key = xmlSplitQName2(qname, &prefix);
	if (key == NULL) {
	    key = xmlStrdup(obj1->stringval);
	    keyURI = NULL;
	    if (prefix != NULL)
		xmlFree(prefix);
	} else {
	    if (prefix != NULL) {
		keyURI = xmlXPathNsLookup(ctxt->context, prefix);
		if (keyURI == NULL) {
		    xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt),
					  NULL, NULL);
		    xsltGenericError(xsltGenericErrorContext,
			"key() : prefix %s is not bound\n", prefix);
		}
		xmlFree(prefix);
	    } else {
		keyURI = NULL;
	    }
	}

	/*
	 * Force conversion of first arg to string
	 */
	valuePush(ctxt, obj2);
	xmlXPathStringFunction(ctxt, 1);
	if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) {
	    xsltPrintErrorContext(xsltXPathGetTransformContext(ctxt),
				  NULL, NULL);
	    xsltGenericError(xsltGenericErrorContext,
		"key() : invalid arg expecting a string\n");
	    ctxt->error = XPATH_INVALID_TYPE;
	    xmlXPathFreeObject(obj1);

	    return;
	}
	obj2 = valuePop(ctxt);
	value = obj2->stringval;

	tctxt = xsltXPathGetTransformContext(ctxt);

	nodelist = xsltGetKey(tctxt, key, keyURI, value);
	valuePush(ctxt, xmlXPathWrapNodeSet(
		        xmlXPathNodeSetMerge(NULL, nodelist)));
    }


    if (obj1 != NULL)
	xmlXPathFreeObject(obj1);
    if (obj2 != NULL)
	xmlXPathFreeObject(obj2);
    if (key != NULL)
	xmlFree(key);
}
Exemplo n.º 15
0
void
RL::ListImpl::parse ()
{
  int list_pos = 1;
  int entry_pos = 1;

  for (xmlNodePtr child = node->children; child != NULL; child = child->next) {

    if (child->type == XML_ELEMENT_NODE
	&& child->name != NULL
	&& xmlStrEqual (BAD_CAST "display-name", child->name)) {

      xmlChar* str = xmlNodeGetContent (child);
      name_node = child;
      if (str != NULL) {

	if ( !group.empty ())
	  display_name = group + " / " + (const char*) str;
	else
	  display_name = (const char*) str;
	xmlFree (str);
      }
      break;
    }

  }

  for (xmlNodePtr child = node->children; child != NULL; child = child->next) {

    if (child->type == XML_ELEMENT_NODE
	&& child->name != NULL
	&& xmlStrEqual (BAD_CAST "list", child->name)) {

      boost::shared_ptr<List> list = boost::shared_ptr<List> (new List (core, path,
							list_pos, display_name,
							child));
      list->entry_added.connect (entry_added);
      list->entry_updated.connect (entry_updated);
      list->entry_removed.connect (entry_removed);
      lists.push_back (list);
      ordering.push_back (LIST);
      list_pos++;
      list->publish ();
      continue;
    }

    if (child->type == XML_ELEMENT_NODE
	&& child->name != NULL
	&& xmlStrEqual (BAD_CAST "entry", child->name)) {

      boost::shared_ptr<Entry> entry = boost::shared_ptr<Entry> (new Entry (core, path,
							    entry_pos,
							    display_name,
							    doc, child));
      std::list<boost::signals2::connection> conns;
      conns.push_back (entry->updated.connect (boost::bind (boost::ref (entry_updated), entry)));
      conns.push_back (entry->removed.connect (boost::bind (boost::ref (entry_removed), entry)));
      entries.push_back (std::pair<boost::shared_ptr<Entry>, std::list<boost::signals2::connection> > (entry, conns));
      ordering.push_back (ENTRY);
      entry_pos++;
      entry_added (entry);
      continue;
    }
  }
}
Exemplo n.º 16
0
int loadstatus() {
	xmlNodePtr root = NULL;
	xmlNodePtr node = NULL;
	xmlParserCtxtPtr parserctxt;
	int ret = 0;
	char* tmp;
	FILE* totest;
	totest = fopen(statname, "r");
	if (totest != NULL) {
		fclose(totest);
		status = xmlParseFile(statname);
	}
	if (status != NULL)
		root = xmlDocGetRootElement(status);
	else
		status = xmlNewDoc(NULL);
	if (root != NULL) {
		parserctxt = xmlNewParserCtxt();
		for (node = root->children; node; node = node->next) {
			if (xmlStrcmp(node->name, "abc") == 0) {
				if (node->children && (strlen(node->children->content) > 0)) {
					ABC = xmlStringDecodeEntities(parserctxt, 
						node->children->content,XML_SUBSTITUTE_BOTH,0,0,0);
				} else
					ret = 1;
			} else if (xmlStrcmp(node->name, "current") == 0) {
				if (node->children && (strlen(node->children->content) > 0)) {
					tmp = xmlStringDecodeEntities(parserctxt, 
						node->children->content,XML_SUBSTITUTE_BOTH,0,0,0);
					strcpy(password,tmp);
					curr_len = strlen(password);
					printf("INFO: Resuming cracking from password: '******'\n",password);
					xmlFree(tmp);
				} else
					ret = 1;
			} else if (xmlStrcmp(node->name, "good_password") == 0) {
				if (node->children && (strlen(node->children->content) > 0)) {
					tmp = xmlStringDecodeEntities(parserctxt, 
						node->children->content,XML_SUBSTITUTE_BOTH,0,0,0);
					strcpy(password,tmp);
					curr_len = strlen(password);
					xmlMutexLock(finishedMutex);
					finished = 1;
					xmlMutexUnlock(finishedMutex);
					strcpy((char*) &password_good, (char*) &password);
					printf("GOOD: This archive was succesfully cracked\n");
					printf("      The good password is: '%s'\n", password);
					xmlFree(tmp);
					ret = 1;
				}
			}
		}
		xmlFreeParserCtxt(parserctxt);
	} else {
		root = xmlNewNode(NULL, "rarcrack");
		xmlDocSetRootElement(status, root);
		node = xmlNewTextChild(root, NULL, "abc", ABC);
		node = xmlNewTextChild(root, NULL, "current", getfirstpassword()); 
		node = xmlNewTextChild(root, NULL, "good_password", "");
		savestatus();
	}
	return ret;
}
Exemplo n.º 17
0
/*******************************************************************************
**
** Function:        import
**
** Description:     Import data from an XML file.  Fill the databases.
**
** Returns:         True if ok.
**
*******************************************************************************/
bool RouteDataSet::import ()
{
    static const char fn [] = "RouteDataSet::import";
    ALOGD ("%s: enter", fn);
    bool retval = false;
    xmlDocPtr doc;
    xmlNodePtr node1;
    std::string strFilename(bcm_nfc_location);
    strFilename += sConfigFile;

    deleteDatabase ();

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

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

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

TheEnd:
    xmlFreeDoc (doc);
    xmlCleanupParser ();
    ALOGD ("%s: exit; return=%u", fn, retval);
    return retval;
}
Exemplo n.º 18
0
static xmlParserInputPtr 
xsltprocExternalEntityLoader(const char *URL, const char *ID,
			     xmlParserCtxtPtr ctxt) {
    xmlParserInputPtr ret;
    warningSAXFunc warning = NULL;

    int i;
    const char *lastsegment = URL;
    const char *iter = URL;

    if (nbpaths > 0) {
	while (*iter != 0) {
	    if (*iter == '/')
		lastsegment = iter + 1;
	    iter++;
	}
    }

    if ((ctxt != NULL) && (ctxt->sax != NULL)) {
	warning = ctxt->sax->warning;
	ctxt->sax->warning = NULL;
    }

    if (defaultEntityLoader != NULL) {
	ret = defaultEntityLoader(URL, ID, ctxt);
	if (ret != NULL) {
	    if (warning != NULL)
		ctxt->sax->warning = warning;
	    if (load_trace) {
		fprintf \
			(stderr,
			 "Loaded URL=\"%s\" ID=\"%s\"\n",
			 URL ? URL : "(null)",
			 ID ? ID : "(null)");
	    }
	    return(ret);
	}
    }
    for (i = 0;i < nbpaths;i++) {
	xmlChar *newURL;

	newURL = xmlStrdup((const xmlChar *) paths[i]);
	newURL = xmlStrcat(newURL, (const xmlChar *) "/");
	newURL = xmlStrcat(newURL, (const xmlChar *) lastsegment);
	if (newURL != NULL) {
	    ret = defaultEntityLoader((const char *)newURL, ID, ctxt);
	    if (ret != NULL) {
		if (warning != NULL)
		    ctxt->sax->warning = warning;
		if (load_trace) {
		    fprintf \
		    	(stderr,
		    	 "Loaded URL=\"%s\" ID=\"%s\"\n",
			 newURL,
		    	 ID ? ID : "(null)");
		}
		xmlFree(newURL);
		return(ret);
	    }
	    xmlFree(newURL);
	}
    }
    if (warning != NULL) {
	ctxt->sax->warning = warning;
	if (URL != NULL)
	    warning(ctxt, "failed to load external entity \"%s\"\n", URL);
	else if (ID != NULL)
	    warning(ctxt, "failed to load external entity \"%s\"\n", ID);
    }
    return(NULL);
}
Exemplo n.º 19
0
static int
xmlSecTransformXPathNodeRead(xmlSecTransformPtr transform, xmlNodePtr node, xmlSecTransformCtxPtr transformCtx) {
    xmlSecPtrListPtr dataList;
    xmlSecXPathDataPtr data;
    xmlNodePtr cur;
    xmlChar* tmp;
    int tmpSize;
    int ret;

    xmlSecAssert2(xmlSecTransformCheckId(transform, xmlSecTransformXPathId), -1);
    xmlSecAssert2(node != NULL, -1);
    xmlSecAssert2(transformCtx != NULL, -1);

    dataList = xmlSecXPathTransformGetDataList(transform);
    xmlSecAssert2(xmlSecPtrListCheckId(dataList, xmlSecXPathDataListId), -1);
    xmlSecAssert2(xmlSecPtrListGetSize(dataList) == 0, -1);

    /* there is only one required node */
    cur = xmlSecGetNextElementNode(node->children);
    if((cur == NULL) || (!xmlSecCheckNodeName(cur, xmlSecNodeXPath, xmlSecDSigNs))) {
        xmlSecInvalidNodeError(cur, xmlSecNodeXPath,
                               xmlSecTransformGetName(transform));
        return(-1);
    }

    /* read information from the node */
    data = xmlSecXPathDataCreate(xmlSecXPathDataTypeXPath);
    if(data == NULL) {
        xmlSecInternalError("xmlSecXPathDataCreate",
                            xmlSecTransformGetName(transform));
        return(-1);
    }

    ret = xmlSecXPathDataNodeRead(data, cur);
    if(ret < 0) {
        xmlSecInternalError("xmlSecXPathDataNodeRead",
                            xmlSecTransformGetName(transform));
        xmlSecXPathDataDestroy(data);
        return(-1);
    }

    /* append it to the list */
    ret = xmlSecPtrListAdd(dataList, data);
    if(ret < 0) {
        xmlSecInternalError("xmlSecPtrListAdd",
                            xmlSecTransformGetName(transform));
        xmlSecXPathDataDestroy(data);
        return(-1);
    }

    /* create full XPath expression */
    xmlSecAssert2(data->expr != NULL, -1);
    tmpSize = xmlStrlen(data->expr) + strlen(xpathPattern) + 1;
    tmp = (xmlChar*) xmlMalloc(sizeof(xmlChar) * tmpSize);
    if(tmp == NULL) {
        xmlSecMallocError(sizeof(xmlChar) * tmpSize,
                          xmlSecTransformGetName(transform));
        return(-1);
    }
    ret = xmlStrPrintf(tmp, tmpSize, xpathPattern, (char*)data->expr);
    if(ret < 0) {
       xmlSecXmlError("xmlStrPrintf", xmlSecTransformGetName(transform));
       xmlFree(tmp);
       return(-1);
    }
    xmlFree(data->expr);
    data->expr = tmp;

    /* set correct node set type and operation */
    data->nodeSetOp     = xmlSecNodeSetIntersection;
    data->nodeSetType   = xmlSecNodeSetNormal;

    /* check that we have nothing else */
    cur = xmlSecGetNextElementNode(cur->next);
    if(cur != NULL) {
        xmlSecUnexpectedNodeError(cur, xmlSecTransformGetName(transform));
        return(-1);
    }
    return(0);
}
Exemplo n.º 20
0
/**
 *gdata_entry_generate_xml:
 *@entry: A GDataEntry Object
 *Returns the xml content:
 **/
gchar *
gdata_entry_generate_xml (GDataEntry *entry)
{
	GDataEntryPrivate *priv;
	GSList *list;
	xmlChar *xmlString;
	xmlNsPtr ns;
	xmlNodePtr cur, cur_child, root;
	xmlDocPtr doc;
	gint xml_buffer_size;

	g_return_val_if_fail(entry !=NULL, NULL);
	g_return_val_if_fail(GDATA_IS_ENTRY (entry), NULL);

	priv = GDATA_ENTRY_GET_PRIVATE(entry);

	if (!(priv->entry_xml == NULL || priv->entry_needs_update == TRUE))
		return priv->entry_xml;

	/* Construct DOM tree */
	doc = xmlNewDoc ((xmlChar *)"1.0");
	root = xmlNewDocNode (doc, NULL, (xmlChar *)"entry", NULL);

	xmlSetProp (root, (xmlChar *)"xmlns", (xmlChar *)"http://www.w3.org/2005/Atom");
	ns =  xmlNewNs (root, (xmlChar *)"http://schemas.google.com/g/2005", (xmlChar *)"gd");
	xmlDocSetRootElement (doc, root);
	cur = root;

	list = priv->categories;
	while (list) {
		cur_child = category_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}

	list = priv->authors;
	while (list) {
		cur_child = author_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}
	
	list = priv->links;
	while (list) {
		cur_child = link_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}

	if (priv->status) {
		cur_child = xmlNewChild(root, NULL, (xmlChar *)"eventStatus", NULL);
		xmlSetNs (cur_child, xmlNewNs (cur_child, NULL, (xmlChar *)"gd"));
		xmlSetProp (cur_child, (xmlChar *)"value", (xmlChar *)priv->status);
	}

	if (priv->start_time || priv->end_time || priv->reminder) {
		cur_child = xmlNewChild(root, NULL, (xmlChar *)"when", NULL);
		xmlSetNs (cur_child, xmlNewNs (cur_child, NULL, (xmlChar *)"gd"));
		xmlSetProp (cur_child, (xmlChar *)"startTime", (xmlChar *)priv->start_time);
		xmlSetProp (cur_child, (xmlChar *)"endTime", (xmlChar *)priv->end_time);

		if (priv->reminder) {
			cur = cur_child;
			cur_child = xmlNewChild(cur, NULL, (xmlChar *)"reminder", (xmlChar *)"");
			xmlSetNs (cur_child, xmlNewNs (cur_child, NULL, (xmlChar *)"gd"));
			xmlSetProp (cur_child->xmlChildrenNode, (xmlChar *)"minutes", (xmlChar *)priv->reminder);
		}
	}

	if (priv->location ) {
		cur_child = xmlNewChild(root, NULL, (xmlChar *)"where", NULL);
		xmlSetNs (cur_child, xmlNewNs (cur_child, NULL, (xmlChar *)"gd"));
		xmlSetProp (cur_child, (xmlChar *)"valueString", (xmlChar *)priv->location);
	}

	if (priv->content) {
		cur_child = xmlNewChild(root, NULL, (xmlChar *)"content", (xmlChar *)priv->content);
		xmlSetProp (cur_child, (xmlChar *)"type", (xmlChar *)"text");
	}

	if (priv->title) {
		cur_child = xmlNewChild(root, NULL, (xmlChar *)"title", (xmlChar *)priv->title);
		xmlSetProp (cur_child, (xmlChar *)"type", (xmlChar *)"text");
	}

	list = priv->email_addresses;
	while (list) {
		cur_child = email_address_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}

	list = priv->im_addresses;
	while (list) {
		cur_child = im_address_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}

	list = priv->organizations;
	while (list) {
		cur_child = organization_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}

	list = priv->phone_numbers;
	while (list) {
		cur_child = phone_number_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}

	list = priv->postal_addresses;
	while (list) {
		cur_child = postal_address_to_xmlnode(list->data);
		xmlAddChild(root, cur_child);
		list = g_slist_next(list);
	}

	/*
	   if (priv->field_table) {
	   g_hash_table_foreach (priv->field_table,(GHFunc) _build_hash_table_entries, &root);
	   }
	 */

	xmlDocDumpMemory(doc, &xmlString, &xml_buffer_size);
    g_free (priv->entry_xml);
	priv->entry_xml = g_strdup((gchar *)xmlString);

	xmlFree(xmlString);
	xmlFreeDoc(doc);

	return priv->entry_xml;
}
Exemplo n.º 21
0
bool Simulation::Parse( void ) {
	xmlDocPtr doc;
	xmlNodePtr cur;
	int versionMajor = 0, versionMinor = 0, versionMacro = 0;
	
	doc = xmlParseFile( filename.c_str() );
	
	if( doc == NULL ) {
		Log::Warning( "Could not load '%s' simulation file.", filename.c_str() );
		return false;
	}
	
	cur = xmlDocGetRootElement( doc );
	
	if( cur == NULL ) {
		Log::Warning( "'%s' file appears to be empty.", filename.c_str() );
		xmlFreeDoc( doc );
		return false;
	}
	
	if( xmlStrcmp( cur->name, (const xmlChar *)"simulation" ) ) {
		Log::Warning( "'%s' appears to be invalid. Root element was %s.", filename.c_str(), (char *)cur->name );
		xmlFreeDoc( doc );
		return false;
	} else {
		Log::Message( "'%s' file found and valid, parsing...", filename.c_str() );
	}
	
	cur = cur->xmlChildrenNode;
	while( cur != NULL ) {
		// Parse for the version information and any children nodes
		if( ( !xmlStrcmp( cur->name, (const xmlChar *)"version-major" ) ) ) {
			xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
			versionMajor = atoi( (char *)key );
			xmlFree( key );
		} else if( ( !xmlStrcmp( cur->name, (const xmlChar *)"version-minor" ) ) ) {
			xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
			versionMinor = atoi( (char *)key );
			xmlFree( key );
		} else if( ( !xmlStrcmp( cur->name, (const xmlChar *)"version-macro" ) ) ) {
			xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
			versionMacro = atoi( (char *)key );
			xmlFree( key );
		} else {
			char *sectionName = (char *)cur->name;

			if( !strcmp( sectionName, "planets" ) ) {
				xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
				planetsFilename = (char *)key;
				xmlFree( key );
				Log::Message( "Planets filename is %s.", planetsFilename.c_str() );
			}
			if( !strcmp( sectionName, "models" ) ) {
				xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
				modelsFilename = (char *)key;
				xmlFree( key );
				Log::Message( "Models filename is %s.", modelsFilename.c_str() );
			}
			if( !strcmp( sectionName, "engines" ) ) {
				xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
				enginesFilename = (char *)key;
				xmlFree( key );
				Log::Message( "Engines filename is %s.", enginesFilename.c_str() );
			}
			if( !strcmp( sectionName, "alliances" ) ) {
				xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
				alliancesFilename = (char *)key;
				xmlFree( key );
				Log::Message( "Alliances filename is %s.", alliancesFilename.c_str() );
			}
			if( !strcmp( sectionName, "playerDefaultModel" ) ) {
				xmlChar *key = xmlNodeListGetString( doc, cur->xmlChildrenNode, 1 );
				playerDefaultModel = (char *)key;
				xmlFree( key );
				Log::Message( "playerDefaultModel is %s.", playerDefaultModel.c_str() );
			}
		}
		
		cur = cur->next;
	}
	
	xmlFreeDoc( doc );
	
	Log::Message( "'%s' parsing done. File is version %d.%d.%d.", filename.c_str(), versionMajor, versionMinor, versionMacro );

	// Now load the various subsystems
	if( planets->Load( planetsFilename ) != true ) {
		Log::Warning( "There was an error loading the planets from '%s'.", planetsFilename.c_str() );
	}
	if( engines->Load( enginesFilename ) != true ) {
		Log::Error( "There was an error loading the engines from '%s'.", enginesFilename.c_str() );
	}
	if( models->Load( modelsFilename ) != true ) {
		Log::Error( "There was an error loading the models from '%s'.", modelsFilename.c_str() );
	}
	if( alliances->Load( alliancesFilename ) != true ) {
		Log::Error( "There was an error loading the alliances from '%s'.", alliancesFilename.c_str() );
	}

	return true;
}
Exemplo n.º 22
0
/**
 * gdata_entry_new_from_xmlptr:
 * @doc: A xml document pointer
 * @ptr: A xml Node pointer
 **/
GDataEntry *
gdata_entry_new_from_xmlptr (xmlDocPtr doc, xmlNodePtr cur)
{
	GDataEntry *entry;
	GDataEntryPrivate *priv;
	xmlChar *value = NULL;
	xmlOutputBufferPtr buf;
	gchar *xmlString;

	g_return_val_if_fail(doc != NULL, NULL);
	g_return_val_if_fail(cur != NULL, NULL);

	if (xmlStrcmp(cur->name, (xmlChar *)"entry")) {
		return NULL;
	}

	entry = gdata_entry_new ();
	priv  = GDATA_ENTRY_GET_PRIVATE(entry);
	buf = xmlAllocOutputBuffer (NULL);

	if (buf == NULL) {
		xmlString = NULL;
	}
	else {
		xmlNodeDumpOutput (buf, NULL, cur, 0, 1, NULL);
		xmlOutputBufferFlush (buf);

		if (buf->conv == NULL)
			xmlString = g_strdup ((gchar *)buf->buffer->content);
		else
			xmlString = g_strdup ((gchar *)buf->conv->content);
		xmlOutputBufferClose (buf);
	}

	priv->entry_xml = g_strdup (xmlString);
	cur = cur->xmlChildrenNode;
	while (cur != NULL) {

		if (!xmlStrcmp(cur->name, (xmlChar *)"author")) {
			priv->authors = g_slist_prepend(priv->authors, xmlnode_to_author(doc, cur));
		}
		else if (!xmlStrcmp(cur->name, (xmlChar *)"link")) {
			priv->links = g_slist_prepend(priv->links, xmlnode_to_link(doc, cur));
		}
		else if (!xmlStrcmp(cur->name, (xmlChar *)"category")) {
			priv->categories = g_slist_prepend(priv->categories, xmlnode_to_category(doc, cur));
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"where")) {
			priv->location = (gchar *)xmlGetProp (cur, (xmlChar *)"valueString");
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"eventStatus")) {
			priv->status = (gchar *)xmlGetProp (cur, (xmlChar *)"value");
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"visibility")) {
			priv->visibility = (gchar *)xmlNodeListGetString (doc, cur->xmlChildrenNode, 1);
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"when")) {
			priv->start_time = (gchar *)xmlGetProp (cur, (xmlChar *)"startTime");
			priv->end_time = (gchar *)xmlGetProp (cur, (xmlChar *)"endTime");
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"recurrence")) {
			priv->is_recurrent = TRUE;
		}

		else if (!xmlStrcmp (cur->name, (xmlChar *)"who")) {
			priv->attendees = g_slist_prepend (priv->attendees, xmlnode_to_attendee (doc, cur));
			priv->has_attendees = TRUE;
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"sendEventNotifications")) {
			priv->send_notification =(gchar *)xmlGetProp (cur, (xmlChar *)"value");
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"comments")) {
			/*FIXME Call _comment_to_xml_node */
		}
		else if (!xmlStrcmp(cur->name, (xmlChar *)"email")) {
			priv->email_addresses = g_slist_prepend(priv->email_addresses, xmlnode_to_email_address(doc, cur));
		}
		else if (!xmlStrcmp(cur->name, (xmlChar *)"im")) {
			priv->im_addresses = g_slist_prepend(priv->im_addresses, xmlnode_to_im_address(doc, cur));
		}
		else if (!xmlStrcmp(cur->name, (xmlChar *)"organization")) {
			priv->organizations = g_slist_prepend(priv->organizations, xmlnode_to_organization(doc, cur));
		}
		else if (!xmlStrcmp(cur->name, (xmlChar *)"phoneNumber")) {
			priv->phone_numbers = g_slist_prepend(priv->phone_numbers, xmlnode_to_phone_number(doc, cur));
		}
		else if (!xmlStrcmp(cur->name, (xmlChar *)"postalAddress")) {
			priv->postal_addresses = g_slist_prepend(priv->postal_addresses, xmlnode_to_postal_address(doc, cur));
		}
		else if (!xmlStrcmp (cur->name, (xmlChar *)"deleted")) {
			priv->is_deleted = TRUE;
		}

		else {
			value = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			g_hash_table_insert(priv->field_table, g_strdup((gchar *)cur->name),
					g_strdup((gchar *)value));
			xmlFree(value);
		}
		cur = cur->next;
	}

	return entry;
}
Exemplo n.º 23
0
void
entry_fill_from_node(Entry* e)
{
  gchar* tmp;
  GError* error = NULL;

  g_return_if_fail(e->node != NULL);
  
  tmp = my_xmlGetProp(e->node, "schema");
  
  if (tmp != NULL)
    {
      /* Filter any crap schemas that appear, some speed cost */
      gchar* why_bad = NULL;
      if (gconf_valid_key(tmp, &why_bad))
        {
          g_assert(why_bad == NULL);
          e->schema_name = g_strdup(tmp);
        }
      else
        {
          e->schema_name = NULL;
          gconf_log(GCL_WARNING, _("Ignoring schema name `%s', invalid: %s"),
                    tmp, why_bad);
          g_free(why_bad);
        }
          
      xmlFree(tmp);
    }
      
  tmp = my_xmlGetProp(e->node, "mtime");

  if (tmp != NULL)
    {
      e->mod_time = gconf_string_to_gulong(tmp);
      xmlFree(tmp);
    }
  else
    e->mod_time = 0;

  tmp = my_xmlGetProp(e->node, "muser");

  if (tmp != NULL)
    {
      e->mod_user = g_strdup(tmp);
      xmlFree(tmp);
    }
  else
    e->mod_user = NULL;

  entry_sync_if_needed(e);
  
  if (e->cached_value != NULL)
    gconf_value_free(e->cached_value);
  
  e->cached_value = node_extract_value(e->node, NULL, /* FIXME current locale as a guess */
                                       &error);

  if (e->cached_value)
    {
      g_return_if_fail(error == NULL);
      return;
    }
  else if (error != NULL)
    {
      /* Ignore errors from node_extract_value() if we got a schema name,
       * since the node's only purpose may be to store the schema name.
       */
      if (e->schema_name == NULL)
        gconf_log (GCL_WARNING,
                   _("Ignoring XML node `%s': %s"),
                   e->name, error->message);
      g_error_free(error);
    }
}
Exemplo n.º 24
0
int send_publish( publ_info_t* publ )
{
	str met = {"PUBLISH", 7};
	str* str_hdr = NULL;
	ua_pres_t* presentity= NULL;
	str* body= NULL;
	str* tuple_id= NULL;
	ua_pres_t* cb_param= NULL;
	unsigned int hash_code=0;
	str etag= {0, 0};
	int ver= 0;
	int result;
	int ret_code= 0;
	pua_event_t* ev= NULL;
	uac_req_t uac_r;
	db1_res_t *res=NULL;
	ua_pres_t dbpres; 
	str pres_uri={0,0}, watcher_uri={0,0}, extra_headers={0,0};
	int ret = -1;

	LM_DBG("pres_uri=%.*s\n", publ->pres_uri->len, publ->pres_uri->s );
	
	if (dbmode == PUA_DB_ONLY && pua_dbf.start_transaction)
	{
		if (pua_dbf.start_transaction(pua_db) < 0)
		{
			LM_ERR("in start_transaction\n");
			goto error;
		}
	}

	/* get event from list */
	ev= get_event(publ->event);
	if(ev== NULL)
	{
		LM_ERR("event not found in list\n");
		goto error;
	}	

	if (dbmode==PUA_DB_ONLY)
	{
		memset(&dbpres, 0, sizeof(dbpres));
		dbpres.pres_uri = &pres_uri;
		dbpres.watcher_uri = &watcher_uri;
		dbpres.extra_headers = &extra_headers;
		presentity = get_record_puadb(publ->id, publ->etag, &dbpres, &res);
	}
	else
	{
		ua_pres_t pres;

		memset(&pres, 0, sizeof(ua_pres_t));
		pres.pres_uri = publ->pres_uri;
		pres.flag = publ->source_flag;
		pres.id = publ->id;
		pres.event = publ->event;
		if(publ->etag)
			pres.etag = *publ->etag;

		hash_code= core_hash(publ->pres_uri, NULL, HASH_SIZE);
		lock_get(&HashT->p_records[hash_code].lock);
		presentity= search_htable(&pres, hash_code);
	}

	if(publ->etag && presentity== NULL)
	{
		if (dbmode!=PUA_DB_ONLY) 
			lock_release(&HashT->p_records[hash_code].lock);
		ret = 418;
		goto error;
	}

	if(publ->flag & INSERT_TYPE)
	{
		LM_DBG("Insert flag set\n");
		goto insert;
	}
	
	if(presentity== NULL)
	{
insert:	
		if (dbmode!=PUA_DB_ONLY) 
			lock_release(&HashT->p_records[hash_code].lock);
		LM_DBG("insert type\n"); 
		
		if(publ->flag & UPDATE_TYPE )
		{
			LM_DBG("UPDATE_TYPE and no record found \n");
			publ->flag= INSERT_TYPE;
		}
		if(publ->expires== 0)
		{
			LM_DBG("request for a publish with expires 0 and"
					" no record found\n");
			goto done;
			
		}
		if(publ->body== NULL)
		{
			LM_ERR("New PUBLISH and no body found- invalid request\n");
			ret = ERR_PUBLISH_NO_BODY;
			goto error;
		}
	}
	else
	{
		LM_DBG("record found in hash_table\n");
		publ->flag= UPDATE_TYPE;
		etag.s= (char*)pkg_malloc(presentity->etag.len* sizeof(char));
		if(etag.s== NULL)
		{
			LM_ERR("while allocating memory\n");
			if (dbmode!=PUA_DB_ONLY) 
				lock_release(&HashT->p_records[hash_code].lock);
			goto error;
		}
		memcpy(etag.s, presentity->etag.s, presentity->etag.len);
		etag.len= presentity->etag.len;

		if(presentity->tuple_id.s && presentity->tuple_id.len)
		{	
			/* get tuple_id*/
			tuple_id=(str*)pkg_malloc(sizeof(str));
			if(tuple_id== NULL)
			{
				LM_ERR("No more memory\n");
				if (dbmode!=PUA_DB_ONLY) 
					lock_release(&HashT->p_records[hash_code].lock);
				goto error;
			}	
			tuple_id->s= (char*)pkg_malloc(presentity->tuple_id.len* sizeof(char));
			if(tuple_id->s== NULL)
			{
				LM_ERR("No more memory\n");
				if (dbmode!=PUA_DB_ONLY) 
					lock_release(&HashT->p_records[hash_code].lock);
				goto error;
			}	
			memcpy(tuple_id->s, presentity->tuple_id.s, presentity->tuple_id.len);
			tuple_id->len= presentity->tuple_id.len;
		}

		if(publ->expires== 0)
		{
			LM_DBG("expires= 0- delete from hash table\n");
			if (dbmode!=PUA_DB_ONLY) 
				lock_release(&HashT->p_records[hash_code].lock);
			goto send_publish;
		}

		presentity->version++; 
		ver= presentity->version;

		if (dbmode==PUA_DB_ONLY)
		{ 
			update_version_puadb(presentity);
		}
		else
		{
			lock_release(&HashT->p_records[hash_code].lock);
		}
	}

	/* handle body */
	if(publ->body && publ->body->s)
	{
		ret_code= ev->process_body(publ, &body, ver, &tuple_id );
		if( ret_code< 0 || body== NULL)
		{
			LM_ERR("while processing body\n");
			if(body== NULL)
				LM_ERR("NULL body\n");
			goto error;
		}
	}
	if(tuple_id)
		LM_DBG("tuple_id= %.*s\n", tuple_id->len, tuple_id->s  );
	
send_publish:
	
	/* construct the callback parameter */
	if(etag.s && etag.len)
		publ->etag = &etag;

	cb_param= publish_cbparam(publ, body, tuple_id, REQ_OTHER);
	if(cb_param== NULL)
	{
		LM_ERR("constructing callback parameter\n");
		goto error;
	}

	if(publ->flag & UPDATE_TYPE)
		LM_DBG("etag:%.*s\n", etag.len, etag.s);
	str_hdr = publ_build_hdr((publ->expires< 0)?3600:publ->expires, ev, &publ->content_type, 
				(publ->flag & UPDATE_TYPE)?&etag:NULL, publ->extra_headers, (body)?1:0);

	if(str_hdr == NULL)
	{
		LM_ERR("while building extra_headers\n");
		goto error;
	}

	LM_DBG("publ->pres_uri:\n%.*s\n ", publ->pres_uri->len, publ->pres_uri->s);
	LM_DBG("str_hdr:\n%.*s %d\n ", str_hdr->len, str_hdr->s, str_hdr->len);
	if(body && body->len && body->s )
		LM_DBG("body:\n%.*s\n ", body->len, body->s);

	set_uac_req(&uac_r, &met, str_hdr, body, 0, TMCB_LOCAL_COMPLETED,
			publ_cback_func, (void*)cb_param);
	result= tmb.t_request(&uac_r,
			publ->pres_uri,			/*! Request-URI */
			publ->pres_uri,			/*! To */
			publ->pres_uri,			/*! From */
			&outbound_proxy		/*! Outbound proxy*/
			);

	if(result< 0)
	{
		LM_ERR("in t_request tm module function\n");
		goto error;
	}

done:
	ret = 0;

	if (dbmode == PUA_DB_ONLY && pua_dbf.end_transaction)
	{
		if (pua_dbf.end_transaction(pua_db) < 0)
		{
			LM_ERR("in end_transaction\n");
			goto error;
		}
	}
	goto finish;

error:
	ret = -1;
	if(cb_param)
		shm_free(cb_param);

	if (dbmode == PUA_DB_ONLY && pua_dbf.abort_transaction)
	{
		if (pua_dbf.abort_transaction(pua_db) < 0)
			LM_ERR("in abort_transaction\n");
	}

finish:
	if(etag.s)
		pkg_free(etag.s);

	if(body && ret_code)
	{
		if(body->s)
			xmlFree(body->s);
		pkg_free(body);
	}	
	if(str_hdr)
		pkg_free(str_hdr);
	if(tuple_id)
	{
		if(tuple_id->s)
			pkg_free(tuple_id->s);
		pkg_free(tuple_id);
	}
	free_results_puadb(res);

	return ret;
}
Exemplo n.º 25
0
static void
schema_subnode_extract_data(xmlNodePtr node, GConfSchema* sc)
{
  gchar* sd_str;
  gchar* locale_str;
  GError* error = NULL;
  
  sd_str = my_xmlGetProp(node, "short_desc");
  locale_str = my_xmlGetProp(node, "locale");
  
  if (sd_str)
    {
      gconf_schema_set_short_desc(sc, sd_str);
      xmlFree(sd_str);
    }

  if (locale_str)
    {
      gconf_log(GCL_DEBUG, "found locale `%s'", locale_str);
      gconf_schema_set_locale(sc, locale_str);
      xmlFree(locale_str);
    }
  else
    {
      gconf_log(GCL_DEBUG, "found <%s> with no locale setting",
                node->name ? node->name : (unsigned char*) "null");
    }
  
  if (node->xmlChildrenNode != NULL)
    {
      GConfValue* default_value = NULL;
      xmlChar* ld_str = NULL;
      GSList* bad_nodes = NULL;
      xmlNodePtr iter = node->xmlChildrenNode;

      while (iter != NULL)
        {
          if (iter->type == XML_ELEMENT_NODE)
            {
              if (default_value == NULL &&
                  strcmp((char *)iter->name, "default") == 0)
                {
                  default_value = node_extract_value(iter, NULL, &error);

                  if (error != NULL)
                    {
                      g_assert(default_value == NULL);
                      
                      gconf_log(GCL_WARNING, _("Failed reading default value for schema: %s"), 
                                error->message);
                      g_error_free(error);
                      error = NULL;
                      
                      bad_nodes = g_slist_prepend(bad_nodes, iter);
                    }
                }
              else if (ld_str == NULL &&
                       strcmp((char *)iter->name, "longdesc") == 0)
                {
                  ld_str = xmlNodeGetContent(iter);
                }
              else
                {
                  bad_nodes = g_slist_prepend(bad_nodes, iter);
                }
            }
          else
            bad_nodes = g_slist_prepend(bad_nodes, iter); /* what is this node? */

          iter = iter->next;
        }
      

      /* Remove the bad nodes from the parse tree */
      if (bad_nodes != NULL)
        {
          GSList* tmp = bad_nodes;
          
          while (tmp != NULL)
            {
              xmlUnlinkNode(tmp->data);
              xmlFreeNode(tmp->data);
              
              tmp = g_slist_next(tmp);
            }
          
          g_slist_free(bad_nodes);
        }

      if (default_value != NULL)
        gconf_schema_set_default_value_nocopy(sc, default_value);

      if (ld_str)
        {
          gconf_schema_set_long_desc(sc, (char *)ld_str);
          xmlFree(ld_str);
        }
    }
}
Exemplo n.º 26
0
static Image *ReadURLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MaxBufferExtent  8192

  char
    filename[MagickPathExtent];

  FILE
    *file;

  Image
    *image;

  ImageInfo
    *read_info;

  int
    unique_file;

  image=(Image *) NULL;
  read_info=CloneImageInfo(image_info);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  file=(FILE *) NULL;
  unique_file=AcquireUniqueFileResource(read_info->filename);
  if (unique_file != -1)
    file=fdopen(unique_file,"wb");
  if ((unique_file == -1) || (file == (FILE *) NULL))
    {
      ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
        read_info->filename);
      read_info=DestroyImageInfo(read_info);
      return((Image *) NULL);
    }
  (void) CopyMagickString(filename,image_info->magick,MagickPathExtent);
  (void) ConcatenateMagickString(filename,":",MagickPathExtent);
  LocaleLower(filename);
  (void) ConcatenateMagickString(filename,image_info->filename,
    MagickPathExtent);
  if (LocaleCompare(read_info->magick,"file") == 0)
    {
      (void) RelinquishUniqueFileResource(read_info->filename);
      unique_file=(-1);
      (void) CopyMagickString(read_info->filename,image_info->filename+2,
        MagickPathExtent);
    }
#if defined(MAGICKCORE_WINDOWS_SUPPORT) && \
    !(defined(__MINGW32__) || defined(__MINGW64__))
  (void) fclose(file);
  if (URLDownloadToFile(NULL,filename,read_info->filename,0,NULL) != S_OK)
    {
      ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
        filename);
      (void) RelinquishUniqueFileResource(read_info->filename);
      read_info=DestroyImageInfo(read_info);
      return((Image *) NULL);
    }
#else
#if defined(MAGICKCORE_XML_DELEGATE) && defined(LIBXML_FTP_ENABLED)
  if (LocaleCompare(read_info->magick,"ftp") == 0)
    {
      void
        *context;

      xmlNanoFTPInit();
      context=xmlNanoFTPNewCtxt(filename);
      if (context != (void *) NULL)
        {
          if (xmlNanoFTPConnect(context) >= 0)
            (void) xmlNanoFTPGet(context,GetFTPData,(void *) file,
              (char *) NULL);
          (void) xmlNanoFTPClose(context);
        }
    }
#endif
#if defined(MAGICKCORE_XML_DELEGATE) && defined(LIBXML_HTTP_ENABLED)
  if (LocaleCompare(read_info->magick,"http") == 0)
    {
      char
        buffer[MaxBufferExtent],
        *type;

      int
        bytes;

      void
        *context;

      type=(char *) NULL;
      context=xmlNanoHTTPMethod(filename,(const char *) NULL,
        (const char *) NULL,&type,(const char *) NULL,0);
      if (context != (void *) NULL)
        {
          ssize_t
            count;

          while ((bytes=xmlNanoHTTPRead(context,buffer,MaxBufferExtent)) > 0)
            count=(ssize_t) fwrite(buffer,bytes,1,file);
          (void) count;
          xmlNanoHTTPClose(context);
          xmlFree(type);
          xmlNanoHTTPCleanup();
        }
    }
#endif
  (void) fclose(file);
#endif
  {
    ExceptionInfo
      *sans;

    ImageInfo
      *clone_info;

    /*
      Guess image format from URL.
    */
    clone_info=CloneImageInfo(image_info);
    sans=AcquireExceptionInfo();
    (void) SetImageInfo(clone_info,0,sans);
    (void) CopyMagickString(read_info->magick,clone_info->magick,
      MagickPathExtent);
    clone_info=DestroyImageInfo(clone_info);
    sans=DestroyExceptionInfo(sans);
  }
  *read_info->magick='\0';
  image=ReadImage(read_info,exception);
  if (unique_file != -1)
    (void) RelinquishUniqueFileResource(read_info->filename);
  read_info=DestroyImageInfo(read_info);
  if (image != (Image *) NULL)
    GetPathComponent(image_info->filename,TailPath,image->filename);
  else
    {
      (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
        "NoDataReturned","`%s'",filename);
      return((Image *) NULL);
    }
  return(GetFirstImageInList(image));
}
Exemplo n.º 27
0
/* this actually works on any node,
   not just <entry>, such as the <car>
   and <cdr> nodes and the <li> nodes and the
   <default> node
*/
static GConfValue*
node_extract_value(xmlNodePtr node, const gchar** locales, GError** err)
{
  GConfValue* value = NULL;
  gchar* type_str;
  GConfValueType type = GCONF_VALUE_INVALID;
  const gchar* default_locales[] = { "C", NULL };
  
  if (locales == NULL)
    locales = default_locales;
  
  type_str = my_xmlGetProp(node, "type");

  if (type_str == NULL)
    {
      gconf_set_error(err, GCONF_ERROR_PARSE_ERROR,
                      _("No \"type\" attribute for <%s> node"),
                      (node->name ? (char*)node->name : "(nil)"));
      return NULL;
    }
      
  type = gconf_value_type_from_string(type_str);

  xmlFree(type_str);
  
  switch (type)
    {
    case GCONF_VALUE_INVALID:
      {
        gconf_set_error(err, GCONF_ERROR_PARSE_ERROR,
                        _("A node has unknown \"type\" attribute `%s', ignoring"), type_str);
        return NULL;
      }
      break;
    case GCONF_VALUE_INT:
    case GCONF_VALUE_BOOL:
    case GCONF_VALUE_FLOAT:
      {
        gchar* value_str;
        
        value_str = my_xmlGetProp(node, "value");
        
        if (value_str == NULL)
          {
            gconf_set_error(err, GCONF_ERROR_PARSE_ERROR,
                            _("No \"value\" attribute for node"));
            return NULL;
          }
            
        value = gconf_value_new_from_string(type, value_str, err);

        xmlFree(value_str);

        g_return_val_if_fail( (value != NULL) ||
                              (err == NULL) ||
                              (*err != NULL),
                              NULL );
        
        return value;
      }
      break;
    case GCONF_VALUE_STRING:
      {
        xmlNodePtr iter;
        
        iter = node->xmlChildrenNode;

        while (iter != NULL)
          {
            if (iter->type == XML_ELEMENT_NODE)
              {
                GConfValue* v = NULL;

                if (strcmp((char *)iter->name, "stringvalue") == 0)
                  {
                    gchar* s;

                    s = (gchar *)xmlNodeGetContent(iter);

                    v = gconf_value_new(GCONF_VALUE_STRING);

                    /* strdup() caused purely by g_free()/free()
                       difference */
                    gconf_value_set_string(v, s ? s : "");
                    if (s)
                      xmlFree(s);
                        
                    return v;
                  }
                else
                  {
                    /* What the hell is this? */
                    gconf_log(GCL_WARNING,
                              _("Didn't understand XML node <%s> inside an XML list node"),
                              iter->name ? iter->name : (guchar*)"???");
                  }
              }
            iter = iter->next;
          }
        return NULL;
      }
      break;      
    case GCONF_VALUE_SCHEMA:
      return schema_node_extract_value(node, locales);
      break;
    case GCONF_VALUE_LIST:
      {
        xmlNodePtr iter;
        GSList* values = NULL;
        GConfValueType list_type = GCONF_VALUE_INVALID;

        {
          gchar* s;
          s = my_xmlGetProp(node, "ltype");
          if (s != NULL)
            {
              list_type = gconf_value_type_from_string(s);
              xmlFree(s);
            }
        }

        switch (list_type)
          {
          case GCONF_VALUE_INVALID:
          case GCONF_VALUE_LIST:
          case GCONF_VALUE_PAIR:
            gconf_set_error(err, GCONF_ERROR_PARSE_ERROR,
                            _("Invalid type (list, pair, or unknown) in a list node"));
              
            return NULL;
          default:
            break;
          }
        
        iter = node->xmlChildrenNode;

        while (iter != NULL)
          {
            if (iter->type == XML_ELEMENT_NODE)
              {
                GConfValue* v = NULL;
                if (strcmp((char*)iter->name, "li") == 0)
                  {
                    
                    v = node_extract_value(iter, locales, err);
                    if (v == NULL)
                      {
                        if (err && *err)
                          {
                            gconf_log(GCL_WARNING,
                                      _("Bad XML node: %s"),
                                      (*err)->message);
                            /* avoid pile-ups */
                            g_clear_error(err);
                          }
                      }
                    else if (v->type != list_type)
                      {
                        gconf_log(GCL_WARNING, _("List contains a badly-typed node (%s, should be %s)"),
                                  gconf_value_type_to_string(v->type),
                                  gconf_value_type_to_string(list_type));
                        gconf_value_free(v);
                        v = NULL;
                      }
                  }
                else
                  {
                    /* What the hell is this? */
                    gconf_log(GCL_WARNING,
                              _("Didn't understand XML node <%s> inside an XML list node"),
                              iter->name ? iter->name : (guchar*)"???");
                  }

                if (v != NULL)
                  values = g_slist_prepend(values, v);
              }
            iter = iter->next;
          }
        
        /* put them in order, set the value */
        values = g_slist_reverse(values);

        value = gconf_value_new(GCONF_VALUE_LIST);

        gconf_value_set_list_type(value, list_type);
        gconf_value_set_list_nocopy(value, values);

        return value;
      }
      break;
    case GCONF_VALUE_PAIR:
      {
        GConfValue* car = NULL;
        GConfValue* cdr = NULL;
        xmlNodePtr iter;
        
        iter = node->xmlChildrenNode;

        while (iter != NULL)
          {
            if (iter->type == XML_ELEMENT_NODE)
              {
                if (car == NULL && strcmp((char *)iter->name, "car") == 0)
                  {
                    car = node_extract_value(iter, locales, err);
                    if (car == NULL)
                      {
                        if (err && *err)
                          {
                            gconf_log(GCL_WARNING,
                                      _("Ignoring bad car from XML pair: %s"),
                                      (*err)->message);
                            /* prevent pile-ups */
                            g_clear_error(err);
                          }
                      }
                    else if (car->type == GCONF_VALUE_LIST ||
                             car->type == GCONF_VALUE_PAIR)
                      {
                        gconf_log(GCL_WARNING, _("parsing XML file: lists and pairs may not be placed inside a pair"));
                        gconf_value_free(car);
                        car = NULL;
                      }
                  }
                else if (cdr == NULL && strcmp((char *)iter->name, "cdr") == 0)
                  {
                    cdr = node_extract_value(iter, locales, err);
                    if (cdr == NULL)
                      {
                        if (err && *err)
                          {
                            gconf_log(GCL_WARNING,
                                      _("Ignoring bad cdr from XML pair: %s"),
                                      (*err)->message);
                            /* avoid pile-ups */
                            g_clear_error(err);
                          }
                      }
                    else if (cdr->type == GCONF_VALUE_LIST ||
                             cdr->type == GCONF_VALUE_PAIR)
                      {
                        gconf_log(GCL_WARNING,
                                  _("parsing XML file: lists and pairs may not be placed inside a pair"));
                        gconf_value_free(cdr);
                        cdr = NULL;
                      }
                  }
                else
                  {
                    /* What the hell is this? */
                    gconf_log(GCL_WARNING,
                              _("Didn't understand XML node <%s> inside an XML pair node"),
                              iter->name ? (gchar*)iter->name : "???");                    
                  }
              }
            iter = iter->next;
          }

        /* Return the pair if we got both halves */
        if (car && cdr)
          {
            value = gconf_value_new(GCONF_VALUE_PAIR);
            gconf_value_set_car_nocopy(value, car);
            gconf_value_set_cdr_nocopy(value, cdr);

            return value;
          }
        else
          {
            gconf_log(GCL_WARNING, _("Didn't find car and cdr for XML pair node"));
            if (car)
              {
                g_assert(cdr == NULL);
                gconf_value_free(car);
                gconf_set_error(err, GCONF_ERROR_PARSE_ERROR,
                                _("Missing cdr from pair of values in XML file"));
              }
            else if (cdr)
              {
                g_assert(car == NULL);
                gconf_value_free(cdr);
                gconf_set_error(err, GCONF_ERROR_PARSE_ERROR,
                                _("Missing car from pair of values in XML file"));
              }
            else
              {
                gconf_set_error(err, GCONF_ERROR_PARSE_ERROR,
                                _("Missing both car and cdr values from pair in XML file"));
              }

            return NULL;
          }
      }
      break;
    default:
      g_assert_not_reached();
      return NULL;
      break;
    }
}
Exemplo n.º 28
0
bool xccdf_benchmark_parse(struct xccdf_item * benchmark, xmlTextReaderPtr reader)
{
	XCCDF_ASSERT_ELEMENT(reader, XCCDFE_BENCHMARK);
	assert(benchmark != NULL);
	if (benchmark->type != XCCDF_BENCHMARK)
		return false;

	xccdf_benchmark_set_schema_version(XBENCHMARK(benchmark), xccdf_detect_version_parser(reader));

	if (!xccdf_item_process_attributes(benchmark, reader)) {
		xccdf_benchmark_free(XBENCHMARK(benchmark));
		return false;
	}
	benchmark->sub.benchmark.style = xccdf_attribute_copy(reader, XCCDFA_STYLE);
	benchmark->sub.benchmark.style_href = xccdf_attribute_copy(reader, XCCDFA_STYLE_HREF);
    benchmark->sub.benchmark.lang = (char *) xmlTextReaderXmlLang(reader);
	if (xccdf_attribute_has(reader, XCCDFA_RESOLVED))
		benchmark->item.flags.resolved = xccdf_attribute_get_bool(reader, XCCDFA_RESOLVED);

	int depth = oscap_element_depth(reader) + 1;

	while (oscap_to_start_element(reader, depth)) {
		struct xccdf_model *parsed_model;

		switch (xccdf_element_get(reader)) {
		case XCCDFE_NOTICE:
				oscap_list_add(benchmark->sub.benchmark.notices, xccdf_notice_new_parse(reader));
				break;
		case XCCDFE_FRONT_MATTER:
				oscap_list_add(benchmark->sub.benchmark.front_matter, oscap_text_new_parse(XCCDF_TEXT_HTMLSUB, reader));
			break;
		case XCCDFE_REAR_MATTER:
				oscap_list_add(benchmark->sub.benchmark.rear_matter, oscap_text_new_parse(XCCDF_TEXT_HTMLSUB, reader));
			break;
		case XCCDFE_PLATFORM:
			oscap_list_add(benchmark->item.platforms, xccdf_attribute_copy(reader, XCCDFA_IDREF));
			break;
		case XCCDFE_MODEL:
			parsed_model = xccdf_model_new_xml(reader);

			// we won't add the implied default scoring model, it is already in the benchmark
			if (strcmp(xccdf_model_get_system(parsed_model), "urn:xccdf:scoring:default") != 0)
				assume_ex(xccdf_benchmark_add_model(XBENCHMARK(benchmark), parsed_model), false);
			else
				xccdf_model_free(parsed_model);

			break;
		case XCCDFE_PLAIN_TEXT:{
				const char *id = xccdf_attribute_get(reader, XCCDFA_ID);
				char *data = (char *)xmlTextReaderReadInnerXml(reader);
				if (id)
					oscap_list_add(benchmark->sub.benchmark.plain_texts,
							xccdf_plain_text_new_fill(id,
							data == NULL ? "" : data));
				xmlFree(data);
				break;
			}
		case XCCDFE_CPE_LIST:{
			struct cpe_parser_ctx *ctx = cpe_parser_ctx_from_reader(reader);
			xccdf_benchmark_set_cpe_list(XBENCHMARK(benchmark), cpe_dict_model_parse(ctx));
			cpe_parser_ctx_free(ctx);
			break;
			}
		case XCCDFE_CPE2_PLATFORMSPEC:
			xccdf_benchmark_set_cpe_lang_model(XBENCHMARK(benchmark), cpe_lang_model_parse(reader));
			break;
		case XCCDFE_PROFILE:
			oscap_list_add(benchmark->sub.benchmark.profiles, xccdf_profile_parse(reader, benchmark));
			break;
		case XCCDFE_GROUP:
		case XCCDFE_RULE:
			xccdf_content_parse(reader, benchmark);
			break;
		case XCCDFE_VALUE:
			oscap_list_add(benchmark->sub.benchmark.values, xccdf_value_parse(reader, benchmark));
			break;
		case XCCDFE_TESTRESULT:
			assume_ex(xccdf_benchmark_add_result(XBENCHMARK(benchmark), xccdf_result_new_parse(reader)), false);
			break;
		default:
			if (!xccdf_item_process_element(benchmark, reader))
				dW("Encountered an unknown element '%s' while parsing XCCDF benchmark.",
				   xmlTextReaderConstLocalName(reader));
		}
		xmlTextReaderRead(reader);
	}

	return true;
}
Exemplo n.º 29
0
static gboolean
do_configure(Log4gConfigurator *base, const char *uri,
        G_GNUC_UNUSED Log4gLoggerRepository *repository, GError **error)
{
	struct Private *priv = GET_PRIVATE(base);
	gboolean status = TRUE;
	GString *string = g_string_sized_new(128);
	if (!string) {
		g_set_error(error, LOG4G_ERROR, LOG4G_ERROR_FAILURE,
				Q_("g_string_new() returned NULL"));
		return FALSE;
	}
	xmlSetGenericErrorFunc(string, error_handler);
	gint options =
		XML_PARSE_NOWARNING | XML_PARSE_NOERROR | XML_PARSE_NOBLANKS;
	if (g_getenv("LOG4G_PARSE_DTDVALID")) {
		options |= XML_PARSE_DTDVALID;
	}
	/* read XML file */
	xmlDocPtr doc = xmlCtxtReadFile(priv->ctx, uri, NULL, options);
	if (!doc) {
		g_set_error(error, LOG4G_ERROR, LOG4G_ERROR_FAILURE,
				Q_("failed to parse configuration"));
		status = FALSE;
		goto exit;
	}
	/* check root element */
	xmlNodePtr node = xmlDocGetRootElement(doc);
	if (!node) {
		g_set_error(error, LOG4G_ERROR, LOG4G_ERROR_FAILURE,
				Q_("invalid document: document is empty"));
		status = FALSE;
		goto exit;
	}
	if (xmlStrcmp(node->name, (const xmlChar *)"configuration")) {
		g_set_error(error, LOG4G_ERROR, LOG4G_ERROR_FAILURE,
				Q_("%s: invalid root element (expected "
					"log4g:configuration)"),
				node->name);
		status = FALSE;
		goto exit;
	}
	/* parse root attributes */
	xmlChar *att = xmlGetProp(node, (const xmlChar *)"debug");
	if (att) {
		if (!xmlStrcmp(att, (const xmlChar *)"true")) {
			log4g_set_internal_debugging(TRUE);
		} else if (!xmlStrcmp(att, (const xmlChar *)"false")) {
			log4g_set_internal_debugging(FALSE);
		} else if (!xmlStrcmp(att, (const xmlChar *)"null")) {
			log4g_log_warn(Q_("%s: ignoring `debug' attribute"),
					att);
		} else {
			log4g_log_error(Q_("%s: invalid value for attribute "
						"`debug'"), att);
		}
		xmlFree(att);
	}
	att = xmlGetProp(node, (const xmlChar *)"reset");
	if (att) {
		if (!xmlStrcmp(att, (const xmlChar *)"true")) {
			log4g_log_manager_reset_configuration();
		}
		xmlFree(att);
	}
	att = xmlGetProp(node, (const xmlChar *)"threshold");
	if (att) {
		Log4gLevel *level;
		Log4gLoggerRepository *repository =
			log4g_log_manager_get_logger_repository();
		if (!xmlStrcmp(att, (const xmlChar *)"all")) {
			level = log4g_level_ALL();
		} else if (!xmlStrcmp(att, (const xmlChar *)"trace")) {
			level = log4g_level_TRACE();
		} else if (!xmlStrcmp(att, (const xmlChar *)"debug")) {
			level = log4g_level_DEBUG();
		} else if (!xmlStrcmp(att, (const xmlChar *)"info")) {
			level = log4g_level_INFO();
		} else if (!xmlStrcmp(att, (const xmlChar *)"warn")) {
			level = log4g_level_WARN();
		} else if (!xmlStrcmp(att, (const xmlChar *)"error")) {
			level = log4g_level_ERROR();
		} else if (!xmlStrcmp(att, (const xmlChar *)"fatal")) {
			level = log4g_level_FATAL();
		} else if (!xmlStrcmp(att, (const xmlChar *)"off")) {
			level = log4g_level_OFF();
		} else if (!xmlStrcmp(att, (const xmlChar *)"null")) {
			level = NULL;
		} else {
			log4g_log_error(Q_("%s: invalid repository threshold"), att);
			level = NULL;
		}
		if (level) {
			log4g_logger_repository_set_threshold(repository,
					level);
		}
		xmlFree(att);
	}
	/* parse document */
	node = node->xmlChildrenNode;
	while (node) {
		if (!xmlStrcmp(node->name, (const xmlChar *)"appender")) {
			Log4gAppender *appender = parse_appender(base, node);
			if (appender) {
				g_object_unref(appender);
			}
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"logger")) {
			parse_logger(base, node);
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"root")) {
			parse_root(base, node);
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"object")) {
			parse_object(base, node);
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"text")) {
			log4g_log_warn(Q_("invalid text element"));
		} else if (!xmlStrcmp(node->name, (const xmlChar *)"comment")) {
			/* do nothing */
		} else {
			log4g_log_warn(Q_("%s: invalid element"), node->name);
		}
		node = node->next;
	}
exit:
	if (string) {
		g_string_free(string, TRUE);
	}
	if (doc) {
		xmlFreeDoc(doc);
	}
	return status;
}
Exemplo n.º 30
0
void dt_lightroom_import(int imgid, dt_develop_t *dev, gboolean iauto)
{
  gboolean refresh_needed = FALSE;
  char imported[256] = { 0 };

  // Get full pathname
  char *pathname = dt_get_lightroom_xmp(imgid);

  if(!pathname)
  {
    if(!iauto) dt_control_log(_("cannot find lightroom XMP!"));
    return;
  }

  // Load LR xmp

  xmlDocPtr doc;
  xmlNodePtr entryNode;

  // Parse xml document

  doc = xmlParseEntity(pathname);

  if(doc == NULL)
  {
    g_free(pathname);
    return;
  }

  // Enter first node, xmpmeta

  entryNode = xmlDocGetRootElement(doc);

  if(entryNode == NULL)
  {
    g_free(pathname);
    xmlFreeDoc(doc);
    return;
  }

  if(xmlStrcmp(entryNode->name, (const xmlChar *)"xmpmeta"))
  {
    if(!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
    g_free(pathname);
    return;
  }

  // Check that this is really a Lightroom document

  xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);

  if(xpathCtx == NULL)
  {
    g_free(pathname);
    xmlFreeDoc(doc);
    return;
  }

  xmlXPathRegisterNs(xpathCtx, BAD_CAST "stEvt", BAD_CAST "http://ns.adobe.com/xap/1.0/sType/ResourceEvent#");

  xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression((const xmlChar *)"//@stEvt:softwareAgent", xpathCtx);

  if(xpathObj == NULL)
  {
    if(!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
    xmlXPathFreeContext(xpathCtx);
    g_free(pathname);
    xmlFreeDoc(doc);
    return;
  }

  xmlNodeSetPtr xnodes = xpathObj->nodesetval;

  if(xnodes != NULL && xnodes->nodeNr > 0)
  {
    xmlNodePtr xnode = xnodes->nodeTab[0];
    xmlChar *value = xmlNodeListGetString(doc, xnode->xmlChildrenNode, 1);

    if(!strstr((char *)value, "Lightroom"))
    {
      xmlXPathFreeContext(xpathCtx);
      xmlXPathFreeObject(xpathObj);
      xmlFreeDoc(doc);
      xmlFree(value);
      if(!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
      g_free(pathname);
      return;
    }
    xmlFree(value);
  }
  else
  {
    xmlXPathFreeObject(xpathObj);
    xmlXPathFreeContext(xpathCtx);
    if(!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
    g_free(pathname);
    return;
  }

  xmlXPathFreeObject(xpathObj);
  xmlXPathFreeContext(xpathCtx);

  // Go safely to Description node

  if(entryNode) entryNode = entryNode->xmlChildrenNode;
  if(entryNode) entryNode = entryNode->next;
  if(entryNode) entryNode = entryNode->xmlChildrenNode;
  if(entryNode) entryNode = entryNode->next;

  if(!entryNode || xmlStrcmp(entryNode->name, (const xmlChar *)"Description"))
  {
    if(!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
    g_free(pathname);
    return;
  }
  g_free(pathname);

  //  Look for attributes in the Description

  dt_iop_clipping_params_t pc;
  memset(&pc, 0, sizeof(pc));
  gboolean has_crop = FALSE;

  dt_iop_flip_params_t pf;
  memset(&pf, 0, sizeof(pf));
  gboolean has_flip = FALSE;

  dt_iop_exposure_params_t pe;
  memset(&pe, 0, sizeof(pe));
  gboolean has_exposure = FALSE;

  dt_iop_vignette_params_t pv;
  memset(&pv, 0, sizeof(pv));
  gboolean has_vignette = FALSE;

  dt_iop_grain_params_t pg;
  memset(&pg, 0, sizeof(pg));
  gboolean has_grain = FALSE;

  dt_iop_spots_params_t ps;
  memset(&ps, 0, sizeof(ps));
  gboolean has_spots = FALSE;

  typedef enum lr_curve_kind_t
  {
    linear = 0,
    medium_contrast = 1,
    string_contrast = 2,
    custom = 3
  } lr_curve_kind_t;

#define MAX_PTS 20
  dt_iop_tonecurve_params_t ptc;
  memset(&ptc, 0, sizeof(ptc));
  int ptc_value[4] = { 0, 0, 0, 0 };
  float ptc_split[3] = { 0.0, 0.0, 0.0 };
  lr_curve_kind_t curve_kind = linear;
  int curve_pts[MAX_PTS][2];
  int n_pts = 0;

  dt_iop_colorzones_params_t pcz;
  memset(&pcz, 0, sizeof(pcz));
  gboolean has_colorzones = FALSE;

  dt_iop_splittoning_params_t pst;
  memset(&pst, 0, sizeof(pst));
  gboolean has_splittoning = FALSE;

  dt_iop_bilat_params_t pbl;
  memset(&pbl, 0, sizeof(pbl));
  gboolean has_bilat = FALSE;

  gboolean has_tags = FALSE;

  int rating = 0;
  gboolean has_rating = FALSE;

  gdouble lat = 0, lon = 0;
  gboolean has_gps = FALSE;

  int color = 0;
  gboolean has_colorlabel = FALSE;

  float fratio = 0;                // factor ratio image
  float crop_roundness = 0;        // from lightroom
  int n_import = 0;                // number of iop imported
  const float hfactor = 3.0 / 9.0; // hue factor adjustment (use 3 out of 9 boxes in colorzones)
  const float lfactor = 4.0 / 9.0; // lightness factor adjustment (use 4 out of 9 boxes in colorzones)
  int iwidth = 0, iheight = 0;     // image width / height
  int orientation = 1;

  xmlAttr *attribute = entryNode->properties;

  while(attribute && attribute->name && attribute->children)
  {
    xmlChar *value = xmlNodeListGetString(entryNode->doc, attribute->children, 1);
    if(!xmlStrcmp(attribute->name, (const xmlChar *)"CropTop"))
      pc.cy = g_ascii_strtod((char *)value, NULL);
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"CropRight"))
      pc.cw = g_ascii_strtod((char *)value, NULL);
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"CropLeft"))
      pc.cx = g_ascii_strtod((char *)value, NULL);
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"CropBottom"))
      pc.ch = g_ascii_strtod((char *)value, NULL);
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"CropAngle"))
      pc.angle = -g_ascii_strtod((char *)value, NULL);
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ImageWidth"))
      iwidth = atoi((char *)value);
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ImageLength"))
      iheight = atoi((char *)value);
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"Orientation"))
    {
      orientation = atoi((char *)value);
      if(dev != NULL && ((dev->image_storage.orientation == 6 && orientation != 6)
                         || (dev->image_storage.orientation == 5 && orientation != 8)
                         || (dev->image_storage.orientation == 0 && orientation != 1)))
        has_flip = TRUE;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HasCrop"))
    {
      if(!xmlStrcmp(value, (const xmlChar *)"True")) has_crop = TRUE;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"Blacks2012"))
    {
      int v = atoi((char *)value);
      if(v != 0)
      {
        has_exposure = TRUE;
        pe.black = lr2dt_blacks((float)v);
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"Exposure2012"))
    {
      float v = g_ascii_strtod((char *)value, NULL);
      if(v != 0.0)
      {
        has_exposure = TRUE;
        pe.exposure = lr2dt_exposure(v);
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"PostCropVignetteAmount"))
    {
      int v = atoi((char *)value);
      if(v != 0)
      {
        has_vignette = TRUE;
        pv.brightness = lr2dt_vignette_gain((float)v);
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"PostCropVignetteMidpoint"))
    {
      int v = atoi((char *)value);
      pv.scale = lr2dt_vignette_midpoint((float)v);
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"PostCropVignetteStyle"))
    {
      int v = atoi((char *)value);
      if(v == 1) // Highlight Priority
        pv.saturation = -0.300;
      else // Color Priority & Paint Overlay
        pv.saturation = -0.200;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"PostCropVignetteFeather"))
    {
      int v = atoi((char *)value);
      if(v != 0) pv.falloff_scale = (float)v;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"PostCropVignetteRoundness"))
    {
      int v = atoi((char *)value);
      crop_roundness = (float)v;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"GrainAmount"))
    {
      int v = atoi((char *)value);
      if(v != 0)
      {
        has_grain = TRUE;
        pg.strength = lr2dt_grain_amount((float)v);
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"GrainFrequency"))
    {
      int v = atoi((char *)value);
      if(v != 0) pg.scale = lr2dt_grain_frequency((float)v);
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ParametricShadows"))
    {
      ptc_value[0] = atoi((char *)value);
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ParametricDarks"))
    {
      ptc_value[1] = atoi((char *)value);
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ParametricLights"))
    {
      ptc_value[2] = atoi((char *)value);
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ParametricHighlights"))
    {
      ptc_value[3] = atoi((char *)value);
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ParametricShadowSplit"))
    {
      ptc_split[0] = g_ascii_strtod((char *)value, NULL) / 100.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ParametricMidtoneSplit"))
    {
      ptc_split[1] = g_ascii_strtod((char *)value, NULL) / 100.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ParametricHighlightSplit"))
    {
      ptc_split[2] = g_ascii_strtod((char *)value, NULL) / 100.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"ToneCurveName2012"))
    {
      if(!xmlStrcmp(value, (const xmlChar *)"Linear"))
        curve_kind = linear;
      else if(!xmlStrcmp(value, (const xmlChar *)"Medium Contrast"))
        curve_kind = medium_contrast;
      else if(!xmlStrcmp(value, (const xmlChar *)"Strong Contrast"))
        curve_kind = medium_contrast;
      else if(!xmlStrcmp(value, (const xmlChar *)"Custom"))
        curve_kind = custom;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentRed"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][0] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentOrange"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][1] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentYellow"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][2] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentGreen"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][3] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentAqua"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][4] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentBlue"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][5] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentPurple"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][6] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SaturationAdjustmentMagenta"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[1][7] = 0.5 + (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentRed"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][0] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentOrange"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][1] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentYellow"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][2] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentGreen"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][3] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentAqua"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][4] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentBlue"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][5] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentPurple"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][6] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"LuminanceAdjustmentMagenta"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[0][7] = 0.5 + lfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentRed"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][0] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentOrange"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][1] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentYellow"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][2] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentGreen"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][3] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentAqua"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][4] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentBlue"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][5] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentPurple"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][6] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"HueAdjustmentMagenta"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_colorzones = TRUE;
      pcz.equalizer_y[2][7] = 0.5 + hfactor * (float)v / 200.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SplitToningShadowHue"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_splittoning = TRUE;
      pst.shadow_hue = (float)v / 255.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SplitToningShadowSaturation"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_splittoning = TRUE;
      pst.shadow_saturation = (float)v / 100.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SplitToningHighlightHue"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_splittoning = TRUE;
      pst.highlight_hue = (float)v / 255.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SplitToningHighlightSaturation"))
    {
      int v = atoi((char *)value);
      if(v != 0) has_splittoning = TRUE;
      pst.highlight_saturation = (float)v / 100.0;
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"SplitToningBalance"))
    {
      float v = g_ascii_strtod((char *)value, NULL);
      pst.balance = lr2dt_splittoning_balance(v);
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"Clarity2012"))
    {
      int v = atoi((char *)value);
      if(v != 0)
      {
        has_bilat = TRUE;
        pbl.detail = lr2dt_clarity((float)v);
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"Rating"))
    {
      int v = atoi((char *)value);
      if(v != 0)
      {
        rating = v;
        has_rating = TRUE;
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"GPSLatitude"))
    {
      int deg;
      double msec;
      char d;

      if(sscanf((const char *)value, "%d,%lf%c", &deg, &msec, &d))
      {
        lat = deg + msec / 60.0;
        if(d == 'S') lat = -lat;
        has_gps = TRUE;
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"GPSLongitude"))
    {
      int deg;
      double msec;
      char d;

      if(sscanf((const char *)value, "%d,%lf%c", &deg, &msec, &d))
      {
        lon = deg + msec / 60.0;
        if(d == 'W') lon = -lon;
        has_gps = TRUE;
      }
    }
    else if(!xmlStrcmp(attribute->name, (const xmlChar *)"Label"))
    {
      for(int i = 0; value[i]; i++) value[i] = tolower(value[i]);

      if(!strcmp((char *)value, _("red")))
        color = 0;
      else if(!strcmp((char *)value, _("yellow")))
        color = 1;
      else if(!strcmp((char *)value, _("green")))
        color = 2;
      else if(!strcmp((char *)value, _("blue")))
        color = 3;
      else
        // just an else here to catch all other cases as on lightroom one can
        // change the names of labels. So purple and the user's defined labels
        // will be mapped to purple on darktable.
        color = 4;

      has_colorlabel = TRUE;
    }

    xmlFree(value);
    attribute = attribute->next;
  }

  //  Look for tags (subject/Bag/* and RetouchInfo/seq/*)

  entryNode = entryNode->xmlChildrenNode;
  if(entryNode) entryNode = entryNode->next;

  while(entryNode)
  {
    if(dev == NULL && (!xmlStrcmp(entryNode->name, (const xmlChar *)"subject")
                       || !xmlStrcmp(entryNode->name, (const xmlChar *)"hierarchicalSubject")))
    {
      xmlNodePtr tagNode = entryNode;

      tagNode = tagNode->xmlChildrenNode;
      tagNode = tagNode->next;
      tagNode = tagNode->xmlChildrenNode;
      tagNode = tagNode->next;

      while(tagNode)
      {
        if(!xmlStrcmp(tagNode->name, (const xmlChar *)"li"))
        {
          xmlChar *value = xmlNodeListGetString(doc, tagNode->xmlChildrenNode, 1);
          guint tagid = 0;

          if(!dt_tag_exists((char *)value, &tagid)) dt_tag_new((char *)value, &tagid);

          dt_tag_attach(tagid, imgid);
          has_tags = TRUE;
          xmlFree(value);
        }
        tagNode = tagNode->next;
      }
    }
    else if(dev != NULL && !xmlStrcmp(entryNode->name, (const xmlChar *)"RetouchInfo"))
    {
      xmlNodePtr riNode = entryNode;

      riNode = riNode->xmlChildrenNode;
      riNode = riNode->next;
      riNode = riNode->xmlChildrenNode;
      riNode = riNode->next;

      while(riNode)
      {
        if(!xmlStrcmp(riNode->name, (const xmlChar *)"li"))
        {
          xmlChar *value = xmlNodeListGetString(doc, riNode->xmlChildrenNode, 1);
          spot_t *p = &ps.spot[ps.num_spots];
          if(sscanf((const char *)value, "centerX = %f, centerY = %f, radius = %f, sourceState = %*[a-zA-Z], "
                                         "sourceX = %f, sourceY = %f",
                    &(p->x), &(p->y), &(p->radius), &(p->xc), &(p->yc)))
          {
            ps.num_spots++;
            has_spots = TRUE;
          }
          xmlFree(value);
        }
        if(ps.num_spots == MAX_SPOTS) break;
        riNode = riNode->next;
      }
    }
    else if(dev != NULL && !xmlStrcmp(entryNode->name, (const xmlChar *)"ToneCurvePV2012"))
    {
      xmlNodePtr tcNode = entryNode;

      tcNode = tcNode->xmlChildrenNode;
      tcNode = tcNode->next;
      tcNode = tcNode->xmlChildrenNode;
      tcNode = tcNode->next;

      while(tcNode)
      {
        if(!xmlStrcmp(tcNode->name, (const xmlChar *)"li"))
        {
          xmlChar *value = xmlNodeListGetString(doc, tcNode->xmlChildrenNode, 1);

          if(sscanf((const char *)value, "%d, %d", &(curve_pts[n_pts][0]), &(curve_pts[n_pts][1]))) n_pts++;
          xmlFree(value);
        }
        if(n_pts == MAX_PTS) break;
        tcNode = tcNode->next;
      }
    }
    entryNode = entryNode->next;
  }

  xmlFreeDoc(doc);

  //  Integrates into the history all the imported iop

  if(dev != NULL && dt_image_is_raw(&dev->image_storage))
  {
    // set colorin to cmatrix which is the default from Adobe (so closer to what Lightroom does)
    dt_iop_colorin_params_t pci = (dt_iop_colorin_params_t){ "cmatrix", DT_INTENT_PERCEPTUAL };

    dt_add_hist(imgid, "colorin", (dt_iop_params_t *)&pci, sizeof(dt_iop_colorin_params_t), imported,
                sizeof(imported), LRDT_COLORIN_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_crop)
  {
    pc.k_sym = 0;
    pc.k_apply = 0;
    pc.crop_auto = 0;
    pc.k_h = pc.k_v = 0;
    pc.k_type = 0;
    pc.kxa = pc.kxd = 0.2f;
    pc.kxc = pc.kxb = 0.8f;
    pc.kya = pc.kyb = 0.2f;
    pc.kyc = pc.kyd = 0.8f;
    float tmp;

    if(has_crop)
    {
      // adjust crop data according to the rotation

      switch(dev->image_storage.orientation)
      {
        case 5: // portrait - counter-clockwise
          tmp = pc.ch;
          pc.ch = 1.0 - pc.cx;
          pc.cx = pc.cy;
          pc.cy = 1.0 - pc.cw;
          pc.cw = tmp;
          break;
        case 6: // portrait - clockwise
          tmp = pc.ch;
          pc.ch = pc.cw;
          pc.cw = 1.0 - pc.cy;
          pc.cy = pc.cx;
          pc.cx = 1.0 - tmp;
          break;
        default:
          break;
      }

      if(pc.angle != 0)
      {
        const float rangle = -pc.angle * (3.141592 / 180);
        float x, y;

        // do the rotation (rangle) using center of image (0.5, 0.5)

        x = pc.cx - 0.5;
        y = 0.5 - pc.cy;
        pc.cx = 0.5 + x * cos(rangle) - y * sin(rangle);
        pc.cy = 0.5 - (x * sin(rangle) + y * cos(rangle));

        x = pc.cw - 0.5;
        y = 0.5 - pc.ch;
        pc.cw = 0.5 + x * cos(rangle) - y * sin(rangle);
        pc.ch = 0.5 - (x * sin(rangle) + y * cos(rangle));
      }
    }
    else
    {
      pc.angle = 0;
      pc.cx = 0;
      pc.cy = 0;
      pc.cw = 1;
      pc.ch = 1;
    }

    fratio = (pc.cw - pc.cx) / (pc.ch - pc.cy);

    dt_add_hist(imgid, "clipping", (dt_iop_params_t *)&pc, sizeof(dt_iop_clipping_params_t), imported,
                sizeof(imported), LRDT_CLIPPING_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_flip)
  {
    pf.orientation = 0;

    if(dev->image_storage.orientation == 5)
      // portrait
      switch(orientation)
      {
        case 8:
          pf.orientation = 0;
          break;
        case 3:
          pf.orientation = 5;
          break;
        case 6:
          pf.orientation = 3;
          break;
        case 1:
          pf.orientation = 6;
          break;

        // with horizontal flip
        case 7:
          pf.orientation = 1;
          break;
        case 2:
          pf.orientation = 4;
          break;
        case 5:
          pf.orientation = 2;
          break;
        case 4:
          pf.orientation = 7;
          break;
      }

    else if(dev->image_storage.orientation == 6)
      // portrait
      switch(orientation)
      {
        case 8:
          pf.orientation = 3;
          break;
        case 3:
          pf.orientation = 6;
          break;
        case 6:
          pf.orientation = 0;
          break;
        case 1:
          pf.orientation = 5;
          break;

        // with horizontal flip
        case 7:
          pf.orientation = 2;
          break;
        case 2:
          pf.orientation = 7;
          break;
        case 5:
          pf.orientation = 1;
          break;
        case 4:
          pf.orientation = 4;
          break;
      }

    else
      // landscape
      switch(orientation)
      {
        case 8:
          pf.orientation = 5;
          break;
        case 3:
          pf.orientation = 3;
          break;
        case 6:
          pf.orientation = 6;
          break;
        case 1:
          pf.orientation = 0;
          break;

        // with horizontal flip
        case 7:
          pf.orientation = 7;
          break;
        case 2:
          pf.orientation = 1;
          break;
        case 5:
          pf.orientation = 4;
          break;
        case 4:
          pf.orientation = 2;
          break;
      }

    dt_add_hist(imgid, "flip", (dt_iop_params_t *)&pf, sizeof(dt_iop_flip_params_t), imported,
                sizeof(imported), LRDT_FLIP_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_exposure)
  {
    dt_add_hist(imgid, "exposure", (dt_iop_params_t *)&pe, sizeof(dt_iop_exposure_params_t), imported,
                sizeof(imported), LRDT_EXPOSURE_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_grain)
  {
    pg.channel = 0;

    dt_add_hist(imgid, "grain", (dt_iop_params_t *)&pg, sizeof(dt_iop_grain_params_t), imported,
                sizeof(imported), LRDT_GRAIN_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_vignette)
  {
    const float base_ratio = 1.325 / 1.5;

    pv.autoratio = FALSE;
    pv.dithering = DITHER_8BIT;
    pv.center.x = 0.0;
    pv.center.y = 0.0;
    pv.shape = 1.0;

    // defensive code, should not happen, but just in case future Lr version
    // has not ImageWidth/ImageLength XML tag.
    if(iwidth == 0 || iheight == 0)
      pv.whratio = base_ratio;
    else
      pv.whratio = base_ratio * ((float)iwidth / (float)iheight);

    if(has_crop) pv.whratio = pv.whratio * fratio;

    //  Adjust scale and ratio based on the roundness. On Lightroom changing
    //  the roundness change the width and the height of the vignette.

    if(crop_roundness > 0)
    {
      float newratio = pv.whratio - (pv.whratio - 1) * (crop_roundness / 100.0);
      float dscale = (1 - (newratio / pv.whratio)) / 2.0;

      pv.scale -= dscale * 100.0;
      pv.whratio = newratio;
    }

    dt_add_hist(imgid, "vignette", (dt_iop_params_t *)&pv, sizeof(dt_iop_vignette_params_t), imported,
                sizeof(imported), LRDT_VIGNETTE_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_spots)
  {
    // Check for orientation, rotate when in portrait mode
    if(orientation > 4)
      for(int k = 0; k < ps.num_spots; k++)
      {
        float tmp = ps.spot[k].y;
        ps.spot[k].y = 1.0 - ps.spot[k].x;
        ps.spot[k].x = tmp;
        tmp = ps.spot[k].yc;
        ps.spot[k].yc = 1.0 - ps.spot[k].xc;
        ps.spot[k].xc = tmp;
      }

    dt_add_hist(imgid, "spots", (dt_iop_params_t *)&ps, sizeof(dt_iop_spots_params_t), imported,
                sizeof(imported), LRDT_SPOTS_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(curve_kind != linear || ptc_value[0] != 0 || ptc_value[1] != 0 || ptc_value[2] != 0 || ptc_value[3] != 0)
  {
    ptc.tonecurve_nodes[ch_L] = 6;
    ptc.tonecurve_nodes[ch_a] = 7;
    ptc.tonecurve_nodes[ch_b] = 7;
    ptc.tonecurve_type[ch_L] = CUBIC_SPLINE;
    ptc.tonecurve_type[ch_a] = CUBIC_SPLINE;
    ptc.tonecurve_type[ch_b] = CUBIC_SPLINE;
    ptc.tonecurve_autoscale_ab = 1;
    ptc.tonecurve_preset = 0;

    float linear_ab[7] = { 0.0, 0.08, 0.3, 0.5, 0.7, 0.92, 1.0 };

    // linear a, b curves
    for(int k = 0; k < 7; k++) ptc.tonecurve[ch_a][k].x = linear_ab[k];
    for(int k = 0; k < 7; k++) ptc.tonecurve[ch_a][k].y = linear_ab[k];
    for(int k = 0; k < 7; k++) ptc.tonecurve[ch_b][k].x = linear_ab[k];
    for(int k = 0; k < 7; k++) ptc.tonecurve[ch_b][k].y = linear_ab[k];

    // Set the base tonecurve

    if(curve_kind == linear)
    {
      ptc.tonecurve[ch_L][0].x = 0.0;
      ptc.tonecurve[ch_L][0].y = 0.0;
      ptc.tonecurve[ch_L][1].x = ptc_split[0] / 2.0;
      ptc.tonecurve[ch_L][1].y = ptc_split[0] / 2.0;
      ptc.tonecurve[ch_L][2].x = ptc_split[1] - (ptc_split[1] - ptc_split[0]) / 2.0;
      ptc.tonecurve[ch_L][2].y = ptc_split[1] - (ptc_split[1] - ptc_split[0]) / 2.0;
      ptc.tonecurve[ch_L][3].x = ptc_split[1] + (ptc_split[2] - ptc_split[1]) / 2.0;
      ptc.tonecurve[ch_L][3].y = ptc_split[1] + (ptc_split[2] - ptc_split[1]) / 2.0;
      ptc.tonecurve[ch_L][4].x = ptc_split[2] + (1.0 - ptc_split[2]) / 2.0;
      ptc.tonecurve[ch_L][4].y = ptc_split[2] + (1.0 - ptc_split[2]) / 2.0;
      ptc.tonecurve[ch_L][5].x = 1.0;
      ptc.tonecurve[ch_L][5].y = 1.0;
    }
    else
    {
      for(int k = 0; k < 6; k++)
      {
        ptc.tonecurve[ch_L][k].x = curve_pts[k][0] / 255.0;
        ptc.tonecurve[ch_L][k].y = curve_pts[k][1] / 255.0;
      }
    }

    if(curve_kind != custom)
    {
      // set shadows/darks/lights/highlight adjustments

      ptc.tonecurve[ch_L][1].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[0] / 100.0);
      ptc.tonecurve[ch_L][2].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[1] / 100.0);
      ptc.tonecurve[ch_L][3].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[2] / 100.0);
      ptc.tonecurve[ch_L][4].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[3] / 100.0);

      if(ptc.tonecurve[ch_L][1].y > ptc.tonecurve[ch_L][2].y)
        ptc.tonecurve[ch_L][1].y = ptc.tonecurve[ch_L][2].y;
      if(ptc.tonecurve[ch_L][3].y > ptc.tonecurve[ch_L][4].y)
        ptc.tonecurve[ch_L][4].y = ptc.tonecurve[ch_L][3].y;
    }

    dt_add_hist(imgid, "tonecurve", (dt_iop_params_t *)&ptc, sizeof(dt_iop_tonecurve_params_t), imported,
                sizeof(imported), LRDT_TONECURVE_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_colorzones)
  {
    pcz.channel = DT_IOP_COLORZONES_h;

    for(int i = 0; i < 3; i++)
      for(int k = 0; k < 8; k++) pcz.equalizer_x[i][k] = k / (DT_IOP_COLORZONES_BANDS - 1.0);

    dt_add_hist(imgid, "colorzones", (dt_iop_params_t *)&pcz, sizeof(dt_iop_colorzones_params_t), imported,
                sizeof(imported), LRDT_COLORZONES_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_splittoning)
  {
    pst.compress = 50.0;

    dt_add_hist(imgid, "splittoning", (dt_iop_params_t *)&pst, sizeof(dt_iop_splittoning_params_t), imported,
                sizeof(imported), LRDT_SPLITTONING_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(dev != NULL && has_bilat)
  {
    pbl.sigma_r = 100.0;
    pbl.sigma_s = 100.0;

    dt_add_hist(imgid, "bilat", (dt_iop_params_t *)&pbl, sizeof(dt_iop_bilat_params_t), imported,
                sizeof(imported), LRDT_BILAT_VERSION, &n_import);
    refresh_needed = TRUE;
  }

  if(has_tags)
  {
    if(imported[0]) g_strlcat(imported, ", ", sizeof(imported));
    g_strlcat(imported, _("tags"), sizeof(imported));
    n_import++;
  }

  if(dev == NULL && has_rating)
  {
    dt_ratings_apply_to_image(imgid, rating);

    if(imported[0]) g_strlcat(imported, ", ", sizeof(imported));
    g_strlcat(imported, _("rating"), sizeof(imported));
    n_import++;
  }

  if(dev == NULL && has_gps)
  {
    dt_image_set_location(imgid, lon, lat);

    if(imported[0]) g_strlcat(imported, ", ", sizeof(imported));
    g_strlcat(imported, _("geotagging"), sizeof(imported));
    n_import++;
  }

  if(dev == NULL && has_colorlabel)
  {
    dt_colorlabels_set_label(imgid, color);

    if(imported[0]) g_strlcat(imported, ", ", sizeof(imported));
    g_strlcat(imported, _("color label"), sizeof(imported));
    n_import++;
  }

  if(dev != NULL && refresh_needed && dev->gui_attached)
  {
    dt_control_log(ngettext("%s has been imported", "%s have been imported", n_import), imported);

    if(!iauto)
    {
      /* signal history changed */
      dt_dev_reload_history_items(dev);
      dt_dev_modulegroups_set(darktable.develop, dt_dev_modulegroups_get(darktable.develop));
      /* update xmp file */
      dt_image_synch_xmp(imgid);
      dt_control_signal_raise(darktable.signals, DT_SIGNAL_DEVELOP_HISTORY_CHANGE);
    }
  }
}