Ejemplo n.º 1
0
static void _parse_paths(xmlDocPtr doc, xmlNodePtr node,
        ice_config_t *configuration)
{
    char *temp;
    aliases *alias, *current, *last;

    do {
        if (node == NULL) break;
        if (xmlIsBlankNode(node)) continue;

        if (strcmp(node->name, "basedir") == 0) {
            if (configuration->base_dir && configuration->base_dir != CONFIG_DEFAULT_BASE_DIR) xmlFree(configuration->base_dir);
            configuration->base_dir = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "logdir") == 0) {
            if (configuration->log_dir && configuration->log_dir != CONFIG_DEFAULT_LOG_DIR) xmlFree(configuration->log_dir);
            configuration->log_dir = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "pidfile") == 0) {
            if (configuration->pidfile) xmlFree(configuration->pidfile);
            configuration->pidfile = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "webroot") == 0) {
            if (configuration->webroot_dir && configuration->webroot_dir != CONFIG_DEFAULT_WEBROOT_DIR) xmlFree(configuration->webroot_dir);
            configuration->webroot_dir = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            if(configuration->webroot_dir[strlen(configuration->webroot_dir)-1] == '/')
                configuration->webroot_dir[strlen(configuration->webroot_dir)-1] = 0;
        } else if (strcmp(node->name, "adminroot") == 0) {
            if (configuration->adminroot_dir && configuration->adminroot_dir != CONFIG_DEFAULT_ADMINROOT_DIR) 
                xmlFree(configuration->adminroot_dir);
            configuration->adminroot_dir = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            if(configuration->adminroot_dir[strlen(configuration->adminroot_dir)-1] == '/')
                configuration->adminroot_dir[strlen(configuration->adminroot_dir)-1] = 0;
        } else if (strcmp(node->name, "alias") == 0) {
            alias = malloc(sizeof(aliases));
            alias->next = NULL;
            alias->source = xmlGetProp(node, "source");
            if(alias->source == NULL) {
                free(alias);
                continue;
            }
            alias->destination = xmlGetProp(node, "dest");
            if(alias->destination == NULL) {
                xmlFree(alias->source);
                free(alias);
                continue;
            }
            temp = NULL;
            temp = xmlGetProp(node, "port");
            if(temp != NULL) {
                alias->port = atoi(temp);
                xmlFree(temp);
            }
            else
                alias->port = -1;
            alias->bind_address = xmlGetProp(node, "bind-address");
            current = configuration->aliases;
            last = NULL;
            while(current) {
                last = current;
                current = current->next;
            }
            if(last)
                last->next = alias;
            else
                configuration->aliases = alias;
        }
    } while ((node = node->next));
}
Ejemplo n.º 2
0
const char *libxmlutil_attr_as_string(const xmlNode *node, const char *name)
{
  return (const char *)xmlGetProp((xmlNode *)node, (const xmlChar *)name);
}
Ejemplo n.º 3
0
static void
irc_network_manager_parse_irc_network (EmpathyIrcNetworkManager *self,
                                       xmlNodePtr node,
                                       gboolean user_defined)
{
  EmpathyIrcNetworkManagerPriv *priv = GET_PRIV (self);
  EmpathyIrcNetwork  *network;
  xmlNodePtr child;
  gchar *str;
  gchar *id, *name;

  id = xmlGetProp (node, "id");
  if (xmlHasProp (node, "dropped"))
    {
      if (!user_defined)
        {
          DEBUG ("the 'dropped' attribute shouldn't be used in the global file");
        }

      network = g_hash_table_lookup (priv->networks, id);
      if (network != NULL)
        {
          network->dropped = TRUE;
          network->user_defined = TRUE;
        }
       xmlFree (id);
      return;
    }

  if (!xmlHasProp (node, "name"))
    return;

  name = xmlGetProp (node, "name");
  network = empathy_irc_network_new (name);

  if (xmlHasProp (node, "network_charset"))
    {
      gchar *charset;
      charset = xmlGetProp (node, "network_charset");
      g_object_set (network, "charset", charset, NULL);
      xmlFree (charset);
    }

  add_network (self, network, id);
  DEBUG ("add network %s (id %s)", name, id);

  for (child = node->children; child; child = child->next)
    {
      gchar *tag;

      tag = (gchar *) child->name;
      str = (gchar *) xmlNodeGetContent (child);

      if (!str)
        continue;

      if (strcmp (tag, "servers") == 0)
        {
          irc_network_manager_parse_irc_server (network, child);
        }

      xmlFree (str);
    }

  network->user_defined = user_defined;
  g_object_unref (network);
  xmlFree (name);
  xmlFree (id);
}
Ejemplo n.º 4
0
static int
refresh_lists (void)
{
    int n;

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

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

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

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

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

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

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

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

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

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

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

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

            xpath_ctx = xmlXPathNewContext (xml_doc);

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

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

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

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

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

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

            xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;

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

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

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

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

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

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

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

        sfree (domids);
    }

    return 0;
}
Ejemplo n.º 5
0
static GPInstructLessonTestOrder *
parse_order_test (xmlNode *node)
{
	GPInstructLessonTestOrder *test = gpinstruct_lesson_test_order_new ();

	xmlNode *current_node;
	xmlChar *temp;

	temp = xmlGetProp (node, BAD_CAST "title");
	if (temp)
	{
		gpinstruct_lesson_element_set_title (GPINSTRUCT_LESSON_ELEMENT (test), (gchar*) temp);
		xmlFree (temp);
	}

	temp = xmlGetProp (node, BAD_CAST "id");
	if (temp)
	{
		gpinstruct_lesson_test_set_id (GPINSTRUCT_LESSON_TEST (test), (gchar*) temp);
		xmlFree (temp);
	}

	temp = xmlGetProp (node, BAD_CAST "explain");
	if (temp)
	{
		gpinstruct_lesson_test_set_explain (GPINSTRUCT_LESSON_TEST (test), GCHAR_TO_GBOOLEAN ((gchar*) temp));
		xmlFree (temp);
	}

	for (current_node = node->children;
	     current_node != NULL;
	     current_node = current_node->next)
	{
		if (current_node->type == XML_ELEMENT_NODE)
		{
			if (xmlStrEqual (current_node->name, BAD_CAST "directions"))
			{
				temp = xmlNodeGetContent (current_node);
				if (temp)
				{
					gpinstruct_lesson_test_set_directions (GPINSTRUCT_LESSON_TEST (test), (gchar*) temp);
					xmlFree (temp);
				}
			}
			else if (xmlStrEqual (current_node->name, BAD_CAST "item"))
			{
				GPInstructLessonTestOrderItem *item = gpinstruct_lesson_test_order_item_new ();
				gpinstruct_lesson_test_order_add_item (test, item);

				temp = xmlGetProp (current_node, BAD_CAST "answer");
				if (temp)
				{
					gpinstruct_lesson_test_order_item_set_answer (item, atoi ((gchar*) temp));
					xmlFree (temp);
				}

				temp = xmlNodeGetContent (current_node);
				if (temp)
				{
					gpinstruct_lesson_test_order_item_set_text (item, (gchar*) temp);
					xmlFree (temp);
				}
			}
			else if (xmlStrEqual (current_node->name, BAD_CAST "explanation"))
			{
				temp = xmlNodeGetContent (current_node);
				if (temp)
				{
					gpinstruct_lesson_test_order_set_explanation (test, (gchar*) temp);
					xmlFree (temp);
				}
			}
		}
	}

	return test;
}
Ejemplo n.º 6
0
static GPInstructLessonElementGroup *
parse_group (xmlNode *node)
{
	GPInstructLessonElementGroup *group = gpinstruct_lesson_element_group_new ();

	xmlNode *current_node;
	xmlChar *temp;

	temp = xmlGetProp (node, BAD_CAST "title");
	if (temp)
	{
		gpinstruct_lesson_element_set_title (GPINSTRUCT_LESSON_ELEMENT (group), (gchar*) temp);
		xmlFree (temp);
	}

	temp = xmlGetProp (node, BAD_CAST "single-score");
	if (temp)
	{
		gpinstruct_lesson_element_group_set_single_score (group, GCHAR_TO_GBOOLEAN ((gchar*) temp));
		xmlFree (temp);
	}

	temp = xmlGetProp (node, BAD_CAST "single-directions");
	if (temp)
	{
		gpinstruct_lesson_element_group_set_single_directions (group, GCHAR_TO_GBOOLEAN ((gchar*) temp));
		xmlFree (temp);
	}

	for (current_node = node->children;
	     current_node != NULL;
	     current_node = current_node->next)
	{
		if (current_node->type == XML_ELEMENT_NODE)
		{
			if (xmlStrEqual (current_node->name, BAD_CAST "directions"))
			{
				temp = xmlNodeGetContent (current_node);
				if (temp)
				{
					gpinstruct_lesson_element_group_set_directions (group, (gchar*) temp);
					xmlFree (temp);
				}
			}
			else if (xmlStrEqual (current_node->name, BAD_CAST "test-multi-choice"))
				gpinstruct_lesson_element_group_add_lesson_element (group,
				                                                    GPINSTRUCT_LESSON_ELEMENT (parse_multi_choice_test (current_node)));
			else if (xmlStrEqual (current_node->name, BAD_CAST "test-word-pool"))
				gpinstruct_lesson_element_group_add_lesson_element (group,
				                                                    GPINSTRUCT_LESSON_ELEMENT (parse_word_pool_test (current_node)));
			else if (xmlStrEqual (current_node->name, BAD_CAST "test-order"))
				gpinstruct_lesson_element_group_add_lesson_element (group,
				                                                    GPINSTRUCT_LESSON_ELEMENT (parse_order_test (current_node)));
			else if (xmlStrEqual (current_node->name, BAD_CAST "test-text"))
				gpinstruct_lesson_element_group_add_lesson_element (group,
				                                                    GPINSTRUCT_LESSON_ELEMENT (parse_text_test (current_node)));
			else if (xmlStrEqual (current_node->name, BAD_CAST "test-scrambled"))
				gpinstruct_lesson_element_group_add_lesson_element (group,
				                                                    GPINSTRUCT_LESSON_ELEMENT (parse_scrambled_test (current_node)));
			else if (xmlStrEqual (current_node->name, BAD_CAST "discussion"))
				gpinstruct_lesson_element_group_add_lesson_element (group,
				                                                    GPINSTRUCT_LESSON_ELEMENT (parse_discussion (current_node)));
			else if (xmlStrEqual (current_node->name, BAD_CAST "reading"))
				gpinstruct_lesson_element_group_add_lesson_element (group,
				                                                    GPINSTRUCT_LESSON_ELEMENT (parse_reading (current_node)));
		}
	}

	return group;
}
Ejemplo n.º 7
0
int cloudfs_connect()
{
  long response = -1;

  xmlNode *top_node = NULL, *service_node = NULL, *endpoint_node = NULL;
  xmlParserCtxtPtr xmlctx = NULL;

  char *postdata;
  if (reconnect_args.tenant[0])
  {
      int count = asprintf(&postdata,
         "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
         "<auth xmlns=\"http://docs.openstack.org/identity/api/v2.0\" tenantName=\"%s\">"
         "<passwordCredentials username=\"%s\" password=\"%s\"/>"
         "</auth>",
         reconnect_args.tenant, reconnect_args.username, reconnect_args.password);
      if (count < 0)
      {
        debugf("Unable to asprintf");
        abort();
      }
  }

  pthread_mutex_lock(&pool_mut);
  debugf("Authenticating...");
  storage_token[0] = storage_url[0] = '\0';

  CURL *curl = curl_easy_init();

  curl_slist *headers = NULL;
  if (reconnect_args.tenant[0])
  {
    add_header(&headers, "Content-Type", "application/xml");
    add_header(&headers, "Accept", "application/xml");

    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postdata));

    xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch);
  }
  else
  {
    add_header(&headers, "X-Auth-User", reconnect_args.username);
    add_header(&headers, "X-Auth-Key", reconnect_args.password);
  }

  curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
  curl_easy_setopt(curl, CURLOPT_URL, reconnect_args.authurl);
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_dispatch);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
  curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, verify_ssl);
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, verify_ssl);
  curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
  curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
  curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);

  curl_easy_perform(curl);
  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
  curl_slist_free_all(headers);
  curl_easy_cleanup(curl);

  if (reconnect_args.tenant[0])
  {
    free(postdata);
    xmlParseChunk(xmlctx, "", 0, 1);
    if (xmlctx->wellFormed && response >= 200 && response < 300)
    {
      xmlNode *root_element = xmlDocGetRootElement(xmlctx->myDoc);
      for (top_node = root_element->children; top_node; top_node = top_node->next)
      {
        if ((top_node->type == XML_ELEMENT_NODE) &&
           (!strcasecmp((const char *)top_node->name, "serviceCatalog")))
        {
          for (service_node = top_node->children; service_node; service_node = service_node->next)
            if ((service_node->type == XML_ELEMENT_NODE) &&
               (!strcasecmp((const char *)service_node->name, "service")))
            {
              xmlChar * serviceType = xmlGetProp(service_node, "type");
              int isObjectStore = serviceType && !strcasecmp(serviceType, "object-store");
              xmlFree(serviceType);

              if (!isObjectStore) continue;

              for (endpoint_node = service_node->children; endpoint_node; endpoint_node = endpoint_node->next)
                if ((endpoint_node->type == XML_ELEMENT_NODE) &&
                   (!strcasecmp((const char *)endpoint_node->name, "endpoint")))
                {
                  xmlChar * publicURL = xmlGetProp(endpoint_node, "publicURL");
                  xmlChar * region = xmlGetProp(endpoint_node, "region");
		  debugf("Found endpoint in region %s, URL is %s",region, publicURL);
                  if (publicURL)
                  {
                    
		    // fix, copy is now int, not char.
                    int copy = 1;
                    if (reconnect_args.region[0])
		    {
			debugf("Region option defined, looking for region %s", reconnect_args.region);
			if(!strcasecmp(reconnect_args.region, region))
			{
				debugf("Found region %s, using this URL %s", region, publicURL);

			}
			else
			{
				debugf("These are not the droids we are looking for... %s", region);
				copy=0;
			}

		    }
                    if (storage_url[0])
                    {
                      if (strstr(publicURL, "cdn"))
                      {
                        copy = 0;
                        debugf("Warning - found multiple object-store services; keeping %s, ignoring %s",
                                                     storage_url, publicURL);
                      }
                      else
		      {
			if(copy)
			{
                        debugf("Warning - found multiple object-store services; using %s instead of %s",
                                                     publicURL, storage_url);
			}
			else
			{
				debugf("Not copying, option override");
			}
		      }
                    }
                    if (copy)
                      strncpy(storage_url, publicURL, sizeof(storage_url));
                  }
		 
                  xmlFree(publicURL);
		  xmlFree(region);
                }
		debugf("Completed search for endpoint, result is %s", storage_url);
            }
        }

        if ((top_node->type == XML_ELEMENT_NODE) &&
            (!strcasecmp((const char *)top_node->name, "token")))
        {
          xmlChar * tokenId = xmlGetProp(top_node, "id");
          if (tokenId)
          {
            if (storage_token[0])
              debugf("Warning - found multiple authentication tokens.");
            strncpy(storage_token, tokenId, sizeof(storage_token));
          }
          xmlFree(tokenId);
        }
      }
    }
    xmlFreeParserCtxt(xmlctx);
  }
  if (reconnect_args.use_snet && storage_url[0])
    rewrite_url_snet(storage_url);
  pthread_mutex_unlock(&pool_mut);
  return (response >= 200 && response < 300 && storage_token[0] && storage_url[0]);
}
Ejemplo n.º 8
0
int ParseXML(xmlDocPtr xmlbuffer, GameInfo *game, ConfigSettings *cs) {
	xmlNode *root = NULL;
	xmlNode *node = NULL;
	xmlNode *child = NULL;
	int count;

	root = xmlDocGetRootElement(xmlbuffer);	
	if (root == NULL) {
		sr_fprintf(stderr, "Empty xml buffer\n");
		return -1;
	}

	for(node = root->children; node != NULL; node = node->next) {
		if (((node->type == XML_ELEMENT_NODE)  &&
		    ((xmlStrcmp(node->name, (const xmlChar *) "game") == 0) ||
		     (xmlStrcmp(node->name, (const xmlChar *) "machine") == 0))))
		{
			char *name = NULL;
			char *type = NULL;
			char *width = NULL;
			char *height = NULL;
			char *refresh = NULL;
			char *orientation = NULL;

			name = (char *)xmlGetProp(node, (const xmlChar *)"name");
			count++;
			for(child = node->children; child != NULL; child = child->next) {
				if ((node->type == XML_ELEMENT_NODE)  &&
				    (xmlStrcmp(child->name, (const xmlChar *) "display") == 0))
				{
					type = (char *)xmlGetProp(child, (const xmlChar *)"type");
					orientation = (char *)xmlGetProp(child, (const xmlChar *)"rotate");
					width = (char *)xmlGetProp(child, (const xmlChar *)"width");
					height = (char *)xmlGetProp(child, (const xmlChar *)"height");
					refresh = (char *)xmlGetProp(child, (const xmlChar *)"refresh");

					game->screens++;

					/* type */
					if (type != NULL && !strcmp(type, "vector"))
						game->vector = 1;
					else
						game->vector = 0;

					/* Width */
					if (width != NULL) {
						if (sscanf(width, "%d", &game->width) != 1)
							game->width = cs->vectorwidth;
					} else
						game->width = cs->vectorwidth;

					/* Height */
					if (height != NULL) {
						if (sscanf(height, "%d", &game->height) != 1)
							game->height = cs->vectorheight;
					} else
						game->height = cs->vectorheight;

					/* Refresh */
					if (refresh != NULL) {
						if (sscanf(refresh, "%lf", &game->refresh) != 1)
							game->refresh = 60.00;
					} else
						game->refresh = 60.00;

					if (cs->froggerfix) {
						if (game->width == 224 && game->height == 768)
							game->height = 256;
						else if (game->height == 224 && game->width == 768)
							game->width = 256;
					}

					game->o_width = game->width;
					game->o_height = game->height;
					game->o_refresh = game->refresh;
					game->o_aspect = (double)game->width / (double)game->height;

					/* Orientation */
					if (orientation != NULL && !game->vector) {
       						if ((strcmp(orientation, "90") == 0) ||
               						(strcmp(orientation, "270") == 0))
       						{       // orientation = vertical
       							int w = game->width;
       							int h = game->height;
							game->orientation = 1;
							if (cs->morientation == 0) {
								game->width = h;
								game->height = w;
							}
       						} else { // horizontal
							game->orientation = 0;
							if (cs->morientation == 1) {
       								int w = game->width;
       								int h = game->height;
								game->width = h;
								game->height = w;
							}
						}
						if ((game->orientation && !cs->morientation) || (!game->orientation &&  (cs->morientation == 1))) {
							double num, den;
							sscanf(cs->aspect, "%lf:%lf", &den, &num);

							game->width = Normalize((double)game->width * (4.0/3.0) / (num/den), 8);
						}
					} else {
						game->orientation = 0;
					}

					game->aspect = (double)game->width / (double)game->height;

					/* Dual screen games */
					if (game->screens > 1) {
						game->height *= 2;
						game->width = game->aspect * (double)game->height;
					}

					game->width = Normalize(game->width, 8);
					game->height = Normalize(game->height, 8);
				}
			}
		}
	
	}
	return 0;
}
Ejemplo n.º 9
0
/** Creates and fills in a gd_fs_entry_t from an <entry>...</entry> in xml.
 *
 *  @xml  the xml containing the entry
 *  @node the node representing this <entry>...</entry> block
 *
 *  @returns pointer to gd_fs_entry_t with fields filled in as needed
 */
