예제 #1
0
파일: fault.c 프로젝트: nelsonc/eucalyptus
/*
 * Retrieves a translated label from <fault> block.
 *
 * NOTE: The pointer returned by this function must be free()'d by the
 * caller.
 *
 * FIXME: Consolidate with get_common_var()?
 *
 * FIXME: Gosh this looks messy.
 */
static char *
get_fault_var (const char *var, const xmlNode *f_node)
{
    if ((f_node == NULL) || (var == NULL)) {
        logprintfl (EUCAWARN, "get_fault_var() called with one or more NULL arguments.\n");
        return NULL;
    }
    // Just in case we're matching the top-level node.
    // FIXME: Move this into a new tmfunction to eliminate repeated logic below?
    if ((f_node->type == XML_ELEMENT_NODE) &&
        !strcasecmp ((const char *)f_node->name, var)) {
        xmlChar *value = xmlGetProp ((xmlNode *)f_node,
                                     (const xmlChar *)LOCALIZED_TAG);
        if (value == NULL) {
            value = xmlGetProp ((xmlNode *)f_node,
                                (const xmlChar *)MESSAGE_TAG);
        }
        // This is a special (parent) case, so it doesn't handle
        // message/localized text in a child node.
        return (char *)value;
    }
    for (xmlNode *node = xmlFirstElementChild ((xmlNode *)f_node); node;
         node = node->next) {
        if ((node->type == XML_ELEMENT_NODE) &&
            !strcasecmp ((const char *)node->name, var)) {
            xmlChar *value = xmlGetProp (node, (const xmlChar *)LOCALIZED_TAG);

            if (value == NULL) {
                value = xmlGetProp (node, (const xmlChar *)MESSAGE_TAG);
            }
            if (value == NULL) {
                // May be a child node, e.g. for "resolution"
                for (xmlNode *subnode = xmlFirstElementChild (node); subnode;
                     subnode = subnode->next) {
                    if ((node->type == XML_ELEMENT_NODE) &&
                        !strcasecmp ((const char *)subnode->name,
                                     LOCALIZED_TAG)) {
                        return (char *)xmlNodeGetContent (subnode);
                    }
                }
                // FIXME: More elegant method than another list walk?
                for (xmlNode *subnode = xmlFirstElementChild (node); subnode;
                     subnode = subnode->next) {
                    if ((node->type == XML_ELEMENT_NODE) &&
                        !strcasecmp ((const char *)subnode->name,
                                     MESSAGE_TAG)) {
                        return (char *)xmlNodeGetContent (subnode);
                    }
                }
            }
            return (char *)value;
        }
    }
    logprintfl (EUCAWARN, "Did not find <%s> message in get_fault_var().\n",
                var);
    return NULL;
}
예제 #2
0
static gint
parse_radio_list(GString *data, GList **list)
{
	gint result = 1;
	xmlDocPtr doc;

	if (data->str == NULL || data->len == 0)
		return 1;

	doc = xmlReadMemory(data->str, data->len, NULL, NULL,
				XML_PARSE_RECOVER | XML_PARSE_NOERROR);

	if (doc == NULL)
		return result;

	do
	{
		xmlNodePtr radioList;
		xmlNodePtr p;

		radioList = xmlDocGetRootElement(doc);
		if (radioList == NULL)
			break;

		for(p=xmlFirstElementChild(radioList); p; p=xmlNextElementSibling(p))
			get_radio(p, list);

		result = 0;
	}
	while(0);

	xmlFreeDoc(doc);

	return result;
}
예제 #3
0
파일: fault.c 프로젝트: nelsonc/eucalyptus
/*
 * Retrieves a translated label from <common> block.
 *
 * NOTE: The pointer returned by this function must be free()'d by the
 * caller.
 *
 * FIXME: Consolidate this with get_fault_id() and make some sort of
 * general-purpose fetch function? Or make get_fault_id() more general
 * and change this to call it?
 *
 * FIXME: Consolidate with get_fault_var()?
 */
static char *
get_common_var (const char *var)
{
    xmlNode *c_node = NULL;

    if ((c_node = get_common_block (ef_doc)) == NULL) {
        logprintfl (EUCAWARN, "Did not find <%s> block\n", COMMON_PREFIX);
        return strdup (var);
    }
    for (xmlNode *node = xmlFirstElementChild (c_node); node;
         node = node->next) {
        if ((node->type == XML_ELEMENT_NODE) &&
            !strcasecmp ((const char *)node->name, "var")) {
            xmlChar *prop = xmlGetProp (node, (const xmlChar *)"name");

            if (!strcasecmp (var, (char *)prop)) {
                xmlChar *value = NULL;

                xmlFree (prop);
                value = xmlGetProp (node, (const xmlChar *)LOCALIZED_TAG);

                if (value == NULL) {
                    value = xmlGetProp (node, (const xmlChar *)"value");
                }
                return (char *)value;
            } else {
                xmlFree (prop);
            }
        }
    }
    // If nothing useful is found, return original variable-name string.
    logprintfl (EUCAWARN, "Did not find label '%s'\n", var);
    return strdup (var);
}
예제 #4
0
xmlNodePtr feed_first_item(xmlDocPtr *doc)
{
	xmlNodePtr node, i_node;
	
	/* get <rss> node */
	node = xmlDocGetRootElement(doc);
	if (node == 0) {
		fprintf(stderr, "Could not find rss node");
		return EXIT_FAILURE;
	}
	
	/* get <channel> node */
	node = xmlFirstElementChild(node);
	if (node == 0) {
		fprintf(stderr, "Could not find channel node");
		return EXIT_FAILURE;
	}
	
	/* find first <item> node */
	for (i_node = node->children; i_node; i_node = i_node->next) {
		if (strcmp(i_node->name,"item") == 0)
			return i_node;
	}
	
	return NULL;
}
예제 #5
0
/**
 * get first child of a node
 *
 * @param n parent node
 * @result child node or NULL
 */
NftPrefsNode *nft_prefs_node_get_first_child(NftPrefsNode * n)
{
		if(!n)
				NFT_LOG_NULL(NULL);

        return xmlFirstElementChild(n);
}
예제 #6
0
/*
 * call-seq:
 *  element_children
 *
 * Get the list of children for this node as a NodeSet.  All nodes will be
 * element nodes.
 *
 * Example:
 *
 *   @doc.root.element_children.all? { |x| x.element? } # => true
 */