struct gd_fs_entry_t* gd_fs_entry_from_xml(xmlDocPtr xml, xmlNodePtr node)
{
    struct gd_fs_entry_t* entry;
    unsigned long inode = 0;

    entry = (struct gd_fs_entry_t*) malloc(sizeof(struct gd_fs_entry_t));
    if(entry == NULL) {} // TODO: ERROR
    memset(entry, 0, sizeof(struct gd_fs_entry_t));

    size_t length;
    xmlNodePtr c1, c2;
    xmlChar *value = NULL;

    inode = get_free_inode();
    for(c1 = node->children; c1 != NULL; c1 = c1->next)
    {

        char const *name = c1->name;

        switch(*name)
        {
        case 'a': // 'author'
            for(c2 = c1->children; c2 != NULL; c2 = c2->next)
            {
                name = c2->name;
                value = xmlNodeListGetString(xml, c2->children, 1);
                switch(*name)
                {
                case 'n':
                    str_init_create(&entry->author, value, 0);
                    break;
                case 'e':
                    str_init_create(&entry->author_email, value, 0);
                    break;
                default:
                    break;
                }
                xmlFree(value);
            }
            break;
        case 'c':
            if(strcmp(name, "content") == 0)
            {
                value = xmlGetProp(c1, "src");
                str_init_create(&entry->src, value, 0);
                xmlFree(value);
            }
            // file's type
            else if (strcmp(name, "category") == 0)
            {
                value = xmlGetProp(c1, "label");
                if (strcmp(value, "folder")==0)
                {
                    inodetable[inode].inode->mode = S_IFDIR | 0700;
                    entry->mode = S_IFDIR | 0700;
                    entry->shared = 0;
                }
                else if (strcmp(value, "shared")==0)
                {
                    inodetable[inode].inode->mode = S_IFREG | 0600;
                    entry->mode = S_IFREG | 0600;
                    entry->shared = 1;
                }
                else
                {
                    inodetable[inode].inode->mode = S_IFREG | 0600;
                    entry->mode = S_IFREG | 0600;
                    entry->shared = 0;
                }
            }
            break;
        case 'f':
            if(strcmp(name, "feedlink") == 0)
            {
                value = xmlGetProp(c1, "rel");
                if(strcmp(value, "http://schemas.google.com/acl/2007#accessControlList") == 0)
                {
                    // Link for r/w access to ACLS for this entry
                    // Do we care?
                    // Can we expose this?
                }
                else if(strcmp(value, "http://schemas.google.com/docs/2007/revisions") == 0)
                {
                    // Link for r/w access to revisions
                    // It would be cool if we can expose these somehow
                }
            }
            break;
        case 'l':
            if(strcmp(name, "lastModifiedBy") == 0)
            {
                for(c2 = c1->children; c2 != NULL; c2 = c2->next)
                {
                    name = c2->name;
                    value = xmlNodeListGetString(xml, c2->children, 1);
                    switch(*name)
                    {
                    case 'n':
                        str_init_create(&entry->lastModifiedBy, value, 0);
                        break;
                    case 'e':
                        str_init_create(&entry->lastModifiedBy_email, value, 0);
                        break;
                    default:
                        break;
                    }
                    xmlFree(value);
                }
            }
            else if(strcmp(name, "link") == 0)
            {
                value = xmlGetProp(c1, "rel");
                if(strcmp(value, "http://schemas.google.com/docs/2007#parent") == 0)
                {
                    xmlChar *value;
                    value = xmlGetProp(c1, "title");
                    str_init_create(&entry->parent, value, 0);
                    xmlFree(value);
                    value = xmlGetProp(c1, "href");
                    str_init_create(&entry->parent_href, value, 0);
                    xmlFree(value);
                    // This entry is inside one (or more?) collections
                    // These entries are the folders for this entry
                }
                else if(strcmp(value, "alternate") == 0)
                {
                    // Link you can open this document in a web browser with
                    // Do we care?
                }
                else if(strcmp(value, "self") == 0)
                {
                    // Link to XML feed for just this entry
                    // Might be useful for checking for updates instead of changesets
                    xmlChar *href = xmlGetProp(c1, "href");
                    str_init_create(&entry->feed, href, 0);
                    xmlFree(href);
                }
                else if(strcmp(value, "edit") == 0)
                {
                    // For writes?
                }
                /*
                else if(strcmp(value, "edit-media") == 0)
                {
                	// deprecated, use 'resumeable-edit-media'
                }
                */
                else if(strcmp(value, "http://schemas.google.com/g/2005#resumable-edit-media") == 0)
                {
                    // For resumeable writes?
                    // This may be the one we *really* want to use, rather than 'edit'
                }
                else if(strcmp(value, "http://schemas.google.com/docs/2007/thumbnail") == 0)
                {
                    // Might be a useful way to expose this for GUI file managers?
                }
                xmlFree(value);
            }
            break;
        case 'm':
            if(strcmp(name, "md5Checksum") == 0)
            {
                value = xmlNodeListGetString(xml, c1->children, 1);
                entry->md5set = 1;
                str_init_create(&entry->md5, value, 0);
                xmlFree(value);
            }
            break;
        case 't': // 'title'
            if(strcmp(name, "title") == 0)
            {
                value = xmlNodeListGetString(xml, c1->children, 1);
                str_init_create(&entry->filename, value, 0);
                entry->filename.str = filenameencode(value, &entry->filename.len);
                entry->filename.reserved = entry->filename.len;
                xmlFree(value);
            }
            break;
        case 's':
            if(strcmp(name, "size") == 0)
            {
                value = xmlNodeListGetString(xml, c1->children, 1);
                length = xmlStrlen(value);
                // TODO: errors?
                entry->size = strtol((char*)value, NULL, 10);
                xmlFree(value);
            }
            break;
        default:
            break;
        }
    }
    entry->inode = inode;
    inodetable[inode].num = inode;
    inodetable[inode].inode->node = entry;
    return entry;
}
Ejemplo n.º 10
0
int Page::LoadXmlPageFile()
{
  xmlNodePtr cur;
  xmlChar * value;
  wxFileName fullpath(file.GetFullPath());
  if(file.IsRelative()) {
	  fullpath.PrependDir(ws::curproj->GetProjPath());
  }
  doc = xmlParseFile((const char*)fullpath.GetFullPath().mb_str());
  if(doc == NULL)
    {
      std::cout << "Error parsing file " << (const char *)fullpath.GetFullPath().mb_str() << std::endl;
      return 0;
    }
  cur = xmlDocGetRootElement(doc);
  if(xmlStrcmp(cur->name, (const xmlChar *)"page") != 0)
    {
      xmlFreeDoc(doc);
      return 0;
    }
  cur = cur->children;
  while(cur != NULL)
    {
      if(!xmlStrcmp(cur->name, (const xmlChar *)"name"))
        {
          value = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
          wxString temp((const char*)value, wxConvUTF8);
          SetName(temp);
          std::cout << "Added name ..." << std::endl;
          xmlFree(value);
        }
      else if(!xmlStrcmp(cur->name, (const xmlChar *)"description"))
        {
          value = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
          wxString temp((const char*)value, wxConvUTF8);
          SetDescription(temp);
          std::cout << "Added description ..." << std::endl;
          xmlFree(value);
        }
      else if(!xmlStrcmp(cur->name, (const xmlChar *)"template"))
        {
          xmlChar *prop;
          if ((prop = xmlGetProp(cur, (const xmlChar*)"uri")) != NULL)
            {
              //do something
            }
          else
            {
              std::cout << "Couldn\'t find template" << std::endl;
            }
        }
      else if(!xmlStrcmp(cur->name, (const xmlChar *)"layout"))
        {
          xmlChar *prop;
          if ((prop = xmlGetProp(cur, (const xmlChar*)"uri")) != NULL)
            {
              //do something
            }
          else
            {
              std::cout << "Couldn\'t find layout" << std::endl;
            }
        }
      else if(!xmlStrcmp(cur->name,(const xmlChar *)"blocks"))
        {
          std::cout << "Processing blocks ..." << std::endl;
          ProcessBlocks(doc, cur);
        }
      cur = cur->next;
    }
  return 1;
};
Ejemplo n.º 11
0
/*
 * Get metric from the xml buffer, value set in pmdef
 */
static int get_mdef(metric_disk *mdisk, private_metric *pmdef)
{
   xmlXPathContextPtr ctxt = NULL;
   xmlXPathObjectPtr obj;
   xmlNodePtr node;
   char *str;
   char *xpath;
   int ret = 0;

   ctxt = xmlXPathNewContext(mdisk->doc);
   if (!ctxt) {
      return -1;
   }

   /* Get the matching metric node type */
   asprintf(&xpath, "//metrics/metric[name='%s'][@context='%s']", pmdef->name, pmdef->context);
   obj = xmlXPathEval(BAD_CAST xpath, ctxt);
   free(xpath);
   if ((obj == NULL) || (obj->type != XPATH_NODESET)) {
      libmsg("%s(): No metrics found that matches %s in context:%s or malformed definition\n",
              __func__, pmdef->name, pmdef->context);
      ret = -1;
      goto out;
   }
   if (xmlXPathNodeSetGetLength(obj->nodesetval) != 1) {
      libmsg("%s(): No metrics found that matches %s in context:%s or malformed definition\n",
              __func__, pmdef->name, pmdef->context);
      ret = -1;
      goto out;
   }
   node = obj->nodesetval->nodeTab[0];
   if ((str = (char *)xmlGetProp(node, BAD_CAST "type")) == NULL) {
      libmsg("%s(): Metric type not specified\n", __func__);
      ret = -1;
      goto out;
   }
   metric_type_from_str((char *)str, &(pmdef->type));
   free(str);
   xmlXPathFreeObject(obj);

   /* Get the matching metric node value */
   asprintf(&xpath, "//metrics/metric[name='%s'][@context='%s']/value/text()", pmdef->name, pmdef->context);
   obj = xmlXPathEval( BAD_CAST xpath, ctxt);  /* worked but no nodes */
   free(xpath);
   if ((obj == NULL) || (obj->type != XPATH_NODESET)) {
      libmsg("%s(): No metrics value found!\n", __func__);
      ret = -1;
      goto out;
   }

   /* Get the nodes value content */
   node = obj->nodesetval->nodeTab[0];
   str = (char *)xmlNodeListGetString(mdisk->doc, node, 1);
   pmdef->value = strdup(str);
   free(str);

out:
   if (obj)
      xmlXPathFreeObject(obj);
   if (ctxt)
      xmlXPathFreeContext(ctxt);
   return ret;
}
Ejemplo n.º 12
0
cheat_manager_t *cheat_manager_new(const char *path)
{
   xmlParserCtxtPtr ctx;
   xmlNodePtr head, cur;
   xmlDocPtr doc;
   cheat_manager_t *handle;

   LIBXML_TEST_VERSION;

   pretro_cheat_reset();

   ctx = NULL;
   doc = NULL;
   handle = (cheat_manager_t*)calloc(1, sizeof(struct cheat_manager));
   if (!handle)
      return NULL;

   head = NULL;
   cur = NULL;

   handle->buf_size = 1;
   handle->cheats = (struct cheat*)calloc(handle->buf_size, sizeof(struct cheat));
   if (!handle->cheats)
   {
      handle->buf_size = 0;
      goto error;
   }

   ctx = xmlNewParserCtxt();
   if (!ctx)
      goto error;

   doc = xmlCtxtReadFile(ctx, path, NULL, 0);
   if (!doc)
   {
      RARCH_ERR("Failed to parse XML file: %s\n", path);
      goto error;
   }

#ifdef HAVE_LIBXML2
   if (ctx->valid == 0)
   {
      RARCH_ERR("Cannot validate XML file: %s\n", path);
      goto error;
   }
#endif

   head = xmlDocGetRootElement(doc);
   for (cur = head; cur; cur = cur->next)
   {
      if (cur->type == XML_ELEMENT_NODE && strcmp((const char*)cur->name, "database") == 0)
         break;
   }

   if (!cur)
      goto error;

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

      if (strcmp((const char*)cur->name, "cartridge") == 0)
      {
         xmlChar *sha256 = xmlGetProp(cur, (const xmlChar*)"sha256");
         if (!sha256)
            continue;

         if (*g_extern.sha256 && strcmp((const char*)sha256, g_extern.sha256) == 0)
         {
            xmlFree(sha256);
            break;
         }

         xmlFree(sha256);
      }
   }

   if (!cur)
      goto error;

   if (!xml_grab_cheats(handle, cur->children))
   {
      RARCH_ERR("Failed to grab cheats. This should not happen.\n");
      goto error;
   }

   if (handle->size == 0)
   {
      RARCH_ERR("Did not find any cheats in XML file: %s\n", path);
      goto error;
   }

   cheat_manager_load_config(handle, g_settings.cheat_settings_path, g_extern.sha256);

   xmlFreeDoc(doc);
   xmlFreeParserCtxt(ctx);
   return handle;