static VALUE element_children(VALUE self)
{
  xmlNodePtr node;
  xmlNodePtr child;
  xmlNodeSetPtr set;
  VALUE document;
  VALUE node_set;

  Data_Get_Struct(self, xmlNode, node);

  child = xmlFirstElementChild(node);
  set = xmlXPathNodeSetCreate(child);

  document = DOC_RUBY_OBJECT(node->doc);

  if(!child) return Nokogiri_wrap_xml_node_set(set, document);

  child = xmlNextElementSibling(child);
  while(NULL != child) {
    xmlXPathNodeSetAddUnique(set, child);
    child = xmlNextElementSibling(child);
  }

  node_set = Nokogiri_wrap_xml_node_set(set, document);

  return node_set;
}
예제 #7
0
static xmlDoc *test_xslt_transforms(xmlDoc *doc, GError **error)
{
	struct xslt_files *info = xslt_files;
	xmlDoc *transformed;
	xsltStylesheetPtr xslt = NULL;
	xmlNode *root_element = xmlDocGetRootElement(doc);
	char *attribute;

	while ((info->root) && (strcasecmp(root_element->name, info->root) != 0)) {
		info++;
	}

	if (info->root) {
		attribute = xmlGetProp(xmlFirstElementChild(root_element), "name");
		if (attribute) {
			if (strcasecmp(attribute, "subsurface") == 0) {
				free((void *)attribute);
				return doc;
			}
			free((void *)attribute);
		}

		xmlSubstituteEntitiesDefault(1);
		xslt = get_stylesheet(info->file);
		if (xslt == NULL) {
			parser_error(error, _("Can't open stylesheet (%s)/%s"), xslt_path, info->file);
			return doc;
		}
		transformed = xsltApplyStylesheet(xslt, doc, NULL);
		xmlFreeDoc(doc);
		xsltFreeStylesheet(xslt);
		return transformed;
	}
	return doc;
}
예제 #8
0
파일: schema.c 프로젝트: ZoloZiak/reactos
static BOOL link_datatypes(xmlDocPtr schema)
{
    xmlNodePtr root, next, child;
    xmlNsPtr ns;

    assert(xmlGetExternalEntityLoader() == external_entity_loader);
    root = xmlDocGetRootElement(schema);
    if (!root)
        return FALSE;

    for (ns = root->nsDef; ns != NULL; ns = ns->next)
    {
        if (xmlStrEqual(ns->href, DT_nsURI))
            break;
    }

    if (!ns)
        return FALSE;

    next = xmlFirstElementChild(root);
    child = xmlNewChild(root, NULL, BAD_CAST "import", NULL);
    if (next) child = xmlAddPrevSibling(next, child);
    xmlSetProp(child, BAD_CAST "namespace", DT_nsURI);
    xmlSetProp(child, BAD_CAST "schemaLocation", DT_nsURI);

    return TRUE;
}
예제 #9
0
xmlNode* XMLParser::getChild(xmlNodePtr cur) const
{
	if(!cur)
	{
		fprintf(stderr,"Warning: Got Empty Node\n");
		return NULL;
	}
	return xmlFirstElementChild(cur);
}
예제 #10
0
/*
 * call-seq:
 *  first_element_child
 *
 * Returns the first child node of this node that is an element.
 *
 * Example:
 *
 *   @doc.root.first_element_child.element? # => true
 */
static VALUE first_element_child(VALUE self)
{
  xmlNodePtr node, child;
  Data_Get_Struct(self, xmlNode, node);

  child = xmlFirstElementChild(node);
  if(!child) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, child);
}
예제 #11
0
/* create junction boxes */
int _create_jb_object(xmlNodePtr node, struct _zparser* parser)
{
    xmlNodePtr _child = NULL;
    struct _zobject* _obj = NULL;
    struct _jb_dims
    {
	double x __attribute__ ((aligned (ZELIA_XML_TSTRUCT_ALIGN)));
	double y __attribute__ ((aligned (ZELIA_XML_TSTRUCT_ALIGN)));
	double width __attribute__ ((aligned (ZELIA_XML_TSTRUCT_ALIGN)));
	double height __attribute__ ((aligned (ZELIA_XML_TSTRUCT_ALIGN)));
	double depth __attribute__ ((aligned (ZELIA_XML_TSTRUCT_ALIGN)));
	double radius __attribute__ ((aligned (ZELIA_XML_TSTRUCT_ALIGN)));
	double angle __attribute__ ((aligned (ZELIA_XML_TSTRUCT_ALIGN)));
    } _jb_dim;

    /* create notes object collection */
    memset(&_jb_dim, 0, sizeof(struct _jb_dims));

    _obj = (struct _zobject*) malloc(sizeof(struct _zobject));
    _obj->type = zobject_item;

    _child = xmlFirstElementChild(node);
    _create_jb_object_helper(_child, (void*) &_jb_dim);

    /* create junction box object */
    _obj->data._i = zjb_new(NULL,
			    &parser->device,
			    _jb_dim.x,
			    _jb_dim.y,
			    _jb_dim.width,
			    _jb_dim.height,
			    _jb_dim.depth,
			    _jb_dim.angle);

    zjb_set_fillet_radius(Z_JB(_obj->data._i), _jb_dim.radius);

    while(_child)
	{
	    if(strcmp((const char*) _child->name, ZPARSER_TERMINALS) == 0)
		_create_jb_object_terminals_helper(_child, _obj->data._i);
	    else if(strcmp((const char*) _child->name, ZPARSER_GLAND) == 0)
		_create_jb_object_gland_helper(_child, _obj->data._i);

	    _child = xmlNextElementSibling(_child);
	}

    /* call draw method */
    zgeneric_draw(_obj->data._i);

    /* push to the collection */
    blist_add_from_end(&parser->object_array, (void*) _obj);

    return ZELIA_OK;
}
예제 #12
0
파일: fault.c 프로젝트: nelsonc/eucalyptus
/*
 * Adds XML doc for a fault to the in-memory fault registry (doc).
 * Creates registry if none exists yet.
 *
 * Can also add COMMON_PREFIX (<common>) block.
 */