error:
   cheat_manager_free(handle);
   if (doc)
      xmlFreeDoc(doc);
   if (ctx)
      xmlFreeParserCtxt(ctx);
   return NULL;
}
Ejemplo n.º 13
0
int ltFunListInit(char *funconffile){
    
  xmlDocPtr doc;
    xmlNodePtr  node;
    xmlNodePtr  childnode;
  xmlNodePtr  tempRootNode;
    char *nodeMaxTime;
    char *nodeName;
    char *nodeDesc;
    char *nodeUrl;
    char *nodeType;
    char *nodeActive;
    char *nodeRightCheck;
    uint32 lFunCode;
    unsigned int i;
    unsigned int j;
    funList tmpFunList;

    
    for(i=0;i<NAS_MAX_FUNNUM;i++){
            _ltfunList[i].lFunCode=0;
            _ltfunList[i].funFlag=0;
            sprintf(_ltfunList[i].strFunName,"%s","");
            sprintf(_ltfunList[i].strFunUrl,"%s","");
            _ltfunList[i].maxruntime=NAS_DEFAULT_FUNTIME;
            _ltfunList[i].op=NULL;
    }
    
            _ltfunList[0].lFunCode=ltMd5Code("ltsSysCheck",strlen("ltsSysCheck"),"LT");;
            _ltfunList[0].funFlag=0;
            sprintf(_ltfunList[0].strFunName,"%s","ltsSysCheck");
            sprintf(_ltfunList[0].strFunUrl,"%s","");
            _ltfunList[0].maxruntime=60;
            _ltfunList[0].op=ltsSysCheck;
            

            
            
            
    doc=xmlParseFile(funconffile); 
    if(doc==NULL){
        return -1;
    }
    i=1;
    tempRootNode=xmlDocGetRootElement(doc);
    for(node = tempRootNode->children; node != NULL; node = node->next) {
      if(node->name!=NULL){
        /*begin core fun*/
            if(!case_diffs(node->name,"corefun")){
                for(childnode=node->children;childnode!=NULL;childnode=childnode->next){
                    nodeType=childnode->name;
                    nodeName=xmlGetProp(childnode,"name");
                    nodeMaxTime=xmlGetProp(childnode,"maxtime");
                    nodeDesc=xmlGetProp(childnode,"desc");
                    nodeUrl=xmlGetProp(childnode,"url");
                    nodeActive=xmlGetProp(childnode,"activeflag");
                    nodeRightCheck=xmlGetProp(childnode,"rightflag");
                    if(nodeType!=NULL && nodeName!=NULL && nodeMaxTime!=NULL && nodeDesc!=NULL && nodeUrl!=NULL && nodeActive!=NULL && nodeRightCheck!=NULL ){
                            for(j=0;j<NAS_MAX_COREFUNNUM;j++){
                                if(strcmp(_ltcorefunList[j].strFunName,nodeName)==0){
                                      lFunCode=ltMd5Code(nodeName,strlen(nodeName),"LT");
                                        _ltfunList[i].lFunCode=lFunCode;
                                        _ltfunList[i].funFlag=0;
                                        snprintf(_ltfunList[i].strFunName,63,"%s",nodeName);
                                        sprintf(_ltfunList[i].strFunUrl,"%s","");
                                        _ltfunList[i].maxruntime=atol(nodeMaxTime);
                                        _ltfunList[i].rightflag=atol(nodeRightCheck);
                                        _ltfunList[i].activeflag=atol(nodeActive);
                                        _ltfunList[i].op=_ltcorefunList[j].op;
                                        i++;
                                        break;
                            	}
                            }	
                    }
                }
            }
            /*end core fun*/
            /*begin sofun*/
            if(!case_diffs(node->name,"sofun")){
                for(childnode=node->children;childnode!=NULL;childnode=childnode->next){
                    nodeType=childnode->name;
                    nodeName=xmlGetProp(childnode,"name");
                    nodeMaxTime=xmlGetProp(childnode,"maxtime");
                    nodeDesc=xmlGetProp(childnode,"desc");
                    nodeUrl=xmlGetProp(childnode,"url");
                    nodeActive=xmlGetProp(childnode,"activeflag");
                    nodeRightCheck=xmlGetProp(childnode,"rightflag");
                    if(nodeType!=NULL && nodeName!=NULL && nodeMaxTime!=NULL && nodeDesc!=NULL && nodeUrl!=NULL && nodeActive!=NULL && nodeRightCheck!=NULL ){
                                      lFunCode=ltMd5Code(nodeName,strlen(nodeName),"LT");
                                        _ltfunList[i].lFunCode=lFunCode;
                                        _ltfunList[i].funFlag=1;
                                        snprintf(_ltfunList[i].strFunName,63,"%s",nodeName);
                                        snprintf(_ltfunList[i].strFunUrl,127,"%s",nodeUrl);
                                        _ltfunList[i].maxruntime=atol(nodeMaxTime);
                                        _ltfunList[i].rightflag=atol(nodeRightCheck);
                                        _ltfunList[i].activeflag=atol(nodeActive);
                                        _ltfunList[i].op=NULL;
                                        i++;
                    }
                }
            }
            /*end sofun*/
            /*begin appfun*/
            if(!case_diffs(node->name,"appfun")){
                for(childnode=node->children;childnode!=NULL;childnode=childnode->next){
                    nodeType=childnode->name;
                    nodeName=xmlGetProp(childnode,"name");
                    nodeMaxTime=xmlGetProp(childnode,"maxtime");
                    nodeDesc=xmlGetProp(childnode,"desc");
                    nodeUrl=xmlGetProp(childnode,"url");
                    nodeActive=xmlGetProp(childnode,"activeflag");
                    nodeRightCheck=xmlGetProp(childnode,"rightflag");
                    if(nodeType!=NULL && nodeName!=NULL && nodeMaxTime!=NULL && nodeDesc!=NULL && nodeUrl!=NULL && nodeActive!=NULL && nodeRightCheck!=NULL ){
                                      lFunCode=ltMd5Code(nodeName,strlen(nodeName),"LT");
                                        _ltfunList[i].lFunCode=lFunCode;
                                        _ltfunList[i].funFlag=3;
                                        snprintf(_ltfunList[i].strFunName,63,"%s",nodeName);
                                        snprintf(_ltfunList[i].strFunUrl,127,"%s",nodeUrl);
                                        _ltfunList[i].maxruntime=atol(nodeMaxTime);
                                        _ltfunList[i].rightflag=atol(nodeRightCheck);
                                        _ltfunList[i].activeflag=atol(nodeActive);
                                        _ltfunList[i].op=NULL;
                                        i++;
                    }
                }
            }
            /*end appfun*/
        }               
  }
  
  _ltPubInfo->maxfuntonnum=i;
  /*排序 按照lFunCode升序排列*/
  

  //模块注册
    ltSetFunListN("msasTestApp3",msasTestApp3);
    ltSetFunListN("msasTestApp4",msasTestApp4);
    ltSetFunListN("msasReportList",msasReportList);
  	ltSetFunListN("msasreportproc1",msasreportproc1);
  	ltSetFunListN("msasreportproc2",msasreportproc2);
  	ltSetFunListN("msasreportproc3",msasreportproc3);
  	ltSetFunListN("msasreportproc4",msasreportproc4);
  	ltSetFunListN("msasreportproc5",msasreportproc5);
  	ltSetFunListN("nasCvtLongTime",nasCvtLongTime);
  	ltSetFunListN("nasCvtStime",nasCvtStime);
  i=_ltPubInfo->maxfuntonnum;
  //printf("iiiiii:%d\n",i);
  //qsort(_ltfunList,i,sizeof(funList),nasSortFunList);
  
    xmlFreeDoc(doc);
    
    
    for(i=0;i<_ltPubInfo->maxfuntonnum-1;i++){
        for(j=_ltPubInfo->maxfuntonnum-1;j>i;j--){
            if( _ltfunList[j].lFunCode< _ltfunList[j-1].lFunCode){
                memcpy(&tmpFunList,&_ltfunList[j],sizeof(funList));
                memcpy(&_ltfunList[j],&_ltfunList[j-1],sizeof(funList));
                memcpy(&_ltfunList[j-1],&tmpFunList,sizeof(funList));
            }
        }
    }

    
//  for(i=0;i<_ltPubInfo->maxfuntonnum;i++){
//      printf("%d lFunCode==%u %s\n",i,_ltfunList[i].lFunCode, _ltfunList[i].strFunName);
//  }
    
    
    
    return 0;   
}
Ejemplo n.º 14
0
bool Items::loadXMLInfos(std::string file)
{
	char *tmp;
	xmlDocPtr doc;
	doc = xmlParseFile(file.c_str());

	if (!doc)
		return false;

	xmlNodePtr root, itemNode;
	root = xmlDocGetRootElement(doc);

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

	itemNode = root->children;

	while (itemNode)
	{
		std::string elem = (char*)itemNode->name;
		if (elem == "item" && (tmp = (char*)xmlGetProp(itemNode, (xmlChar*)"id")))
		{
			int id = atoi(tmp);
			xmlFreeOTSERV(tmp);
			ItemMap::iterator it = items.find(id);

			if ((it != items.end()) && (it->second != NULL))
			{
				ItemType *itemtype = it->second;

#ifdef YUR_ITEM_EXT
				tmp = (char*)xmlGetProp(itemNode, (xmlChar*)"questbox");
				if (tmp)
				{
					itemtype->pickupable = false;
					itemtype->moveable = false;
					xmlFreeOTSERV(tmp);
				}
#endif //YUR_ITEM_EXT

#ifdef TLM_HOUSE_SYSTEM
				tmp = (char*)xmlGetProp(itemNode, (xmlChar*)"door");
				if (tmp)
				{
					itemtype->isDoor = atoi(tmp)!=0;
					xmlFreeOTSERV(tmp);
				}
#endif //TLM_HOUSE_SYSTEM

#ifdef YUR_RINGS_AMULETS
				tmp = (char*)xmlGetProp(itemNode, (xmlChar*)"charges");
				if (tmp)
				{
					itemtype->newCharges = atoi(tmp);
					xmlFreeOTSERV(tmp);
				}

				tmp = (char*)xmlGetProp(itemNode, (xmlChar*)"time");
				if (tmp)
				{
					itemtype->newTime = atoi(tmp);
					xmlFreeOTSERV(tmp);
				}
#endif //YUR_RINGS_AMULETS
			}
			else
				std::cout << "invalid item " << id << std::endl;
		}
		itemNode = itemNode->next;
	}

	xmlFreeDoc(doc);
	return true;
}
Ejemplo n.º 15
0
static int
xmlSecEncCtxEncDataNodeRead(xmlSecEncCtxPtr encCtx, xmlNodePtr node) {
    xmlNodePtr cur;
    int ret;

    xmlSecAssert2(encCtx != NULL, -1);
    xmlSecAssert2((encCtx->operation == xmlSecTransformOperationEncrypt) || (encCtx->operation == xmlSecTransformOperationDecrypt), -1);
    xmlSecAssert2(node != NULL, -1);

    switch(encCtx->mode) {
        case xmlEncCtxModeEncryptedData:
            if(!xmlSecCheckNodeName(node, xmlSecNodeEncryptedData, xmlSecEncNs)) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            xmlSecErrorsSafeString(xmlSecNodeGetName(node)),
                            XMLSEC_ERRORS_R_INVALID_NODE,
                            "expected=%s",
                            xmlSecErrorsSafeString(xmlSecNodeEncryptedData));
                return(-1);
            }
            break;
        case xmlEncCtxModeEncryptedKey:
            if(!xmlSecCheckNodeName(node, xmlSecNodeEncryptedKey, xmlSecEncNs)) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            xmlSecErrorsSafeString(xmlSecNodeGetName(node)),
                            XMLSEC_ERRORS_R_INVALID_NODE,
                            "expected=%s",
                            xmlSecErrorsSafeString(xmlSecNodeEncryptedKey));
                return(-1);
            }
            break;
    }

    /* first read node data */
    xmlSecAssert2(encCtx->id == NULL, -1);
    xmlSecAssert2(encCtx->type == NULL, -1);
    xmlSecAssert2(encCtx->mimeType == NULL, -1);
    xmlSecAssert2(encCtx->encoding == NULL, -1);
    xmlSecAssert2(encCtx->recipient == NULL, -1);
    xmlSecAssert2(encCtx->carriedKeyName == NULL, -1);

    encCtx->id = xmlGetProp(node, xmlSecAttrId);
    encCtx->type = xmlGetProp(node, xmlSecAttrType);
    encCtx->mimeType = xmlGetProp(node, xmlSecAttrMimeType);
    encCtx->encoding = xmlGetProp(node, xmlSecAttrEncoding);
    if(encCtx->mode == xmlEncCtxModeEncryptedKey) {
        encCtx->recipient = xmlGetProp(node, xmlSecAttrRecipient);
        /* todo: check recipient? */
    }
    cur = xmlSecGetNextElementNode(node->children);

    /* first node is optional EncryptionMethod, we'll read it later */
    xmlSecAssert2(encCtx->encMethodNode == NULL, -1);
    if((cur != NULL) && (xmlSecCheckNodeName(cur, xmlSecNodeEncryptionMethod, xmlSecEncNs))) {
        encCtx->encMethodNode = cur;
        cur = xmlSecGetNextElementNode(cur->next);
    }

    /* next node is optional KeyInfo, we'll process it later */
    xmlSecAssert2(encCtx->keyInfoNode == NULL, -1);
    if((cur != NULL) && (xmlSecCheckNodeName(cur, xmlSecNodeKeyInfo, xmlSecDSigNs))) {
        encCtx->keyInfoNode = cur;
        cur = xmlSecGetNextElementNode(cur->next);
    }

    /* next is required CipherData node */
    if((cur == NULL) || (!xmlSecCheckNodeName(cur, xmlSecNodeCipherData, xmlSecEncNs))) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    xmlSecErrorsSafeString(xmlSecNodeGetName(cur)),
                    XMLSEC_ERRORS_R_INVALID_NODE,
                    "node=%s",
                    xmlSecErrorsSafeString(xmlSecNodeCipherData));
        return(-1);
    }

    ret = xmlSecEncCtxCipherDataNodeRead(encCtx, cur);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecEncCtxCipherDataNodeRead",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }
    cur = xmlSecGetNextElementNode(cur->next);

    /* next is optional EncryptionProperties node (we simply ignore it) */
    if((cur != NULL) && (xmlSecCheckNodeName(cur, xmlSecNodeEncryptionProperties, xmlSecEncNs))) {
        cur = xmlSecGetNextElementNode(cur->next);
    }

    /* there are more possible nodes for the <EncryptedKey> node */
    if(encCtx->mode == xmlEncCtxModeEncryptedKey) {
        /* next is optional ReferenceList node (we simply ignore it) */
        if((cur != NULL) && (xmlSecCheckNodeName(cur, xmlSecNodeReferenceList, xmlSecEncNs))) {
            cur = xmlSecGetNextElementNode(cur->next);
        }

        /* next is optional CarriedKeyName node (we simply ignore it) */
        if((cur != NULL) && (xmlSecCheckNodeName(cur, xmlSecNodeCarriedKeyName, xmlSecEncNs))) {
            encCtx->carriedKeyName = xmlNodeGetContent(cur);
            if(encCtx->carriedKeyName == NULL) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            xmlSecErrorsSafeString(xmlSecNodeGetName(cur)),
                            XMLSEC_ERRORS_R_INVALID_NODE_CONTENT,
                            "node=%s",
                            xmlSecErrorsSafeString(xmlSecNodeCipherData));
                return(-1);
            }
            /* TODO: decode the name? */
            cur = xmlSecGetNextElementNode(cur->next);
        }
    }

    /* if there is something left than it's an error */
    if(cur != NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    xmlSecErrorsSafeString(xmlSecNodeGetName(cur)),
                    XMLSEC_ERRORS_R_UNEXPECTED_NODE,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    /* now read the encryption method node */
    xmlSecAssert2(encCtx->encMethod == NULL, -1);
    if(encCtx->encMethodNode != NULL) {
        encCtx->encMethod = xmlSecTransformCtxNodeRead(&(encCtx->transformCtx), encCtx->encMethodNode,
                                                xmlSecTransformUsageEncryptionMethod);
        if(encCtx->encMethod == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecTransformCtxNodeRead",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "node=%s",
                        xmlSecErrorsSafeString(xmlSecNodeGetName(encCtx->encMethodNode)));
            return(-1);
        }
    } else if(encCtx->defEncMethodId != xmlSecTransformIdUnknown) {
        encCtx->encMethod = xmlSecTransformCtxCreateAndAppend(&(encCtx->transformCtx),
                                                              encCtx->defEncMethodId);
        if(encCtx->encMethod == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecTransformCtxAppend",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
    } else {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    NULL,
                    XMLSEC_ERRORS_R_INVALID_DATA,
                    "encryption method not specified");
        return(-1);
    }
    encCtx->encMethod->operation = encCtx->operation;

    /* we have encryption method, find key */
    ret = xmlSecTransformSetKeyReq(encCtx->encMethod, &(encCtx->keyInfoReadCtx.keyReq));
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecTransformSetKeyReq",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    "transform=%s",
                    xmlSecErrorsSafeString(xmlSecTransformGetName(encCtx->encMethod)));
        return(-1);
    }

    /* TODO: KeyInfo node != NULL and encKey != NULL */
    if((encCtx->encKey == NULL) && (encCtx->keyInfoReadCtx.keysMngr != NULL)
                        && (encCtx->keyInfoReadCtx.keysMngr->getKey != NULL)) {
        encCtx->encKey = (encCtx->keyInfoReadCtx.keysMngr->getKey)(encCtx->keyInfoNode,
                                                             &(encCtx->keyInfoReadCtx));
    }

    /* check that we have exactly what we want */
    if((encCtx->encKey == NULL) ||
       (!xmlSecKeyMatch(encCtx->encKey, NULL, &(encCtx->keyInfoReadCtx.keyReq)))) {

        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    NULL,
                    XMLSEC_ERRORS_R_KEY_NOT_FOUND,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    /* set the key to the transform */
    ret = xmlSecTransformSetKey(encCtx->encMethod, encCtx->encKey);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecTransformSetKey",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    "transform=%s",
                    xmlSecErrorsSafeString(xmlSecTransformGetName(encCtx->encMethod)));
        return(-1);
    }

    /* if we need to write result to xml node then we need base64 encode it */
    if((encCtx->operation == xmlSecTransformOperationEncrypt) && (encCtx->cipherValueNode != NULL)) {
        xmlSecTransformPtr base64Encode;

        /* we need to add base64 encode transform */
        base64Encode = xmlSecTransformCtxCreateAndAppend(&(encCtx->transformCtx), xmlSecTransformBase64Id);
        if(base64Encode == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecTransformCtxCreateAndAppend",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
        base64Encode->operation         = xmlSecTransformOperationEncode;
        encCtx->resultBase64Encoded     = 1;
    }

    return(0);
}
Ejemplo n.º 16
0
static void
lj_entry_load_from_xml_node(LJEntry *entry, xmlDocPtr doc, xmlNodePtr node) {
	xmlChar *itemid;
	xmlNodePtr cur;

	if ((itemid = xmlGetProp(node, BAD_CAST "itemid")) != NULL) {
		entry->itemid = atoi((char*)itemid);
		xmlFree(itemid);
	}
	cur = node->xmlChildrenNode;
	while (cur != NULL) {
		XML_ENTRY_META_GET(subject)
		else XML_ENTRY_META_GET(event)
		else if (xmlStrcmp(cur->name, BAD_CAST "mood") == 0) {
			xmlChar *id;
			entry->mood = (char*)xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			if (entry->mood && strlen(entry->mood) == 0) {
				g_free(entry->mood); entry->mood = NULL;
			}
			if ((id = xmlGetProp(cur, BAD_CAST "modeid")) != NULL) {
				entry->moodid = atoi((char*)id);
				xmlFree(id);
			}
		}
		else XML_ENTRY_META_GET(music)
		else XML_ENTRY_META_GET(location)
		else XML_ENTRY_META_GET(taglist)
		else XML_ENTRY_META_GET(pickeyword)
		else if (xmlStrcmp(cur->name, BAD_CAST "preformatted") == 0) {
			entry->preformatted = TRUE;
		} else if (xmlStrcmp(cur->name, BAD_CAST "backdated") == 0) {
			entry->backdated = TRUE;
		} else if (xmlStrcmp(cur->name, BAD_CAST "comments") == 0) {
			xmlChar *type;
			if ((type = xmlGetProp(cur, BAD_CAST "type")) != NULL) {
				if (xmlStrcmp(type, BAD_CAST "noemail") == 0) {
					entry->comments = LJ_COMMENTS_NOEMAIL;
				} else if (xmlStrcmp(type, BAD_CAST "disable") == 0) {
					entry->comments = LJ_COMMENTS_DISABLE;
				}
				xmlFree(type);
			}
		} else if (xmlStrcmp(cur->name, BAD_CAST "time") == 0) {
			xmlChar *date = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
			lj_ljdate_to_tm((char*)date, &entry->time);
			g_free(date);
		} else if (xmlStrcmp(cur->name, BAD_CAST "security") == 0) {
			xmlChar *type, *mask;
			type = xmlGetProp(cur, BAD_CAST "type");
			mask = xmlGetProp(cur, BAD_CAST "allowmask");
			lj_security_from_strings(&entry->security,
			                         (char*)type, (char*)mask);
			xmlFree(type);
			xmlFree(mask);
		}

		cur = cur->next;
	}
	/* http://www.livejournal.com/community/logjam/113710.html */
	if (!entry->subject)
		entry->subject = g_strdup("");
	if (!entry->event)
		entry->event = g_strdup("");
}
Ejemplo n.º 17
0
static gboolean
convert_metadata_file (const gchar *filename)
{
    ConvertData *data;
    xmlDocPtr doc;
    xmlNodePtr cur;

    if (!g_file_test (filename, G_FILE_TEST_EXISTS))
        return FALSE;

    doc = xmlParseFile (filename);
    if (!doc) {
        g_printerr ("Error loading metadata file %s\n", filename);
        return FALSE;
    }

    cur = xmlDocGetRootElement (doc);
    if (!cur) {
        g_printerr ("Metadata file %s is empty\n", filename);
        xmlFreeDoc (doc);
        return TRUE;
    }

    if (xmlStrcmp (cur->name, (const xmlChar *) "metadata")) {
        g_printerr ("File %s is not a valid atril metadata file\n", filename);
        xmlFreeDoc (doc);
        return FALSE;
    }

    data = g_new0 (ConvertData, 1);
    data->doc = doc;

    for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
        xmlChar *uri;
        DocItem *item;

        if (xmlStrcmp (cur->name, (const xmlChar *)"document") != 0)
            continue;

        uri = xmlGetProp (cur, (const xmlChar *)"uri");
        if (!uri)
            continue;

        item = g_new (DocItem, 1);
        item->uri = uri;
        item->cur = cur;
        data->items = g_list_prepend (data->items, item);
    }

    if (!data->items) {
        xmlFreeDoc (data->doc);
        g_free (data);

        return TRUE;
    }

    show_progress_dialog (data);

    data->current = data->items;
    g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
                     (GSourceFunc)convert_file,
                     data,
                     (GDestroyNotify)convert_finish);

    return TRUE;
}
int process_node(

  dynamic_string *status,
  xmlNode        *node)

  {
  char               *attr_value;
  char               *role_value;
  xmlNode            *child;
  xmlNode            *segments;
  xmlNode            *segment_child;
  dynamic_string     *features;
  char                buf[MAXLINE];
  int                 num_procs     = 0;
  int                 avail_procs   = 0;
  unsigned long       memory        = 0;
  unsigned long long  mem_kb;
  char               *rsv_id        = NULL;

  if ((features = get_dynamic_string(-1, NULL)) == NULL)
    return(ENOMEM);

  copy_to_end_of_dynamic_string(status, "node=");
  attr_value = (char *)xmlGetProp(node, (const xmlChar *)node_id);
  append_dynamic_string(status, attr_value);
  free(attr_value);

  /* check to see if the role is interactive - report these as down */
  role_value = (char *)xmlGetProp(node, (const xmlChar *)role);

  copy_to_end_of_dynamic_string(status, "ARCH=");
  attr_value = (char *)xmlGetProp(node, (const xmlChar *)architecture);
  append_dynamic_string(status, attr_value);
  free(attr_value);

  copy_to_end_of_dynamic_string(status, "name=");
  attr_value = (char *)xmlGetProp(node, (const xmlChar *)name);
  append_dynamic_string(status, attr_value);
  free(attr_value);

  /* process the children */
  for (child = node->children; child != NULL; child = child->next)
    {
    if (!strcmp((const char *)child->name, segment_array))
      {
      for (segments = child->children; segments != NULL; segments = segments->next)
        {
        for (segment_child = segments->children; segment_child != NULL; segment_child = segment_child->next)
          {
          if (!strcmp((const char *)segment_child->name, processor_array))
            process_processor_array(segment_child, &num_procs, &avail_procs, &rsv_id);
          else if (!strcmp((const char *)segment_child->name, memory_array))
            process_memory_array(segment_child, &memory);
          else if (!strcmp((const char *)segment_child->name, label_array))
            process_label_array(features, segment_child);
          }
        }
      }
    else if (!strcmp((const char *)child->name, processor_array))
      {
      process_processor_array(child, &num_procs, &avail_procs, &rsv_id);
      }
    else if (!strcmp((const char *)child->name, memory_array))
      {
      process_memory_array(child, &memory);
      }
    else if (!strcmp((const char *)child->name, label_array))
      {
      process_label_array(features, child);
      }
    else if (!strcmp((const char *)child->name, accelerator_array))
      {
      process_accelerator_array(status, child);
      }
    } /* END the loop for processing the children */

  /* once done, add the procs, available procs, memory info, reservation, and features */
  snprintf(buf, sizeof(buf), "CPROC=%d", num_procs);
  copy_to_end_of_dynamic_string(status, buf);

  snprintf(buf, sizeof(buf), "APROC=%d", avail_procs);
  copy_to_end_of_dynamic_string(status, buf);

  snprintf(buf, sizeof(buf), "CMEMORY=%lu", memory);
  copy_to_end_of_dynamic_string(status, buf);

  mem_kb = memory * 1024;

  snprintf(buf, sizeof(buf), "totmem=%llukb", mem_kb);
  copy_to_end_of_dynamic_string(status, buf);

  snprintf(buf, sizeof(buf), "physmem=%llukb", mem_kb);
  copy_to_end_of_dynamic_string(status, buf);

  if (rsv_id != NULL)
    {
    /* don't write the reservation id if we're in interactive mode */
    if ((role_value == NULL) ||
        (strcmp(role_value, interactive_caps)))
      {
      copy_to_end_of_dynamic_string(status, "reservation_id=");
      append_dynamic_string(status, rsv_id);
      }

    free(rsv_id);

    /* if there's a reservation on this node, the state is busy */
    copy_to_end_of_dynamic_string(status, "state=BUSY");
    
    snprintf(buf, sizeof(buf), "availmem=0kb");
    copy_to_end_of_dynamic_string(status, buf);
    }
  else
    {
    /* no reservation, evaluate the state normally */
    copy_to_end_of_dynamic_string(status, "state=");
    attr_value = (char *)xmlGetProp(node, (const xmlChar *)state);
    
    if ((role_value != NULL) &&
        (!strcmp(role_value, interactive_caps)))
      {
      append_dynamic_string(status, "DOWN");
      
      snprintf(buf, sizeof(buf), "availmem=0kb");
      copy_to_end_of_dynamic_string(status, buf);
      }
    else
      {
      append_dynamic_string(status, attr_value);
     
      snprintf(buf, sizeof(buf), "availmem=%llukb", mem_kb);
      copy_to_end_of_dynamic_string(status, buf);
      }

    free(attr_value);
    }

  if (role_value != NULL)
    free(role_value);

  if (features->used > 0)
    {
    copy_to_end_of_dynamic_string(status, "feature_list=");
    append_dynamic_string(status, features->str);
    }

  free_dynamic_string(features);

  return(PBSE_NONE);
  } /* END process_node() */
Ejemplo n.º 19
0
static gboolean
convert_file (ConvertData *data)
{
    GFile *file;
    DocItem *item;
    const gchar *uri;
    xmlNodePtr node;
    xmlNodePtr cur;
    gint total, current;
    gchar *text;

    if (!data->current)
        return FALSE;

    item = (DocItem *) data->current->data;
    uri = (const gchar *)item->uri;
    node = item->cur;
    data->current = g_list_next (data->current);

    /* Update progress information */
    total = g_list_length (data->items);
    current = ++(data->n_item);

    text = g_strdup_printf (_("Converting %s"), uri);
    gtk_label_set_text (GTK_LABEL (data->label), text);
    g_free (text);

    text = g_strdup_printf (_("%d of %d documents converted"), current, total);
    gtk_progress_bar_set_text (GTK_PROGRESS_BAR (data->progress), text);
    g_free (text);
    gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (data->progress),
                                   (gdouble)(current - 1) / total);

    file = g_file_new_for_uri (uri);
    if (!g_file_query_exists (file, NULL)) {
        g_printerr ("Uri %s does not exist\n", uri);
        g_object_unref (file);

        return data->current != NULL;
    }

    for (cur = node->xmlChildrenNode; cur != NULL; cur = cur->next) {
        xmlChar *key;
        xmlChar *value;

        if (xmlStrcmp (cur->name, (const xmlChar *)"entry") != 0)
            continue;

        key = xmlGetProp (cur, (const xmlChar *)"key");
        value = xmlGetProp (cur, (const xmlChar *)"value");
        if (key && value) {
            GFileInfo *info;
            gchar *gio_key;
            GError *error = NULL;

            info = g_file_info_new ();

            gio_key = g_strconcat (EV_METADATA_NAMESPACE"::", key, NULL);
            g_file_info_set_attribute_string (info, gio_key, (const gchar *)value);
            g_free (gio_key);

            if (!g_file_set_attributes_from_info (file, info, 0, NULL, &error)) {
                g_printerr ("Error setting metadata for %s: %s\n",
                            uri, error->message);
                g_error_free (error);
            }

            g_object_unref (info);
        }

        if (key)
            xmlFree (key);
        if (value)
            xmlFree (value);
    }

    g_object_unref (file);

    return data->current != NULL;
}
Ejemplo n.º 20
0
static GPInstructLessonTestScrambled *
parse_scrambled_test (xmlNode *node)
{
	GPInstructLessonTestScrambled *test = gpinstruct_lesson_test_scrambled_new ();

	xmlNode *current_node, *parent_node;
	xmlChar *temp;

	temp = xmlGetProp (node, BAD_CAST "title");
	if (temp)
	{
		gpinstruct_lesson_element_set_title (GPINSTRUCT_LESSON_ELEMENT (test), (gchar*) temp);
		xmlFree (temp);
	}

	temp = xmlGetProp (node, BAD_CAST "id");
	if (temp)
	{
		gpinstruct_lesson_test_set_id (GPINSTRUCT_LESSON_TEST (test), (gchar*) temp);
		xmlFree (temp);
	}

	temp = xmlGetProp (node, BAD_CAST "explain");
	if (temp)
	{
		gpinstruct_lesson_test_set_explain (GPINSTRUCT_LESSON_TEST (test), GCHAR_TO_GBOOLEAN ((gchar*) temp));
		xmlFree (temp);
	}

	for (current_node = node->children;
	     current_node != NULL;
	     current_node = current_node->next)
	{
		if (current_node->type == XML_ELEMENT_NODE)
		{
			if (xmlStrEqual (current_node->name, BAD_CAST "directions"))
			{
				temp = xmlNodeGetContent (current_node);
				if (temp)
				{
					gpinstruct_lesson_test_set_directions (GPINSTRUCT_LESSON_TEST (test), (gchar*) temp);
					xmlFree (temp);
				}
			}
			else if (xmlStrEqual (current_node->name, BAD_CAST "question"))
			{
				GPInstructLessonTestScrambledQuestion *question = gpinstruct_lesson_test_scrambled_question_new ();
				gpinstruct_lesson_test_scrambled_add_question (test, question);

				temp = xmlGetProp (current_node, BAD_CAST "answer");
				if (temp)
				{
					gpinstruct_lesson_test_scrambled_question_set_answer (question, (gchar*) temp);
					xmlFree (temp);
				}

				for (parent_node = current_node,
				     current_node = current_node->children;
				     current_node != NULL;
				     current_node = current_node->next)
				{
					if (current_node->type == XML_ELEMENT_NODE)
					{
						if (xmlStrEqual (current_node->name, BAD_CAST "text"))
						{
							temp = xmlNodeGetContent (current_node);
							if (temp)
							{
								gpinstruct_lesson_test_scrambled_question_set_text (question, (gchar*) temp);
								xmlFree (temp);
							}
						}
						else if (xmlStrEqual (current_node->name, BAD_CAST "explanation"))
						{
							temp = xmlNodeGetContent (current_node);
							if (temp)
							{
								gpinstruct_lesson_test_scrambled_question_set_explanation (question, (gchar*) temp);
								xmlFree (temp);
							}
						}
					}
				}

				current_node = parent_node;
				parent_node = current_node->parent;
			}
		}
	}

	return test;
}
Ejemplo n.º 21
0
                *name = g_strdup ((char *)val);
                xmlFree (val);
            }
            if (!*icon_data_uri && xmlStrcmp (child->name, (const xmlChar *)"Image") == 0)
            {
                xmlChar *val = xmlNodeListGetString(doc, child->xmlChildrenNode, 1);
                if (val)
                    *icon_data_uri = g_strdup ((char *)val);
                xmlFree (val);
            }
            if (!*url && xmlStrcmp (child->name, (const xmlChar *)"Url") == 0)
            {
                xmlChar *template;
                xmlChar *type;

                type = xmlGetProp(child, (const xmlChar *)"type");
                if (!type)
                    continue;

                if (xmlStrcmp (type, (const xmlChar *)"text/html") != 0)
                {
                    xmlFree (type);
                    continue;
                }
                xmlFree (type);

                template = xmlGetProp(child, (const xmlChar *)"template");
                if (!template)
                    continue;
                *url = g_strdup ((char *)template);
                xmlFree (template);
static void
mailwatch_read_config(Control *c, xmlNodePtr node)
{
    XfceMailwatchPlugin *mwp = c->data;
    xmlChar *value;
    gchar *cfgfile;
    gboolean reload_icon = TRUE;
    
    DBG("entering");
    
    value = xmlGetProp(node, (const xmlChar *)"click_command");
    if(value) {
        mwp->click_command = g_strdup(value);
        xmlFree(value);
    }
    
    value = xmlGetProp(node, (const xmlChar *)"new_messages_command");
    if(value) {
        mwp->new_messages_command = g_strdup(value);
        xmlFree(value);
    }
    
    value = xmlGetProp(node, (const xmlChar *)"normal_icon");
    if(value) {
        mwp->normal_icon = g_strdup(value);
        xmlFree(value);
        reload_icon = TRUE;
    } else
        mwp->normal_icon = g_strdup(DEFAULT_NORMAL_ICON);
    
    value = xmlGetProp(node, (const xmlChar *)"new_mail_icon");
    if(value) {
        mwp->new_mail_icon = g_strdup(value);
        xmlFree(value);
        reload_icon = TRUE;
    } else
        mwp->new_mail_icon = g_strdup(DEFAULT_NEW_MAIL_ICON);
    
    if(reload_icon)
        mailwatch_set_size(c, settings.size);
    
    value = xmlGetProp(node, (const xmlChar *)"log_lines");
    if(value) {
        mwp->log_lines = atoi(value);
        xmlFree(value);
    } else
        mwp->log_lines = DEFAULT_LOG_LINES;
    
    value = xmlGetProp(node, (const xmlChar *)"show_log_status");
    if(value) {
        mwp->show_log_status = (*value == '0' ? FALSE : TRUE);
        xmlFree(value);
    } else
        mwp->show_log_status = TRUE;
    
    value = xmlGetProp(node, (const xmlChar *)"cfgfile_suffix");
    if(!value) {
        GTimeVal gtv = { 0, 0 };
        
        g_get_current_time(&gtv);
        cfgfile = g_strdup_printf("xfce4/panel/mailwatch/mailwatch.%ld.%ld.rc",
                gtv.tv_sec, gtv.tv_usec);
    } else {
        cfgfile = g_strdup_printf("xfce4/panel/mailwatch/mailwatch.%s.rc", value);
        xmlFree(value);
    }
    
    xfce_mailwatch_set_config_file(mwp->mailwatch, cfgfile);
    DBG("cfgfile = %s", cfgfile);
    xfce_mailwatch_load_config(mwp->mailwatch);
    g_free(cfgfile);
}
Ejemplo n.º 23
0
static void _parse_root(xmlDocPtr doc, xmlNodePtr node, 
        ice_config_t *configuration)
{
    char *tmp;

    do {
        if (node == NULL) break;
        if (xmlIsBlankNode(node)) continue;

        if (strcmp(node->name, "location") == 0) {
            if (configuration->location && configuration->location != CONFIG_DEFAULT_LOCATION) xmlFree(configuration->location);
            configuration->location = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "admin") == 0) {
            if (configuration->admin && configuration->admin != CONFIG_DEFAULT_ADMIN) xmlFree(configuration->admin);
            configuration->admin = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if(strcmp(node->name, "authentication") == 0) {
            _parse_authentication(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "source-password") == 0) {
            /* TODO: This is the backwards-compatibility location */
            char *mount, *pass;
            if ((mount = (char *)xmlGetProp(node, "mount")) != NULL) {
                pass = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
                /* FIXME: This is a placeholder for per-mount passwords */
            }
            else {
                if (configuration->source_password && configuration->source_password != CONFIG_DEFAULT_SOURCE_PASSWORD) xmlFree(configuration->source_password);
                configuration->source_password = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            }
        } else if (strcmp(node->name, "icelogin") == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            configuration->ice_login = atoi(tmp);
            if (tmp) xmlFree(tmp);
        } else if (strcmp(node->name, "fileserve") == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            configuration->fileserve = atoi(tmp);
            if (tmp) xmlFree(tmp);
        } else if (strcmp(node->name, "relays-on-demand") == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            configuration->on_demand = atoi(tmp);
            if (tmp) xmlFree(tmp);
        } else if (strcmp(node->name, "hostname") == 0) {
            if (configuration->hostname && configuration->hostname != CONFIG_DEFAULT_HOSTNAME) xmlFree(configuration->hostname);
            configuration->hostname = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "listen-socket") == 0) {
            _parse_listen_socket(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "port") == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            configuration->port = atoi(tmp);
            configuration->listeners[0].port = atoi(tmp);
            if (tmp) xmlFree(tmp);
        } else if (strcmp(node->name, "bind-address") == 0) {
            if (configuration->listeners[0].bind_address) 
                xmlFree(configuration->listeners[0].bind_address);
            configuration->listeners[0].bind_address = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "master-server") == 0) {
            if (configuration->master_server) xmlFree(configuration->master_server);
            configuration->master_server = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "master-username") == 0) {
            if (configuration->master_username) xmlFree(configuration->master_username);
            configuration->master_username = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "master-password") == 0) {
            if (configuration->master_password) xmlFree(configuration->master_password);
            configuration->master_password = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "master-server-port") == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            configuration->master_server_port = atoi(tmp);
            xmlFree (tmp);
        } else if (strcmp(node->name, "master-update-interval") == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            configuration->master_update_interval = atoi(tmp);
            xmlFree (tmp);
        } else if (strcmp(node->name, "shoutcast-mount") == 0) {
            if (configuration->shoutcast_mount &&
                    configuration->shoutcast_mount != CONFIG_DEFAULT_SHOUTCAST_MOUNT)
                xmlFree(configuration->shoutcast_mount);
            configuration->shoutcast_mount = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
        } else if (strcmp(node->name, "limits") == 0) {
            _parse_limits(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "relay") == 0) {
            _parse_relay(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "mount") == 0) {
            _parse_mount(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "directory") == 0) {
            _parse_directory(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "paths") == 0) {
            _parse_paths(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "logging") == 0) {
            _parse_logging(doc, node->xmlChildrenNode, configuration);
        } else if (strcmp(node->name, "security") == 0) {
            _parse_security(doc, node->xmlChildrenNode, configuration);
        }
    } while ((node = node->next));
}
Ejemplo n.º 24
0
static int _picasa_api_upload_photo( _picasa_api_context_t *ctx, char *mime , char *data, int size , char *caption, char *description, gint imgid )
{
  _buffer_t buffer;
  memset(&buffer,0,sizeof(_buffer_t));
  char uri[4096]= {0};

  gchar *entry = g_markup_printf_escaped (
                   "<entry xmlns='http://www.w3.org/2005/Atom'>"
                   "<title>%s</title>"
                   "<summary>%s</summary>"
                   "<category scheme=\"http://schemas.google.com/g/2005#kind\""
                   " term=\"http://schemas.google.com/photos/2007#photo\"/>"
                   "</entry>",
                   caption,description);


  // Hack for nonform multipart post...
  gchar mpart1[4096]= {0};
  gchar *mpart_format="Media multipart posting\n--END_OF_PART\nContent-Type: application/atom+xml\n\n%s\n--END_OF_PART\nContent-Type: %s\n\n";
  sprintf(mpart1,mpart_format,entry,mime);

  int mpart1size=strlen(mpart1);
  int postdata_length=mpart1size+size+strlen("\n--END_OF_PART--");
  gchar *postdata=g_malloc(postdata_length);
  memcpy( postdata, mpart1, mpart1size);
  memcpy( postdata+mpart1size, data, size);
  memcpy( postdata+mpart1size+size, "\n--END_OF_PART--",strlen("\n--END_OF_PART--") );

  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers,ctx->authHeader);
  headers = curl_slist_append(headers,"Content-Type: multipart/related; boundary=\"END_OF_PART\"");
  headers = curl_slist_append(headers,"MIME-version: 1.0");
  headers = curl_slist_append(headers,"Expect:");
  headers = curl_slist_append(headers,"GData-Version: 2");

  sprintf(uri,"http://picasaweb.google.com/data/feed/api/user/default/albumid/%s", ctx->current_album->id);
  curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, uri);