static boolean
add_eucafault (const xmlDoc *new_doc)
{
    if (xmlDocGetRootElement (ef_doc) == NULL) {
        logprintfl (EUCATRACE, "Creating new document.\n");
        ef_doc = xmlCopyDoc ((xmlDoc *)new_doc, 1); /* 1 == recursive copy */

        if (ef_doc == NULL) {
            logprintfl (EUCAERROR, "Problem creating fault registry.\n");
            return FALSE;
        }
    } else {
        logprintfl (EUCATRACE, "Appending to existing document.\n");
        if (xmlAddNextSibling (xmlFirstElementChild (xmlDocGetRootElement (ef_doc)),
                               xmlFirstElementChild (xmlDocGetRootElement ((xmlDoc *)new_doc))) == NULL) {
            logprintfl (EUCAERROR, "Problem adding fault to existing registry.\n");
            return FALSE;
        }
    }
    return TRUE;
}
예제 #13
0
int _create_label_object(xmlNodePtr node, struct _zparser* parser)
{
    struct _zobject* _obj = NULL;

    xmlNodePtr _child = NULL;
    xmlChar* _content = NULL;
    xmlChar* _path = NULL;
    unsigned int _del_flg = 1;
    double _x = 0.0, _y = 0.0;
    
    _child = xmlFirstElementChild(node);
    while(_child)
	{
	    _del_flg = 1;
	    _content = xmlNodeGetContent(_child);
	    if(strcmp((const char*) _child->name, ZPARSER_TEMPLATE_PATH) == 0)
		{
		    _del_flg = 0;
		    _path = _content;
		}
	    else if(strcmp((const char*) _child->name, ZPARSER_COORD_X) == 0)
		_x = atof((const char*) _content);
	    else if(strcmp((const char*) _child->name, ZPARSER_COORD_Y) == 0)
		_y = atof((const char*) _content);
	    
	    /* if delete flag is true delete and set the pointer to NULL */
	    if(_del_flg)
		{
		    xmlFree(_content);
		    _content = NULL;
		}
	    
	    _child = xmlNextElementSibling(_child);
	}

    if(_path == NULL)
	return ZELIA_NULL;

    /* create object */
    _obj = (struct _zobject*) malloc(sizeof(struct _zobject));
    _obj->type = zobject_item;

    _obj->data._i = zlabel_new(NULL, &parser->file, (const char*) _path, _x, _y);
    
    /* call draw method */
    zgeneric_draw(_obj->data._i);

    /* push to the collection */
    blist_add_from_end(&parser->object_array, (void*) _obj);
    
    return ZELIA_OK;
}
예제 #14
0
파일: CMRXmlDoc.cpp 프로젝트: svalat/CMR
/*******************  FUNCTION  *********************/
CMRXmlNode CMRXmlNode::getFirstChild ( void )
{
	//nothing
	if (node == NULL)
	{
		return CMRXmlNode(NULL);
	} else if ((node->type == XML_ELEMENT_NODE) && (node->children != NULL)) {
		xmlNodePtr res = xmlFirstElementChild(node);
		return CMRXmlNode(res);
	} else {
		return CMRXmlNode(NULL);
	}
}
예제 #15
0
파일: libxml.hpp 프로젝트: APTriTec/ponder
    static NodeType findFirstChild(NodeType node, const std::string& name)
    {
        const xmlChar* convertedName = reinterpret_cast<const xmlChar*>(name.c_str());
        NodeType child = xmlFirstElementChild(node);
        while (child)
        {
            if (xmlStrcmp(child->name, convertedName) == 0)
                break;
            else
                child = xmlNextElementSibling(child);
        }

        return child;
    }
예제 #16
0
int _create_file_object(xmlNodePtr node, struct _zparser* parser)
{
    char* _save_path = NULL;
    char* _template_path = NULL;
    char* _sheet_size = NULL;
    zSheets _sheet_type = zSheetA4_Portrait;

    xmlNodePtr _child = NULL;
    int stat = 0;

    /* get first child node */
    _child = xmlFirstElementChild(node);
    while(_child)
	{
	    if(strcmp((const char*) _child->name, ZPARSER_TEMPLATE_PATH) == 0)
		_template_path = (char*) xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_SAVE_PATH) == 0)
		_save_path = (char*) xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_SHEET_SIZE) == 0)
		_sheet_size = (char*) xmlNodeGetContent(_child);

	    _child = xmlNextElementSibling(_child);
	}

    /* if the paths were set we create the file object */
    stat = zfile_create_file_from_template(&parser->file, _template_path, _save_path);
    if(stat != ZELIA_OK)
	ZELIA_LOG_MESSAGE("errors occured while creating a new file");

    if(strcmp(_sheet_size, ZPARSER_SHEET_A4_PORT) == 0)
	_sheet_type = zSheetA4_Portrait;
    else if(strcmp(_sheet_size, ZPARSER_SHEET_A4_LAND) == 0)
	_sheet_type = zSheetA4_Landscape;
    else if(strcmp(_sheet_size, ZPARSER_SHEET_A3_PORT) == 0)
	_sheet_type = zSheetA3_Portrait;
    else
	_sheet_type = zSheetA3_Landscape;

    zdevice_new2(_sheet_type, 0, &parser->device);

    /* free memory */
    free(_template_path);
    free(_save_path);
    free(_sheet_size);
    return ZELIA_OK;
}
예제 #17
0
파일: fault.c 프로젝트: nelsonc/eucalyptus
/*
 * Returns true (1) if common block exists in doc, false (0) if not.
 */