#ifdef _DEBUG
  curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 1);
#else
  curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 0);
#endif
  curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD,0);   // A post request !
  curl_easy_setopt(ctx->curl_handle, CURLOPT_POST,1);
  curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDS, postdata);
  curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDSIZE, postdata_length);
  curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEFUNCTION, _picasa_api_buffer_write_func);
  curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEDATA, &buffer);

  curl_easy_perform( ctx->curl_handle );

  curl_slist_free_all(headers);

  long result;
  curl_easy_getinfo(ctx->curl_handle,CURLINFO_RESPONSE_CODE,&result );

  // If we want to add tags let's do...
  if( result == 201 && imgid > 0 )
  {
    // Image was created , fine.. and result have the fully created photo xml entry..
    // Let's perform an update of the photos keywords with tags passed along to this function..
    // and use picasa photo update api to add keywords to the photo...

    // Build the keywords content string
    gchar *keywords = NULL;
    keywords = dt_tag_get_list(imgid, ",");

    xmlDocPtr doc;
    xmlNodePtr entryNode;
    // Parse xml document
    if( ( doc = xmlParseDoc( (xmlChar *)buffer.data ))==NULL) return 0;
    entryNode = xmlDocGetRootElement(doc);
    if(  !xmlStrcmp(entryNode->name, (const xmlChar *) "entry") )
    {
      // Let's get the gd:etag attribute of entry...
      // For now, we force update using "If-Match: *"
      /*
        if( !xmlHasProp(entryNode, (const xmlChar*)"gd:etag") ) return 0;
        xmlChar *etag = xmlGetProp(entryNode,(const xmlChar*)"gd:etag");
      */

      gchar *photo_id=NULL;
      gchar *updateUri=NULL;
      xmlNodePtr entryChilds = entryNode->xmlChildrenNode;
      if( entryChilds != NULL )
      {
        do
        {
          if ((!xmlStrcmp(entryChilds->name, (const xmlChar *)"id")) )
          {
            // Get the photo id used in uri for update
            xmlChar *id= xmlNodeListGetString(doc, entryChilds->xmlChildrenNode, 1);
            if( xmlStrncmp( id, (const xmlChar *)"http://",7) )
              photo_id = g_strdup((const char *)id);
            xmlFree(id);
          }
          else  if ((!xmlStrcmp(entryChilds->name, (const xmlChar *)"group")) )
          {
            // Got the media:group entry lets find the child media:keywords
            xmlNodePtr mediaChilds = entryChilds->xmlChildrenNode;
            if(mediaChilds != NULL)
            {
              do
              {
                // Got the keywords tag, let's set the tags
                if ((!xmlStrcmp(mediaChilds->name, (const xmlChar *)"keywords")) )
                  xmlNodeSetContent(mediaChilds, (xmlChar *)keywords);
              }
              while( (mediaChilds = mediaChilds->next)!=NULL );
            }
          }
          else if (( !xmlStrcmp(entryChilds->name,(const xmlChar*)"link")) )
          {
            xmlChar *rel = xmlGetProp(entryChilds,(const xmlChar*)"rel");
            if( !xmlStrcmp(rel,(const xmlChar *)"edit") )
            {
              updateUri=(char *)xmlGetProp(entryChilds,(const xmlChar*)"href");
            }
            xmlFree(rel);
          }
        }
        while( (entryChilds = entryChilds->next)!=NULL );
      }

      // Let's update the photo
      struct curl_slist *headers = NULL;
      headers = curl_slist_append(headers,ctx->authHeader);
      headers = curl_slist_append(headers,"Content-Type: application/atom+xml");
      headers = curl_slist_append(headers,"If-Match: *");
      headers = curl_slist_append(headers,"Expect:");
      headers = curl_slist_append(headers,"GData-Version: 2");

      _buffer_t response;
      memset(&response,0,sizeof(_buffer_t));

      // Setup data to send..
      _buffer_t writebuffer;
      int datasize;
      xmlDocDumpMemory(doc,(xmlChar **)&writebuffer.data, &datasize);
      writebuffer.size = datasize;
      writebuffer.offset=0;

      curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, updateUri);
#ifdef _DEBUG
      curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 1);
#else
      curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 0);
#endif
      curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPHEADER, headers);
      curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD,1);   // A put request
      curl_easy_setopt(ctx->curl_handle, CURLOPT_READDATA,&writebuffer);
      curl_easy_setopt(ctx->curl_handle, CURLOPT_INFILESIZE,writebuffer.size);
      curl_easy_setopt(ctx->curl_handle, CURLOPT_READFUNCTION,_picasa_api_buffer_read_func);
      curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEFUNCTION, _picasa_api_buffer_write_func);
      curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEDATA, &response);
      curl_easy_perform( ctx->curl_handle );

      xmlFree( updateUri );
      xmlFree( writebuffer.data );
      if (response.data != NULL)
        g_free(response.data);
      if (photo_id != NULL)
        g_free(photo_id); // FIXME: never used!

      curl_slist_free_all( headers );
    }

  }
  return result;
}
Ejemplo n.º 25
0
AgsScriptObject*
ags_script_object_real_valueof(AgsScriptObject *script_object,
			       GError **error)
{
  AgsScriptObject *first_match, *last_match, *current;
  GList *node_list;
  guint retval_count;
  gchar *xpath;
  gchar **name;
  guint *index;
  guint index_length;
  guint name_length;
  xmlNode *node;
  guint i, j, k;
  guint z_index;
  guint current_node_count;
  gboolean is_node_after_first_match, is_node_after_last_match;

  /* entry */
  xpath = xmlGetProp(script_object->node, "retval\0");

  if((first_match = ags_script_object_find_flags_descending_first_match(script_object,
									AGS_SCRIPT_OBJECT_LAUNCHED,
									strtoul(xmlGetProp(script_object->node, "z_index\0"), NULL, 10))) == NULL){
    return(NULL);
  }

  last_match = ags_script_object_find_flags_descending_last_match(script_object,
								  AGS_SCRIPT_OBJECT_LAUNCHED,
								  strtoul(xmlGetProp(script_object->node, "z_index\0"), NULL, 10));

  retval_count = ags_script_object_count_retval(script_object);

  name = ags_script_object_split_xpath(xpath, &name_length);
  index = ags_script_object_read_index(xpath,
				       &index_length);

  if(index_length > retval_count){
    guint prefix_length;

    current = script_object;
    node_list = NULL;

    is_node_after_first_match = FALSE;
    is_node_after_last_match = TRUE;

    for(i = 0, j = 0; i < index_length; i++){

      if(current == first_match){
	is_node_after_first_match = TRUE;
      }

      if(current == NULL){
	/* set error */
	g_set_error(error,
		    AGS_SCRIPT_OBJECT_ERROR,
		    AGS_SCRIPT_OBJECT_INDEX_EXCEEDED,
		    "can't access index because it doesn't exist: %d of %d\0",
		    retval_count, retval_count);

	return(NULL);
      }

      /* find first - start */
      if(name[i][1] == '/'){
	prefix_length = 2;

	if(name[i][2] != '\0' && name[i][2] != '[' && name[i][2] != '@'){
	  while(current != NULL){
	    node = current->node;
	    
	  //FIXME:JK: strlen() not very safe
	    if(!xmlStrncmp(node->name, &(name[i][prefix_length]), strlen(node->name))){
	      break;
	    }else{
	      current = current->retval;
	      j++;
	    }
	  }
	}

	if(current == NULL){
	  /* set error */
	  g_set_error(error,
		      AGS_SCRIPT_OBJECT_ERROR,
		      AGS_SCRIPT_OBJECT_INDEX_EXCEEDED,
		      "named child doesn't exist\0");

	  return(NULL);
	}
      }else{
	prefix_length = 1;

	if(!xmlStrcmp(node->name, &(name[i][prefix_length]))){
	  current = current->retval;
	  node = current->node;

	  j++;
	}else{
	  /* set error */
	  g_set_error(error,
		      AGS_SCRIPT_OBJECT_ERROR,
		      AGS_SCRIPT_OBJECT_INDEX_EXCEEDED,
		      "named child doesn't exist\0");
	}
      }

      /* position */
      z_index = strtoul(xmlGetProp(node, "z_index\0"), NULL, 10);

      if(index[i] != AGS_SCRIPT_OBJECT_XPATH_NaN){
	for(k = 0; k < index[i] && current != NULL; j++){
	  node = current->node;
	  current = current->retval;
	  
	  //FIXME:JK: strlen() not very safe
	  if(!xmlStrncmp(node->name, &(name[i][prefix_length]), strlen(node->name)) &&
	     z_index == strtoul(xmlGetProp(node, "z_index\0"), NULL, 10)){
	    k++;
	  }
	}
      }else{
	current = last_match;
      }

      node_list = g_list_prepend(node_list,
				 node);

      if(index[i] != AGS_SCRIPT_OBJECT_XPATH_NaN && 
	 k != index[i]){
	/* set error */
	g_set_error(error,
		    AGS_SCRIPT_OBJECT_ERROR,
		    AGS_SCRIPT_OBJECT_INDEX_EXCEEDED,
		    "can't access index because it doesn't exist: %d of %d\0",
		    retval_count, retval_count);

	return(NULL);
      }
    }

    if(!is_node_after_first_match){
      /* set error */
      g_set_error(error,
		  AGS_SCRIPT_OBJECT_ERROR,
		  AGS_SCRIPT_OBJECT_INDEX_EXCEEDED,
		  "can't access index because it doesn't exist: %d of %d\0",
		  -1, index_length);

      return(NULL);
    }
  }else{
    /* set error */
    g_set_error(error,
		AGS_SCRIPT_OBJECT_ERROR,
		AGS_SCRIPT_OBJECT_INDEX_EXCEEDED,
		"can't access index because it doesn't exist: %d of %d\0",
		-1, index_length);

    return(NULL);
  }

  if(j > 0){
    return(current);
  }else{
    return(first_match);
  }
}
Ejemplo n.º 26
0
static void fetchSelectionDetails(const xmlNodePtr selectionNode, mdsSelection_t* selection)
{
    mdsSelectionItem_t* item = NULL;

    int           i;
    xmlChar*      xcp;
    xmlNodePtr    child = NULL;
    xmlNodePtr*   p_node = NULL;
    xmlNodeSetPtr itemNodes = NULL;
    int           itemNum;  // number of items
    int           itemIdx;  // item index


    CL_LOGPRINTF("entry");

    // get "id" attribute
    xcp = xmlGetProp(selectionNode, "id");
    if (xcp == NULL)
    {
        xcp = xmlStrdup("");
    }
    selection->id = xcp;

    // get "constant" attribute
    selection->constant = FALSE;
    xcp = xmlGetProp(selectionNode, "constant");
    if (xcp)
    {
        if (xmlStrcmp(xcp, "true") == 0)
        {
            selection->constant = TRUE;
        }
        xmlFree(xcp);
    }

    // get "hide" attribute
    selection->hide = FALSE;
    xcp = xmlGetProp(selectionNode, "hide");
    if (xcp)
    {
        if (xmlStrcmp(xcp, "true") == 0)
        {
            selection->hide = TRUE;
        }
        xmlFree(xcp);
    }

    // get "sequence" attribute
    selection->sequence = 0;
    xcp = xmlGetProp(selectionNode, "sequence");
    if (xcp)
    {
        i = atoi(xcp);
        if (i >= 0)
        {
            selection->sequence = i;
        }
        xmlFree(xcp);
    }

    // get "display-as" value
    xcp   = NULL;
    child = ermXmlGetChildNode(selectionNode, "display-as");
    if (child)
    {
        xcp = xmlNodeGetContent(child);
    }
    if (xcp == NULL)
    {
        xcp = xmlStrdup("");
    }
    selection->display_as = xcp;

    // get "title" value
    xcp   = NULL;
    child = ermXmlGetChildNode(selectionNode, "title");
    if (child)
    {
        xcp = xmlNodeGetContent(child);
    }
    if (xcp == NULL)
    {
        xcp = xmlStrdup("");
    }
    selection->title = xcp;

    // get "instruction" value
    xcp   = NULL;
    child = ermXmlGetChildNode(selectionNode, "instruction");
    if (child)
    {
        xcp = xmlNodeGetContent(child);
    }
    if (xcp == NULL)
    {
        xcp = xmlStrdup("");
    }
    selection->instruction = xcp;

    // get "min-selected" value
    selection->min_selected = 1;  // default
    child = ermXmlGetChildNode(selectionNode, "min-selected");
    if (child)
    {
        xcp = xmlNodeGetContent(child);
        i = atoi(xcp);
        if (i >= 0)
        {
            selection->min_selected = i;
        }
        xmlFree(xcp);
    }

    // get "max-selected" value
    selection->max_selected = 1;  // default
    child = ermXmlGetChildNode(selectionNode, "max-selected");
    if (child)
    {
        xcp = xmlNodeGetContent(child);
        i = atoi(xcp);
        if (i >= 0)
        {
            selection->max_selected = i;
        }
        xmlFree(xcp);
    }

    // get selection items
    selection->num_items = 0;
    child = ermXmlGetChildNode(selectionNode, "selection-item-list");
    if (child)
    {
        itemNodes = ermXmlGetChildNodeSet(child, "selection-item");
        itemNum   = itemNodes->nodeNr;
        selection->num_items = itemNum;
        selection->items     = g_new0(mdsSelectionItem_t, itemNum);

        p_node = itemNodes->nodeTab;
        item = (mdsSelectionItem_t*) selection->items;  // const_cast
        for (itemIdx = 0 ; itemIdx < itemNum ; itemIdx++, p_node++, item++)
        {
            fetchSelectionItemDetails(*p_node, item);
        }
    }
    else { CL_ERRORPRINTF("No selection-item-list"); }

    // sort the selections
    qsort( (void*)selection->items,
            selection->num_items,
            sizeof(selection->items[0]),
            selectionItemCompareFunc );
    
    // free temporary memory
    if (itemNodes) { xmlXPathFreeNodeSet(itemNodes); }
}
Ejemplo n.º 27
0
/* process xml response */
static int __process_node_xml_response(xmlDoc * doc, xmlNode * node,
                                       int ent_id)
{
    loginfo(_("node response for entity %d\n"), ent_id);
    char * str = (char *) xmlGetProp(node, (const xmlChar *) "id");
    if (str)
        logdebug("node response id(job id) = %s\n", str);
    else {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        return -1;
    }
    int id = atoi(str);
    free(str);

    str = (char *) xmlGetProp(node, (const xmlChar *) "status");
    if (str)
        logdebug("node response status = %s\n", str);
    else {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        return -1;
    }
    int status = atoi(str);
    free(str);

    int data_type = -1;
    node = node->children;
    for (; node; node = node->next) {
        if (node->type == XML_ELEMENT_NODE) {
            if (strcmp((char *)node->name, "result") == 0) {
                xmlNode * n = node->children;
                if (n && n->type == XML_TEXT_NODE && n->content)
                    loginfo(_("response result: %s\n"), n->content);
                else
                    loginfo(_("response no result message\n"));
            }
            else if (strcmp((char *)node->name, "data") == 0) {
                str = (char *) xmlGetProp(node, (const xmlChar *) "type");
                if (str) {
                    logdebug("node response data type = %s\n", str);
                    data_type = atoi(str);
                    free(str);
                }
                else
                    logwarn(_("response data no type\n"));
            }
        }
    }

    if (id != 0) {
        LYJobInfo * job = job_find(id);
        if (job == NULL) {
            logwarn(_("job(%d) not found waiting for node reply\n"), id);
            return 0;
        }
        if (job_update_status(job, status)) {
            logerror(_("error in %s(%d)\n"), __func__, __LINE__);
            return -1;
        }
        if (status != LY_S_FINISHED_SUCCESS || data_type < 0)
            return 0;
    }

    int ent_type = ly_entity_type(ent_id);
    if (ent_type == LY_ENTITY_NODE && data_type == DATA_INSTANCE_INFO) { 
        if ( __instance_info_update(doc, node, ent_id, &status)) {
            logerror(_("error in %s(%d)\n"), __func__, __LINE__);
            return -1;
        }
    }
   
    if (ent_type == LY_ENTITY_NODE && data_type == DATA_NODE_INFO) { 
        if ( __node_info_update(doc, node, ent_id, &status)) {
            logerror(_("error in %s(%d)\n"), __func__, __LINE__);
            return -1;
        }
    }
 
    return 0;
}
Ejemplo n.º 28
0
static void parseModifyEnable(xmlDocPtr doc, xmlNodePtr cur, clDisplayItem_t * displayItem, char *szContainerPath)
{
    xmlChar*   key;
    xmlNodePtr child;
    gboolean   bDefault;
    gboolean   bSpecific;

    // get default value
    bDefault = FALSE;
    key = xmlGetProp(cur, "default");
    if (key)
    {
        if ( xmlStrcmp(key, "true") == 0 )
        {
            bDefault = TRUE;
        }
        xmlFree(key);
    }
    displayItem->modifyEnable.bDefault = bDefault;

    // specific values as specified in child elements
    bSpecific = bDefault;
    child = ermXmlGetChildNode(cur, "delete-enable");
    if (child)
    {
        key = xmlNodeGetContent(child);
        if (key)
        {
            if ( xmlStrcmp(key, "true") == 0 )
            {
                bSpecific = TRUE;
            }
            else
            {
                // specific is "false" or invalid,
                // in both situations consider it "false"
                bSpecific = FALSE;
            }
            xmlFree(key);
        }
    }
    displayItem->modifyEnable.bDelete = bSpecific;
    //
    bSpecific = bDefault;
    child = ermXmlGetChildNode(cur, "scribble-enable");
    if (child)
    {
        key = xmlNodeGetContent(child);
        if (key)
        {
            if ( xmlStrcmp(key, "true") == 0 )
            {
                bSpecific = TRUE;
            }
            else
            {
                // specific is "false" or invalid,
                // in both situations consider it "false"
                bSpecific = FALSE;
            }
            xmlFree(key);
        }
    }
    displayItem->modifyEnable.bScribble = bSpecific;
    //
    bSpecific = bDefault;
    child = ermXmlGetChildNode(cur, "tagging-enable");
    if (child)
    {
        key = xmlNodeGetContent(child);
        if (key)
        {
            if ( xmlStrcmp(key, "true") == 0 )
            {
                bSpecific = TRUE;
            }
            else
            {
                // specific is "false" or invalid,
                // in both situations consider it "false"
                bSpecific = FALSE;
            }
            xmlFree(key);
        }
    }
    displayItem->modifyEnable.bTagging = bSpecific;
}
Ejemplo n.º 29
0
int erClXmlParseManifest(char *szContainerPath, clDisplayItem_t * displayItem)
{
    int      ret = -1;  // return value: 0 = ok, -1 = error

    xmlDoc  *doc            = NULL;
    xmlNode *rootElement    = NULL;
    xmlNode *cur            = NULL;
    xmlNode *symlinkElement = NULL;
    xmlChar *targetPath     = NULL;
    xmlChar *key;


    int n = strlen(szContainerPath) + 1 + strlen(MANIFEST_FILENAME) + 1;
    char *szFilename = alloca(n);
    g_assert(szFilename != NULL);
    snprintf(szFilename, n, "%s/" MANIFEST_FILENAME, szContainerPath);
    
    LIBXML_TEST_VERSION doc = xmlParseFile(szFilename);

    if (doc == NULL)
    {
        CL_ERRORPRINTF("Document not parsed successfully");
        return ret;
    }

    /* Get the root element node */
    rootElement = xmlDocGetRootElement(doc);

    // Check whether we have a document with the correct root (i.e. package)
    if (xmlStrcmp(rootElement->name, (const xmlChar *) "package"))
    {
        CL_ERRORPRINTF("Document of the wrong type, root node != package");
        xmlFreeDoc(doc);
        return ret;
    }

    
    // Check whether this manifest actually is a symlink
    symlinkElement = ermXmlGetChildNode(rootElement, "symlink");
    if (symlinkElement)
    {
        // check whether target must be extended with locale
        displayItem->fit = mdsFitManifestSymlink;
        key = xmlGetProp(symlinkElement, "add-locale");
        if (key)
        {
            if (xmlStrcmp(key, "true") == 0)
            {
                displayItem->fit = mdsFitManifestSymlinkLocale;
            }
            xmlFree(key);
        }

        // get target details
        targetPath = xmlNodeGetContent(symlinkElement);
        szFilename = getVerifiedPath(targetPath, szContainerPath);
        CL_WARNPRINTF("symlink [%s] [%s] --> [%s]", szContainerPath, targetPath, szFilename);
        if (szFilename)
        {
            strcpy(displayItem->szFilename, szFilename);
            free(szFilename);
        }
        else
        {
            CL_ERRORPRINTF("directory [%s] [%s] is incorrect", szContainerPath, targetPath);
            // display as a folder without manifest
            strcpy(displayItem->szFilename, szContainerPath);
            displayItem->fit = mdsFitFolder;
        }
    }
    else
    {
        cur = rootElement->xmlChildrenNode;
        while (cur != NULL)
        {
            if ((!xmlStrcmp(cur->name, (const xmlChar *) "metadata")))
            {
                CL_LOGPRINTF("Found node metadata");
                parseMetadata(doc, cur, displayItem, szContainerPath);
            }

            if ((!xmlStrcmp(cur->name, (const xmlChar *) "storage")))
            {
                CL_LOGPRINTF("Found node storage");
                parseStoragedata(doc, cur, displayItem, szContainerPath);
                //update the type of container, since this is a special type of container
                displayItem->fit = mdsFitStorage;
            }

            if ((!xmlStrcmp(cur->name, (const xmlChar *) "application")))
            {
                CL_LOGPRINTF("Found node application");
                parseApplicationdata(doc, cur, displayItem, szContainerPath);
                //update the type of container, since this is a special type of container
                displayItem->fit = mdsFitApplication;
            }

            if ((!xmlStrcmp(cur->name, (const xmlChar *) "directory")))
            {
                CL_LOGPRINTF("Found node directory");
                parseDirectorydata(doc, cur, displayItem, szContainerPath);
                //update the type of container, since this is a special type of container
                displayItem->fit = mdsFitManifestDirectory;
            }
            cur = cur->next;
        }
    }

    /* free the document */
    xmlFreeDoc(doc);

    /* Free the global variables that may have been allocated by the parser */
    xmlCleanupParser();

    return 0;
}
Ejemplo n.º 30
-1
/**
 * Reinit a program object using data from [cur] xmlNode and applying [locale]
 * When [cur]==0 the object is cleared, memory freed and the object is put to its
 * initial empty state
 */