static xmlNode *
get_common_block (const xmlDoc *doc)
{
    if (doc == NULL) {
        return NULL;
    }
    for (xmlNode *node =
             xmlFirstElementChild (xmlDocGetRootElement ((xmlDoc *)doc));
         node; node = node->next) {

        if (node->type == XML_ELEMENT_NODE) {
            if (!strcasecmp ((const char *)node->name, COMMON_PREFIX)) {
                logprintfl (EUCATRACE, "Found <%s> block.\n", COMMON_PREFIX);
                return node;
            }
        }
    }
    return NULL;
}
예제 #18
0
char *filter(char *str, Regexfilter *filterList) 
{
	
	xmlDocPtr doc;
	xmlNodePtr item_node, title_node;
	xmlChar *xmlbuff, *title_content;
	int buffersize;
	
	doc = xmlReadMemory(str, strlen(str), "noname.xml", NULL, 0);
	
	if (doc == NULL) {
		fprintf(stderr, "Failed to parse document\n");
		return;
	}
	
	item_node = feed_first_item(doc);
	
	/* loop through items */
	while (item_node != NULL) {
		
		title_node = xmlFirstElementChild(item_node); 
		title_content = xmlNodeGetContent(title_node);

		if (!pattern_check((char *)title_content, filterList)) {
			/* remove <item> node and leftover space*/
			feed_remove_node(&item_node);
			feed_remove_node(&item_node);
		}
		
		item_node = xmlNextElementSibling(item_node);
	}

	
	/* 
	 * Convert rss doc to string 
	 * and return.
	 */
	xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize,1);
	
	xmlFreeDoc(doc);
	
	return xmlbuff;
}
예제 #19
0
파일: helper.c 프로젝트: afeld/tangle
void removeDefaultNamespace(xmlNs *ns, xmlNode *node) {
    removeNamespace(&node->nsDef, ns);

    xmlAttr *attr;

    for (attr = node->properties; attr; attr = attr->next) {
        if (!attr->ns)
            continue;

        removeNamespace(&attr->ns, ns);
    }

    if (node->ns == ns)
        node->ns = NULL;

    xmlNode *child;

    for (child = xmlFirstElementChild(node); child; child = xmlNextElementSibling(child)) {
        removeDefaultNamespace(ns, child);
    }
}
예제 #20
0
파일: fault.c 프로젝트: nelsonc/eucalyptus
/*
 * Returns fault node if fault id exists in registry, NULL if not.
 *
 * Uses global fault registry unless a non-NULL doc pointer is passed as a
 * parameter, so it can be used either to match a fault id in a single
 * doc or to determine if a fault id already exists in the overall
 * registry.
 *
 * If NULL id supplied, simply returns the first fault node in document.
 */
static xmlNode *
get_eucafault (const char *id, const xmlDoc *doc)
{
    /*
     * Uses global registry if no doc supplied.
     */
    if (doc == NULL) {
        doc = ef_doc;
    }
    for (xmlNode *node =
             xmlFirstElementChild (xmlDocGetRootElement ((xmlDoc *)doc));
         node; node = node->next) {

        char *this_id = get_fault_id (node);

        if (id == NULL) {
            return node;
        } else if ((this_id != NULL) && !strcasecmp (this_id, id)) {
            return node;
        }
    }
    return NULL;
}
예제 #21
0
static gint
parse_track_list_data(GString *data, GList **list)
{
	gint result = 1;
	xmlDocPtr doc = NULL;

	doc = xmlReadMemory(data->str, data->len, NULL, NULL,
				XML_PARSE_RECOVER | XML_PARSE_NOERROR);

	if (doc == NULL)
		return result;

	do
	{
		xmlNodePtr root;
		xmlNodePtr track_list;
		xmlNodePtr p;

		root = xmlDocGetRootElement(doc);
		if (root == NULL)
			break;

		track_list = xml_first_child(root, BAD_CAST "trackList");
		if (track_list == NULL)
			break;

		for(p = xmlFirstElementChild(track_list); p ; p = xmlNextElementSibling(p))
			get_track(p, list);

		result = 0;
	}
	while(0);

	xmlFreeDoc(doc);

	return result;
}
예제 #22
0
/*
 * Construct an iCalendar component from an xCal string.
 */
icalcomponent *xcal_string_as_icalcomponent(const char *str)
{
    xmlParserCtxtPtr ctxt;
    xmlDocPtr doc = NULL;
    xmlNodePtr root;
    icalcomponent *ical = NULL;

    if (!str) return NULL;

    /* Parse the XML request */
    ctxt = xmlNewParserCtxt();
    if (ctxt) {
        doc = xmlCtxtReadMemory(ctxt, str, strlen(str), NULL, NULL,
                                XML_PARSE_NOWARNING);
        xmlFreeParserCtxt(ctxt);
    }
    if (!doc) {
        syslog(LOG_WARNING, "XML parse error");
        return NULL;
    }

    /* Get root element */
    if (!(root = xmlDocGetRootElement(doc)) ||
            xmlStrcmp(root->name, BAD_CAST "icalendar") ||
            xmlStrcmp(root->ns->href, BAD_CAST XML_NS_ICALENDAR)) {
        syslog(LOG_WARNING,
               "XML root element is not %s:icalendar", XML_NS_ICALENDAR);
        goto done;
    }

    ical = xml_element_to_icalcomponent(xmlFirstElementChild(root));

done:
    xmlFreeDoc(doc);

    return ical;
}
예제 #23
0
template <typename Traits> inline shared_ptr<typename detector_impl<Traits>::branch_type>
detector_impl<Traits>::parse_branch(xmlNodePtr node) const {
	
	shared_ptr<branch_type> result(new branch_type());
	for (xmlNodePtr n = xmlFirstElementChild(node); 0 != n; n = xmlNextElementSibling(n)) {
		if (disabled(n)) {
			continue;
		}
		else if (xmlStrncasecmp(n->name, (xmlChar const*) "match", sizeof("match")) == 0) {
			xml_elems elems(n, "pattern");
			for (xml_elems::iterator i = elems.begin(), end = elems.end(); i != end; ++i) {
				if (disabled(*i)) {
					continue;
				}
				char const *type = xml_attr_text(*i, "type");
				if (strncasecmp(type, "string", sizeof("string")) == 0) {
					result->add_match(xml_node_text(*i));
				}
				else if (strncasecmp(type, "regex", sizeof("regex")) == 0) {
					result->add_regex_match(xml_node_text(*i));
				}
				else {
					resource<xmlChar*, xml_string_traits> path(xmlGetNodePath(*i));
					throw error("unknown pattern type %s in [%s]", type, (char const*) path.get());
				}
			}
		}
		else if (xmlStrncasecmp(n->name, (xmlChar const*) "branch", sizeof("branch")) == 0) {
			result->add_child(parse_branch(n));
		}
		else if (xmlStrncasecmp(n->name, (xmlChar const*) "define", sizeof("definition")) == 0) {
			result->add_definition(parse_definition(n));
		}
	}
	return result;
}
예제 #24
0
/* parse xml file and create objects */
void* zelia_xml_parse_file(const char* xml_path, void* parser)
{
    char* _buff = NULL;					/* buffer to hold the file contents */
    size_t _sz = 0;					/* buffer file size */

    xmlDocPtr _xml_doc = NULL;				/* xml document pointer */
    xmlNodePtr _root = NULL;
    struct _zparser* obj = NULL;
    
    /* check arguments */
    ZCHECK_OBJ_INT(xml_path);
    
    if(parser == NULL)
	{
	    ZCONSTRUCTOR(obj, struct _zparser);
	}
    else
	obj = (struct _zparser*) parser;

    /* read the file */
    if(_read_file(xml_path, &_buff, &_sz) != ZELIA_OK)
	return NULL;


    /* initialise object array */
    blist_new(&obj->object_array, _delete_helper);

    if(!zfile_new(&obj->file))
	return NULL;

    /* toggle the force overwrite mode */
    zfile_toggle_overwrite(&obj->file);

    /* parse the document */
    xmlInitParser();

    _xml_doc = xmlParseMemory(_buff, _sz);

    if(_xml_doc == NULL)
	{
	    ZELIA_LOG_MESSAGE("zelia_xml unable to parse the document");
	    goto clean_up;
	}

    _root = xmlDocGetRootElement(_xml_doc);

    _main_loop(xmlFirstElementChild(_root), obj);
    
    xmlFreeDoc(_xml_doc);
    xmlCleanupParser();

 clean_up:

    if(_buff != NULL && _sz > 0)
	free(_buff);
    _buff = NULL;
    _sz = 0;
    
    if(ZDESTRUCTOR_CHECK)
	{
	    _finalise_parser(obj);
	    free(obj);
	}
    else
	return obj;
    
    return NULL;
}
예제 #25
0
inline __attribute__ ((always_inline)) static int _create_jb_object_terminals_helper(xmlNodePtr node, zgeneric* object)
{
    xmlChar* _nums = NULL, *_widths = NULL, *_heights = NULL, *_links = NULL, *_enums = NULL;
    xmlChar* _annot = NULL;
    int _num = 0, _enum = 0;
    double _width = 0.0, _height = 0.0;

    xmlNodePtr _child = NULL;

    _child = xmlFirstElementChild(node);
    while(_child)
	{
	    if(strcmp((const char*) _child->name, ZPARSER_TERMINALS_NUM) == 0)
		_nums = xmlNodeGetContent(_child);
	    if(strcmp((const char*) _child->name, ZPARSER_ETERMINALS_NUM) == 0)
		_enums = xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_COLUMN_WIDTH_ATTRIB) == 0)
		_widths = xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_ROW_HEIGHT_ATTRIB) == 0)
		_heights = xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_TERMINALS_LINKS) == 0)
		_links = xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_TERMINAL_ANNOT) == 0)
		_annot = xmlNodeGetContent(_child);
	    
	    /* break from loop if we have obtained every thing */
	    if(_nums && _widths && _heights && _links)
		break;
    	    _child = xmlNextElementSibling(_child);
	}

    if(_nums)
	{
	    _num = atoi((const char*) _nums);
	    xmlFree(_nums);
	}

    if(_enums)
	{
	    _enum = atoi((const char*) _enums);
	    xmlFree(_enums);
	}

    if(_widths)
	{
	    _width = atof((const char*) _widths);
	    xmlFree(_widths);
	}

    if(_heights)
	{
	    _height = atof((const char*) _heights);
	    xmlFree(_heights);
	}

    /* check links pointer and add terminals */
    zjb_add_with_earth_terminals(Z_JB(object),
				 _num,
				 _enum,
				 _width,
				 _height,
				 _annot? (const char*) _annot : NULL,
				 _links? (const char*) _links : NULL);
    if(_links)
	xmlFree(_links);

    if(_annot)
	xmlFree(_annot);

    return ZELIA_OK;
}
예제 #26
0
inline __attribute__ ((always_inline)) static int _create_jb_object_gland_helper(xmlNodePtr node, zgeneric* object)
{
    xmlChar *_xs = NULL;
    xmlChar *_ys = NULL;
    xmlChar *_szs = NULL;
    xmlChar *_hexs = NULL;

    double _x = 0.0, _y = 0.0;
    zGlandSize _sz = zM16;
    int _hex = 0;
    xmlNodePtr _child = NULL;

    _child = xmlFirstElementChild(node);
    while(_child)
	{
	    if(strcmp((const char*) _child->name, ZPARSER_COORD_X) == 0)
		_xs = xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_COORD_Y) == 0)
		_ys = xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_SIZE) == 0)
		_szs = xmlNodeGetContent(_child);
	    else if(strcmp((const char*) _child->name, ZPARSER_HEX_FLG) == 0)
		_hexs = xmlNodeGetContent(_child);

	    /* break if all interested variables are set */
	    if(_xs && _ys && _szs && _hexs)
		break;

    	    _child = xmlNextElementSibling(_child);
	}


    if(_xs)
	{
	    _x = atof((const char*) _xs);
	    xmlFree(_xs);
	}

    if(_ys)
	{
	    _y = atof((const char*) _ys);
	    xmlFree(_ys);
	}

    if(_szs)
	{
	    if(strcmp((const char*) _szs, ZPARSER_GLAND_SZ_M16) == 0)
		_sz = zM16;
	    else if(strcmp((const char*) _szs, ZPARSER_GLAND_SZ_M20) == 0)
		_sz = zM20;
	    else
		_sz = zM25;

	    xmlFree(_szs);
	}

    if(_hexs)
	{
	    _hex = atoi((const char*) _hexs);
	    xmlFree(_hexs);
	}

    /* add glands */
    zjb_add_glands(Z_JB(object), _x, _y, _sz, _hex);

    return ZELIA_OK;
}
예제 #27
0
/*
 * Construct an iCalendar component from a XML element.
 */