static void reinit_program( program_t *pro, xmlNodePtr cur, xmlChar *locale )
{
    if( cur ) {
        xmlChar *start = xmlGetProp( cur, BAD_CAST "start" );
        xmlChar *stop = xmlGetProp( cur, BAD_CAST "stop" );
        xmlChar *lang;
        time_t start_time = 0;
        time_t end_time = 0;

        if( start ) {
            start_time = parse_xmltv_date( (char *) start );
            xmlFree( start );
        }
        if( stop ) {
            end_time = parse_xmltv_date( (char *) stop );
            xmlFree( stop );
        } else {
            end_time = start_time + 1800;
        }
        pro->start_time = start_time;
        pro->end_time = end_time;

        cur = cur->xmlChildrenNode;
        while( cur ) {
            lang = xmlGetProp( cur, BAD_CAST "lang");
            if( !xmlStrcasecmp( cur->name, BAD_CAST "title" ) ) {
                if( !lang || !locale ) {
                    if ( pro->title ) xmlFree ( pro->title );
                    pro->title = xmlNodeGetContent( cur );
                } else if( !xmlStrncasecmp( lang, locale, 2 ) ) {
                    if ( pro->title_local ) xmlFree ( pro->title_local );
                    pro->title_local = xmlNodeGetContent( cur );
                } else if( !pro->title ) {
                    pro->title = xmlNodeGetContent( cur );
                }
            } else if( !xmlStrcasecmp( cur->name, BAD_CAST "sub-title" ) ) {
                if( !lang || !locale ) {
                    if ( pro->subtitle ) xmlFree ( pro->subtitle );
                    pro->subtitle = xmlNodeGetContent( cur );
                } else if( !xmlStrncasecmp( lang, locale, 2 ) ) {
                    if ( pro->subtitle_local )
                        xmlFree ( pro->subtitle_local );
                    pro->subtitle_local = xmlNodeGetContent( cur );
                } else if( !pro->subtitle ) {
                    pro->subtitle = xmlNodeGetContent( cur );
                }
            } else if( !xmlStrcasecmp( cur->name, BAD_CAST "desc" ) ) {
                if( !lang || !locale ) {
                    if ( pro->description ) xmlFree ( pro->description );
                    pro->description = xmlNodeGetContent( cur );
                } else if( !xmlStrncasecmp( lang, locale, 2 ) ) {
                    if ( pro->description_local )
                        xmlFree ( pro->description_local );
                    pro->description_local = xmlNodeGetContent( cur );
                } else if( !pro->description ) {
                    pro->description = xmlNodeGetContent( cur );
                }
            }
            if( lang ) xmlFree( lang );
            cur = cur->next;
        }
    } else {
         pro->title = pro->subtitle = pro->description = 0;
         pro->title_local = pro->subtitle_local = pro->description_local = 0;
         pro->start_time = 0;
         pro->end_time = 0;
    }
}