static icalcomponent *xml_element_to_icalcomponent(xmlNodePtr xcomp)
{
    icalcomponent_kind kind;
    icalcomponent *comp = NULL;
    xmlNodePtr node, xprop, xsub;

    if (!xcomp) return NULL;

    /* Get component type */
    kind =
        icalenum_string_to_component_kind(
            ucase(icalmemory_tmp_copy((const char *) xcomp->name)));
    if (kind == ICAL_NO_COMPONENT) {
        syslog(LOG_WARNING, "Unknown xCal component type: %s", xcomp->name);
        return NULL;
    }

    /* Create new component */
    comp = icalcomponent_new(kind);
    if (!comp) {
        syslog(LOG_ERR, "Creation of new %s component failed", xcomp->name);
        return NULL;
    }

    /* Add properties */
    node = xmlFirstElementChild(xcomp);
    if (!node || xmlStrcmp(node->name, BAD_CAST "properties")) {
        syslog(LOG_WARNING,
               "Expected <properties> XML element, received %s", node->name);
        goto error;
    }
    for (xprop = xmlFirstElementChild(node); xprop;
            xprop = xmlNextElementSibling(xprop)) {
        icalproperty *prop = xml_element_to_icalproperty(xprop);

        if (!prop) goto error;

        icalcomponent_add_property(comp, prop);
    }

    /* Add sub-components */
    if (!(node = xmlNextElementSibling(node))) return comp;

    if (xmlStrcmp(node->name, BAD_CAST "components")) {
        syslog(LOG_WARNING,
               "Expected <components> XML element, received %s", node->name);
        goto error;
    }

    for (xsub = xmlFirstElementChild(node); xsub;
            xsub = xmlNextElementSibling(xsub)) {
        icalcomponent *sub = xml_element_to_icalcomponent(xsub);

        if (!sub) goto error;

        icalcomponent_add_component(comp, sub);
    }

    /* Sanity check */
    if ((node = xmlNextElementSibling(node))) {
        syslog(LOG_WARNING,
               "Unexpected XML element in component: %s", node->name);
        goto error;
    }

    return comp;

error:
    icalcomponent_free(comp);
    return NULL;
}
예제 #28
0
/*
 * Construct an iCalendar property from a XML element.
 */
static icalproperty *xml_element_to_icalproperty(xmlNodePtr xprop)
{
    const char *propname, *typestr;
    icalproperty_kind kind;
    icalproperty *prop = NULL;
    icalvalue_kind valkind;
    icalvalue *value;
    xmlNodePtr node;

    /* Get the property type */
    propname = ucase(icalmemory_tmp_copy((const char *) xprop->name));
    kind = icalenum_string_to_property_kind(propname);
    if (kind == ICAL_NO_PROPERTY) {
        syslog(LOG_WARNING, "Unknown xCal property type: %s", propname);
        return NULL;
    }

    /* Create new property */
    prop = icalproperty_new(kind);
    if (!prop) {
        syslog(LOG_ERR, "Creation of new %s property failed", propname);
        return NULL;
    }
    if (kind == ICAL_X_PROPERTY) icalproperty_set_x_name(prop, propname);


    /* Add parameters */
    node = xmlFirstElementChild(xprop);
    if (node && !xmlStrcmp(node->name, BAD_CAST "parameters")) {
        xmlNodePtr xparam;

        for (xparam = xmlFirstElementChild(node); xparam;
                xparam = xmlNextElementSibling(xparam)) {
            char *paramname =
                ucase(icalmemory_tmp_copy((const char *) xparam->name));
            xmlChar *paramval = xmlNodeGetContent(xmlFirstElementChild(xparam));

            /* XXX  Need to handle multi-valued parameters */
            icalproperty_set_parameter_from_string(prop, paramname,
                                                   (const char *) paramval);

            xmlFree(paramval);
        }

        node = xmlNextElementSibling(node);
    }

    /* Get the value type */
    if (!node) {
        syslog(LOG_WARNING, "Missing xCal value for %s property",
               propname);
        return NULL;
    }
    typestr = ucase(icalmemory_tmp_copy((const char *) node->name));
    valkind = !strcmp(typestr, "UNKNOWN") ? ICAL_X_VALUE :
              icalenum_string_to_value_kind(typestr);
    if (valkind == ICAL_NO_VALUE) {
        syslog(LOG_WARNING, "Unknown xCal value type for %s property: %s",
               propname, typestr);
        return NULL;
    }
    else if (valkind == ICAL_TEXT_VALUE) {
        /* "text" also includes enumerated types - grab type from property */
        valkind = icalproperty_kind_to_value_kind(kind);
    }


    /* Add value */
    switch (kind) {
    case ICAL_CATEGORIES_PROPERTY:
    case ICAL_RESOURCES_PROPERTY:
    case ICAL_POLLPROPERTIES_PROPERTY:
        if (valkind == ICAL_TEXT_VALUE) {
            /* Handle multi-valued properties */
            struct buf buf = BUF_INITIALIZER;
            xmlChar *content = NULL;

            content = xmlNodeGetContent(node);
            buf_setcstr(&buf, (const char *) content);
            free(content);

            while ((node = xmlNextElementSibling(node))) {
                buf_putc(&buf, ',');
                content = xmlNodeGetContent(node);
                buf_appendcstr(&buf, (const char *) content);
                free(content);
            }

            value = icalvalue_new_from_string(valkind, buf_cstring(&buf));
            buf_free(&buf);
            break;
        }

    default:
        value = xml_element_to_icalvalue(node, valkind);
        if (!value) {
            syslog(LOG_ERR, "Parsing %s property value failed", propname);
            goto error;
        }
    }

    icalproperty_set_value(prop, value);


    /* Sanity check */
    if ((node = xmlNextElementSibling(node))) {
        syslog(LOG_WARNING,
               "Unexpected XML element in property: %s", node->name);
        goto error;
    }

    return prop;

error:
    icalproperty_free(prop);
    return NULL;
}
예제 #29
0
/*
 * Construct an iCalendar property value from XML content.
 */
static icalvalue *xml_element_to_icalvalue(xmlNodePtr xtype,
        icalvalue_kind kind)
{
    icalvalue *value = NULL;
    xmlNodePtr node;
    xmlChar *content = NULL;

    switch (kind) {

    case ICAL_GEO_VALUE: {
        struct icalgeotype geo;

        node = xmlFirstElementChild(xtype);
        if (!node) {
            syslog(LOG_WARNING, "Missing <latitude> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "latitude")) {
            syslog(LOG_WARNING,
                   "Expected <latitude> XML element, received %s", node->name);
            break;
        }

        content = xmlNodeGetContent(node);
        geo.lat = atof((const char *) content);

        node = xmlNextElementSibling(node);
        if (!node) {
            syslog(LOG_WARNING, "Missing <longitude> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "longitude")) {
            syslog(LOG_WARNING,
                   "Expected <longitude> XML element, received %s", node->name);
            break;
        }

        xmlFree(content);
        content = xmlNodeGetContent(node);
        geo.lon = atof((const char *) content);

        value = icalvalue_new_geo(geo);

        break;
    }

    case ICAL_PERIOD_VALUE: {
        struct icalperiodtype p;

        p.start = p.end = icaltime_null_time();
        p.duration = icaldurationtype_from_int(0);

        node = xmlFirstElementChild(xtype);
        if (!node) {
            syslog(LOG_WARNING, "Missing <start> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "start")) {
            syslog(LOG_WARNING,
                   "Expected <start> XML element, received %s", node->name);
            break;
        }

        content = xmlNodeGetContent(node);
        p.start = icaltime_from_string((const char *) content);
        if (icaltime_is_null_time(p.start)) break;

        node = xmlNextElementSibling(node);
        if (!node) {
            syslog(LOG_WARNING, "Missing <end> / <duration> XML element");
            break;
        }
        else if (!xmlStrcmp(node->name, BAD_CAST "end")) {
            xmlFree(content);
            content = xmlNodeGetContent(node);
            p.end = icaltime_from_string((const char *) content);
            if (icaltime_is_null_time(p.end)) break;
        }
        else if (!xmlStrcmp(node->name, BAD_CAST "duration")) {
            xmlFree(content);
            content = xmlNodeGetContent(node);
            p.duration = icaldurationtype_from_string((const char *) content);
            if (icaldurationtype_as_int(p.duration) == 0) break;
        }
        else {
            syslog(LOG_WARNING,
                   "Expected <end> / <duration> XML element, received %s",
                   node->name);
            break;
        }

        value = icalvalue_new_period(p);

        break;
    }

    case ICAL_RECUR_VALUE: {
        struct buf rrule = BUF_INITIALIZER;
        struct hash_table byrules;
        struct icalrecurrencetype rt;
        char *sep = "";

        construct_hash_table(&byrules, 10, 1);

        /* create an iCal RRULE string from xCal <recur> sub-elements */
        for (node = xmlFirstElementChild(xtype); node;
                node = xmlNextElementSibling(node)) {

            content = xmlNodeGetContent(node);
            if (!xmlStrncmp(node->name, BAD_CAST "by", 2)) {
                /* BY* rules can have a list of values -
                   assemble them using a hash table */
                struct buf *vals =
                    hash_lookup((const char *) node->name, &byrules);

                if (vals) {
                    /* append this value to existing list */
                    buf_printf(vals, ",%s", (char *) content);
                }
                else {
                    /* create new list with this valiue */
                    vals = xzmalloc(sizeof(struct buf));
                    buf_setcstr(vals, (char *) content);
                    hash_insert((char *) node->name, vals, &byrules);
                }
            }
            else {
                /* single value rpart */
                buf_printf(&rrule, "%s%s=%s", sep,
                           ucase((char *) node->name), (char *) content);
                sep = ";";
            }

            xmlFree(content);
            content = NULL;
        }

        /* append the BY* rules to RRULE buffer */
        hash_enumerate(&byrules,
                       (void (*)(const char*, void*, void*)) &append_byrule,
                       &rrule);
        free_hash_table(&byrules, NULL);

        /* parse our iCal RRULE string */
        rt = icalrecurrencetype_from_string(buf_cstring(&rrule));
        buf_free(&rrule);

        if (rt.freq != ICAL_NO_RECURRENCE) value = icalvalue_new_recur(rt);

        break;
    }

    case ICAL_REQUESTSTATUS_VALUE: {
        struct icalreqstattype rst = { ICAL_UNKNOWN_STATUS, NULL, NULL };
        short maj, min;

        node = xmlFirstElementChild(xtype);
        if (!node) {
            syslog(LOG_WARNING, "Missing <code> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "code")) {
            syslog(LOG_WARNING,
                   "Expected <code> XML element, received %s", node->name);
            break;
        }

        content = xmlNodeGetContent(node);
        if (sscanf((const char *) content, "%hd.%hd", &maj, &min) == 2) {
            rst.code = icalenum_num_to_reqstat(maj, min);
        }
        if (rst.code == ICAL_UNKNOWN_STATUS) {
            syslog(LOG_WARNING, "Unknown request-status code");
            break;
        }

        node = xmlNextElementSibling(node);
        if (!node) {
            syslog(LOG_WARNING, "Missing <description> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "description")) {
            syslog(LOG_WARNING,
                   "Expected <description> XML element, received %s",
                   node->name);
            break;
        }

        xmlFree(content);
        content = xmlNodeGetContent(node);
        rst.desc = (const char *) content;

        node = xmlNextElementSibling(node);
        if (node) {
            if (xmlStrcmp(node->name, BAD_CAST "data")) {
                syslog(LOG_WARNING,
                       "Expected <data> XML element, received %s", node->name);
                break;
            }

            xmlFree(content);
            content = xmlNodeGetContent(node);
            rst.debug = (const char *) content;
        }

        value = icalvalue_new_requeststatus(rst);
        break;
    }

    case ICAL_UTCOFFSET_VALUE: {
        int n, utcoffset, hours, minutes, seconds = 0;
        char sign;

        content = xmlNodeGetContent(xtype);
        n = sscanf((const char *) content, "%c%02d:%02d:%02d",
                   &sign, &hours, &minutes, &seconds);

        if (n < 3) {
            syslog(LOG_WARNING, "Unexpected utc-offset format");
            break;
        }

        utcoffset = hours*3600 + minutes*60 + seconds;

        if (sign == '-') utcoffset = -utcoffset;

        value = icalvalue_new_utcoffset(utcoffset);
        break;
    }

    default:
        content = xmlNodeGetContent(xtype);
        value = icalvalue_new_from_string(kind, (const char *) content);
        break;
    }

    if (content) xmlFree(content);

    return value;
}
예제 #30
0
int main(int argc, char **argv)
{
    int opt, r = 0;
    char *alt_config = NULL, *pub = NULL, *ver = NULL, *winfile = NULL;
    char prefix[2048];
    enum { REBUILD, WINZONES, NONE } op = NONE;

    if ((geteuid()) == 0 && (become_cyrus(/*ismaster*/0) != 0)) {
	fatal("must run as the Cyrus user", EC_USAGE);
    }

    while ((opt = getopt(argc, argv, "C:r:vw:")) != EOF) {
	switch (opt) {
	case 'C': /* alt config file */
	    alt_config = optarg;
	    break;

	case 'r':
	    if (op == NONE) {
		op = REBUILD;
		pub = optarg;
		ver = strchr(optarg, ':');
		if (ver) *ver++ = '\0';
		else usage();
	    }
	    else usage();
	    break;

	case 'v':
	    verbose = 1;
	    break;

	case 'w':
	    if (op == NONE) {
		op = WINZONES;
		winfile = optarg;
	    }
	    else usage();
	    break;

	default:
	    usage();
	}
    }

    cyrus_init(alt_config, "ctl_zoneinfo", 0, 0);

    signals_set_shutdown(&shut_down);
    signals_add_handlers(0);

    snprintf(prefix, sizeof(prefix), "%s%s", config_dir, FNAME_ZONEINFODIR);

    switch (op) {
    case REBUILD: {
	struct hash_table tzentries;
	struct zoneinfo *info;
	struct txn *tid = NULL;
	char buf[1024];
	FILE *fp;

	construct_hash_table(&tzentries, 500, 1);

	/* Add INFO record (overall lastmod and TZ DB source version) */
	info = xzmalloc(sizeof(struct zoneinfo));
	info->type = ZI_INFO;
	appendstrlist(&info->data, pub);
	appendstrlist(&info->data, ver);
	hash_insert(INFO_TZID, info, &tzentries);

	/* Add LEAP record (last updated and hash) */
	snprintf(buf, sizeof(buf), "%s%s", prefix, FNAME_LEAPSECFILE);
	if (verbose) printf("Processing leap seconds file %s\n", buf);
	if (!(fp = fopen(buf, "r"))) {
	    fprintf(stderr, "Could not open leap seconds file %s\n", buf);
	}
	else {
	    struct zoneinfo *leap = xzmalloc(sizeof(struct zoneinfo));
	    leap->type = ZI_INFO;

	    while(fgets(buf, sizeof(buf), fp)) {
		if (buf[0] == '#') {
		    /* comment line */

		    if (buf[1] == '$') {
			/* last updated */
			unsigned long last;

			sscanf(buf+2, "\t%lu", &last);
			leap->dtstamp = last - NIST_EPOCH_OFFSET;
		    }
		    else if (buf[1] == 'h') {
			/* hash */
			char *p, *hash = buf+3 /* skip "#h\t" */;

			/* trim trailing whitespace */
			for (p = hash + strlen(hash); isspace(*--p); *p = '\0');
			appendstrlist(&leap->data, hash);
		    }
		}
	    }
	    fclose(fp);

	    hash_insert(LEAP_TZID, leap, &tzentries);
	    info->dtstamp = leap->dtstamp;
	}

	/* Add ZONE/LINK records */
	do_zonedir(prefix, &tzentries, info);

	zoneinfo_open(NULL);

	/* Store records */
	hash_enumerate(&tzentries, &store_zoneinfo, &tid);

	zoneinfo_close(tid);

	free_hash_table(&tzentries, &free_zoneinfo);
	break;
    }

    case WINZONES: {
	xmlParserCtxtPtr ctxt;
	xmlDocPtr doc;
	xmlNodePtr node;
	struct buf tzidbuf = BUF_INITIALIZER;
	struct buf aliasbuf = BUF_INITIALIZER;

	if (verbose) printf("Processing Windows Zone file %s\n", winfile);

	/* Parse the XML file */
	ctxt = xmlNewParserCtxt();
	if (!ctxt) {
	    fprintf(stderr, "Failed to create XML parser context\n");
	    break;
	}

	doc = xmlCtxtReadFile(ctxt, winfile, NULL, 0);
	xmlFreeParserCtxt(ctxt);
	if (!doc) {
	    fprintf(stderr, "Failed to parse XML document\n");
	    break;
	}

	node = xmlDocGetRootElement(doc);
	if (!node || xmlStrcmp(node->name, BAD_CAST "supplementalData")) {
	    fprintf(stderr, "Incorrect root node\n");
	    goto done;
	}

	for (node = xmlFirstElementChild(node);
	     node && xmlStrcmp(node->name, BAD_CAST "windowsZones");
	     node = xmlNextElementSibling(node));
	if (!node) {
	    fprintf(stderr, "Missing windowsZones node\n");
	    goto done;
	}

	node = xmlFirstElementChild(node);
	if (!node || xmlStrcmp(node->name, BAD_CAST "mapTimezones")) {
	    fprintf(stderr, "Missing mapTimezones node\n");
	    goto done;
	}

	if (chdir(prefix)) {
	    fprintf(stderr, "chdir(%s) failed\n", prefix);
	    goto done;
	}

	for (node = xmlFirstElementChild(node);
	     node;
	     node = xmlNextElementSibling(node)) {
	    if (!xmlStrcmp(node->name, BAD_CAST "mapZone") &&
		!xmlStrcmp(xmlGetProp(node, BAD_CAST "territory"),
			   BAD_CAST "001")) {
		const char *tzid, *alias;

		buf_setcstr(&tzidbuf,
			    (const char *) xmlGetProp(node, BAD_CAST "type"));
		buf_appendcstr(&tzidbuf, ".ics");
		tzid = buf_cstring(&tzidbuf);
		buf_setcstr(&aliasbuf,
			    (const char *) xmlGetProp(node, BAD_CAST "other"));
		buf_appendcstr(&aliasbuf, ".ics");
		alias = buf_cstring(&aliasbuf);

		if (verbose) printf("\tLINK: %s -> %s\n", alias, tzid);

		if (symlink(tzid, alias)) {
		    if (errno == EEXIST) {
			struct stat sbuf;

			if (stat(alias, &sbuf)) {
			    fprintf(stderr, "stat(%s) failed: %s\n",
				    alias, strerror(errno));
			    errno = EEXIST;
			}
			else if (sbuf.st_mode & S_IFLNK) {
			    char link[MAX_MAILBOX_PATH+1];
			    int n = readlink(alias, link, MAX_MAILBOX_PATH);

			    if (n == -1) {
				fprintf(stderr, "readlink(%s) failed: %s\n",
					alias, strerror(errno));
				errno = EEXIST;
			    }
			    else if (n == (int) strlen(tzid) &&
				     !strncmp(tzid, link, n)) {
				errno = 0;
			    }
			}
		    }

		    if (errno) {
			fprintf(stderr, "symlink(%s, %s) failed: %s\n",
				tzid, alias, strerror(errno));
		    }
		}
	    }
	}

  done:
	buf_free(&aliasbuf);
	buf_free(&tzidbuf);
	xmlFreeDoc(doc);
	break;
    }

    case NONE:
	r = 2;
	usage();
	break;
    }

    cyrus_done();

    return r;
}