Beispiel #1
0
static void
propopen(void *dat, const XML_Char *s, const XML_Char **atts)
{
	struct parse	*p = dat;
	enum calelem	 elem;

	if (CALELEM__MAX == (elem = calelem_find(s))) 
		kdbg("Unknown property: %s", s);
	else
		kdbg("Known property: %s", s);

	switch (elem) {
	case (CALELEM__MAX):
		propadd(p, s, PROP__MAX, NULL);
		break;
	default:
		if (PROP__MAX == calprops[elem]) {
			propadd(p, s, PROP__MAX, NULL);
			break;
		}
		p->buf.sz = 0;
		XML_SetDefaultHandler(p->xp, parsebuffer);
		break;
	}
}
Beispiel #2
0
END_TEST

/* Regression test for SF bug #483514. */
START_TEST(test_dtd_default_handling)
{
    char *text =
        "<!DOCTYPE doc [\n"
        "<!ENTITY e SYSTEM 'http://xml.libexpat.org/e'>\n"
        "<!NOTATION n SYSTEM 'http://xml.libexpat.org/n'>\n"
        "<!ELEMENT doc EMPTY>\n"
        "<!ATTLIST doc a CDATA #IMPLIED>\n"
        "<?pi in dtd?>\n"
        "<!--comment in dtd-->\n"
        "]><doc/>";

    XML_SetDefaultHandler(parser, accumulate_characters);
    XML_SetDoctypeDeclHandler(parser,
                              dummy_start_doctype_handler,
                              dummy_end_doctype_handler);
    XML_SetEntityDeclHandler(parser, dummy_entity_decl_handler);
    XML_SetNotationDeclHandler(parser, dummy_notation_decl_handler);
    XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
    XML_SetProcessingInstructionHandler(parser, dummy_pi_handler);
    XML_SetCommentHandler(parser, dummy_comment_handler);
    run_character_check(text, "\n\n\n\n\n\n\n<doc/>");
}
Beispiel #3
0
struct caldav *
caldav_parse(const char *buf, size_t sz)
{
	struct parse	 p;

	memset(&p, 0, sizeof(struct parse));

	if (NULL == (p.xp = XML_ParserCreateNS(NULL, ':'))) {
		kerr(NULL);
		return(NULL);
	}

	bufappend(&p.buf, " ", 1);

	XML_SetDefaultHandler(p.xp, NULL);
	XML_SetElementHandler(p.xp, parseopen, parseclose);
	XML_SetCdataSectionHandler(p.xp, cdata, cdata);
	XML_SetUserData(p.xp, &p);

	if (XML_STATUS_OK != XML_Parse(p.xp, buf, (int)sz, 1)) {
		caldav_free(p.p);
		p.p = NULL;
	}

	XML_ParserFree(p.xp);
	free(p.buf.buf);
	return(p.p);
}
Beispiel #4
0
static void
parseopen(void *dat, const XML_Char *s, const XML_Char **atts)
{
	struct parse	*p = dat;
	enum calelem	 elem;

	if (CALELEM__MAX != (elem = calelem_find(s)))
		kdbg("Known element: %s", s);
	else
		kdbg("Unknown element: %s", s);

	switch (elem) {
	case (CALELEM_CALENDAR_QUERY):
		caldav_alloc(p, TYPE_CALQUERY);
		break;
	case (CALELEM_CALENDAR_MULTIGET):
		caldav_alloc(p, TYPE_CALMULTIGET);
		break;
	case (CALELEM_PROPERTYUPDATE):
		caldav_alloc(p, TYPE_PROPERTYUPDATE);
		break;
	case (CALELEM_PROPFIND):
		caldav_alloc(p, TYPE_PROPFIND);
		break;
	case (CALELEM_HREF):
		p->buf.sz = 0;
		XML_SetDefaultHandler(p->xp, parsebuffer);
		break;
	case (CALELEM_PROP):
		XML_SetElementHandler(p->xp, propopen, propclose);
		break;
	default:
		break;
	}
}
Beispiel #5
0
void XMLParser::EnableDefaultHandler(bool enable, bool expand)
{
	assert(m_parser != NULL);
	if (expand)
		XML_SetDefaultHandlerExpand(m_parser, enable ? DefaultHandler : NULL);
	else
		XML_SetDefaultHandler(m_parser, enable ? DefaultHandler : NULL);
}
Beispiel #6
0
void XmlParser::EnableDefaultHandler ( bool _isEnable, bool _isExpand )
{
    ex_assert( m_pParser, "m_pParser is not create" );
    if ( _isExpand )
        XML_SetDefaultHandlerExpand( m_pParser, _isEnable ? DefaultHandler : NULL );
    else
        XML_SetDefaultHandler( m_pParser, _isEnable ? DefaultHandler : NULL );
}
Beispiel #7
0
TinyDomElement* TinyDom::parse(std::istream& istr) {

  XML_Parser parser = XML_ParserCreate(0);
  TinyDomParser tdparser;

  XML_SetUserData(parser, &tdparser);
  XML_SetCharacterDataHandler(parser, characterDataHandler);
  XML_SetElementHandler(parser, startElementHandler, endElementHandler);
  XML_SetCommentHandler(parser, commentHandler);
  XML_SetProcessingInstructionHandler(parser, processingInstructionHandler);
  XML_SetXmlDeclHandler(parser, xmlDeclHandler);
  XML_SetDefaultHandler(parser, defaultHandler);
  XML_SetDoctypeDeclHandler(parser, startDoctypeDeclHandler, endDoctypeDeclHandler);

  try {

    while (1) {
      void* buf = XML_GetBuffer(parser, 1024);
      if (!buf) {
	throw std::runtime_error("out of memory!");
      }
      istr.read((char*)buf, 1024);
	  std::streamsize len = istr.gcount();
      if (istr.fail() && !istr.eof()) {
	throw std::runtime_error("failed IO");
      }
      bool isFinal = (istr.eof() || len < 1024);
      if (! XML_ParseBuffer(parser, len, isFinal)) {
	std::ostringstream ostr;
	ostr << "parse error at line " << XML_GetErrorLineNumber(parser)
	     << ", column " << XML_GetErrorColumnNumber(parser) << ": "
	     << XML_ErrorString(XML_GetErrorCode(parser));
	throw std::runtime_error(ostr.str());
				 
      }
      if (isFinal) {
	break;
      }
    }
	
    XML_ParserFree(parser);
	
  } catch (...) {

    //std::cerr << "Got exception: " << e.what() << "\n";

    if (parser) { XML_ParserFree(parser); }
    delete tdparser.rootElement;
    throw;

  }

  return tdparser.rootElement;

}
Beispiel #8
0
PRIVATE void HTXML_setHandlers (XML_Parser me)
{
    XML_SetElementHandler(me, XML_startElement, XML_endElement);
    XML_SetCharacterDataHandler(me, XML_characterData);
    XML_SetProcessingInstructionHandler(me, XML_processingInstruction);
    XML_SetDefaultHandler(me, XML_default);
    XML_SetUnparsedEntityDeclHandler(me, XML_unparsedEntityDecl);
    XML_SetNotationDeclHandler(me, XML_notationDecl);
    XML_SetExternalEntityRefHandler(me, XML_externalEntityRef);
    XML_SetUnknownEncodingHandler(me, XML_unknownEncoding, NULL);
}
Beispiel #9
0
static void init_parser(XML_Parser parser, expat_parser *parser_data)
{
    XML_SetUserData(parser, parser_data);

    XML_SetStartElementHandler(parser, (XML_StartElementHandler)start_element_handler);
    XML_SetEndElementHandler(parser, (XML_EndElementHandler)end_element_handler);
    XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)character_data_handler);
    XML_SetStartNamespaceDeclHandler(parser, (XML_StartNamespaceDeclHandler)namespace_decl_handler);

    XML_SetReturnNSTriplet(parser, 1);
    XML_SetDefaultHandler(parser, NULL);
};
void ParserEngine::init()
{
	if (_parser)
		XML_ParserFree(_parser);

	if (!_pBuffer)
		_pBuffer  = new char[PARSE_BUFFER_SIZE];

	if (dynamic_cast<NoNamespacePrefixesStrategy*>(_pNamespaceStrategy))
	{
		_parser = XML_ParserCreateNS(_encodingSpecified ? _encoding.c_str() : 0, '\t');
		if (_parser)
		{
			XML_SetNamespaceDeclHandler(_parser, handleStartNamespaceDecl, handleEndNamespaceDecl);
		}
	}
	else if (dynamic_cast<NamespacePrefixesStrategy*>(_pNamespaceStrategy))
	{
		_parser = XML_ParserCreateNS(_encodingSpecified ? _encoding.c_str() : 0, '\t');
		if (_parser)
		{
			XML_SetReturnNSTriplet(_parser, 1);
			XML_SetNamespaceDeclHandler(_parser, handleStartNamespaceDecl, handleEndNamespaceDecl);
		}
	}
	else
	{
		_parser = XML_ParserCreate(_encodingSpecified ? _encoding.c_str() : 0);
	}

	if (!_parser) throw XMLException("Cannot create Expat parser");

	XML_SetUserData(_parser, this);
	XML_SetElementHandler(_parser, handleStartElement, handleEndElement);
	XML_SetCharacterDataHandler(_parser, handleCharacterData);
	XML_SetProcessingInstructionHandler(_parser, handleProcessingInstruction);
	if (_expandInternalEntities)
		XML_SetDefaultHandlerExpand(_parser, handleDefault);
	else
		XML_SetDefaultHandler(_parser, handleDefault);
	XML_SetUnparsedEntityDeclHandler(_parser, handleUnparsedEntityDecl);
	XML_SetNotationDeclHandler(_parser, handleNotationDecl);
	XML_SetExternalEntityRefHandler(_parser, handleExternalEntityRef);
	XML_SetCommentHandler(_parser, handleComment);
	XML_SetCdataSectionHandler(_parser, handleStartCdataSection, handleEndCdataSection);
	XML_SetDoctypeDeclHandler(_parser, handleStartDoctypeDecl, handleEndDoctypeDecl);
	XML_SetEntityDeclHandler(_parser, handleEntityDecl);
	XML_SetSkippedEntityHandler(_parser, handleSkippedEntity);
	XML_SetParamEntityParsing(_parser, _externalParameterEntities ? XML_PARAM_ENTITY_PARSING_ALWAYS : XML_PARAM_ENTITY_PARSING_NEVER);
	XML_SetUnknownEncodingHandler(_parser, handleUnknownEncoding, this);
}
Beispiel #11
0
bool_t reset_handlers_parser(parser_t *parser) {
  if( parser ) {
    XML_SetStartElementHandler(parser->p, parser->callbacks.start_tag ?
			       xml_startelementhandler : NULL);
    XML_SetEndElementHandler(parser->p, parser->callbacks.end_tag ?
			     xml_endelementhandler : NULL);
    XML_SetCommentHandler(parser->p, parser->callbacks.comment ?
			  xml_commenthandler : NULL);
    XML_SetCharacterDataHandler(parser->p, parser->callbacks.chardata ?
				xml_characterdatahandler : NULL);
    XML_SetProcessingInstructionHandler(parser->p, parser->callbacks.pidata ?
					xml_processinginstructionhandler : NULL);
    XML_SetStartCdataSectionHandler(parser->p, parser->callbacks.start_cdata ?
				    xml_startcdatahandler : NULL);
    /* if start_cdata, always set endcdatahandler */
    XML_SetEndCdataSectionHandler(parser->p, parser->callbacks.start_cdata ?
				  xml_endcdatahandler : NULL);
    XML_SetDefaultHandler(parser->p, parser->callbacks.dfault ?
    			  xml_defaulthandler : NULL);


    XML_SetStartDoctypeDeclHandler(parser->p, parser->callbacks.start_doctypedecl ?
				   xml_startdoctypedeclhandler : NULL);
    /* if start_doctypedecl, always set enddoctypedeclhandler */
    XML_SetEndDoctypeDeclHandler(parser->p, parser->callbacks.start_doctypedecl ?
				 xml_enddoctypedeclhandler : NULL);
    XML_SetEntityDeclHandler(parser->p, parser->callbacks.entitydecl ?
			     xml_entitydeclhandler : NULL);

    /* what to do about entities: there can be internal and external
     * entities, which expat treats differently. We want all our
     * entities to stay unprocessed, otherwise we'll get well formedness
     * errors. When a handler is called, the raw string is passed to
     * the default handler (provided it exists). */
    XML_UseForeignDTD(parser->p, XML_TRUE);
    XML_SetParamEntityParsing(parser->p, XML_PARAM_ENTITY_PARSING_NEVER);
    XML_SetExternalEntityRefHandler(parser->p,
				    xml_externalentityrefhandler);
    XML_SetExternalEntityRefHandlerArg(parser->p, parser);
    XML_SetSkippedEntityHandler(parser->p, xml_skippedentityhandler);


    return TRUE;
  }
  return FALSE;
}
Beispiel #12
0
static int lxp_make_parser (lua_State *L) {
  XML_Parser p;
  int bufferCharData = (lua_type(L, 3) != LUA_TBOOLEAN) || (lua_toboolean(L, 3) != 0);
  char sep = *luaL_optstring(L, 2, "");
  lxp_userdata *xpu = createlxp(L);
  xpu->bufferCharData = bufferCharData;
  p = xpu->parser = (sep == '\0') ? XML_ParserCreate(NULL) :
                                    XML_ParserCreateNS(NULL, sep);
  if (!p)
    luaL_error(L, "XML_ParserCreate failed");
  luaL_checktype(L, 1, LUA_TTABLE);
  checkcallbacks(L);
  lua_pushvalue(L, 1);
  xpu->tableref = luaL_ref(L, LUA_REGISTRYINDEX);
  XML_SetUserData(p, xpu);
  if (hasfield(L, StartCdataKey) || hasfield(L, EndCdataKey))
    XML_SetCdataSectionHandler(p, f_StartCdata, f_EndCdataKey);
  if (hasfield(L, CharDataKey))
    XML_SetCharacterDataHandler(p, f_CharData);
  if (hasfield(L, CommentKey))
    XML_SetCommentHandler(p, f_Comment);
  if (hasfield(L, DefaultKey))
    XML_SetDefaultHandler(p, f_Default);
  if (hasfield(L, DefaultExpandKey))
    XML_SetDefaultHandlerExpand(p, f_DefaultExpand);
  if (hasfield(L, StartElementKey) || hasfield(L, EndElementKey))
    XML_SetElementHandler(p, f_StartElement, f_EndElement);
  if (hasfield(L, ExternalEntityKey))
    XML_SetExternalEntityRefHandler(p, f_ExternaEntity);
  if (hasfield(L, StartNamespaceDeclKey) || hasfield(L, EndNamespaceDeclKey))
    XML_SetNamespaceDeclHandler(p, f_StartNamespaceDecl, f_EndNamespaceDecl);
  if (hasfield(L, NotationDeclKey))
    XML_SetNotationDeclHandler(p, f_NotationDecl);
  if (hasfield(L, NotStandaloneKey))
    XML_SetNotStandaloneHandler(p, f_NotStandalone);
  if (hasfield(L, ProcessingInstructionKey))
    XML_SetProcessingInstructionHandler(p, f_ProcessingInstruction);
  if (hasfield(L, UnparsedEntityDeclKey))
    XML_SetUnparsedEntityDeclHandler(p, f_UnparsedEntityDecl);
  if (hasfield(L, StartDoctypeDeclKey))
    XML_SetStartDoctypeDeclHandler(p, f_StartDoctypeDecl);
  if (hasfield(L, XmlDeclKey))
    XML_SetXmlDeclHandler(p, f_XmlDecl);
  return 1;
}
Beispiel #13
0
nad_t nad_parse(const char *buf, int len) {
    struct build_data bd;
    XML_Parser p;

    if(len == 0)
        len = strlen(buf);

    p = XML_ParserCreateNS(NULL, '|');
    if(p == NULL)
        return NULL;
    bd.p = p;

    XML_SetReturnNSTriplet(p, 1);
    /* Prevent the "billion laughs" attack against expat by disabling
     * internal entity expansion.  With 2.x, forcibly stop the parser
     * if an entity is declared - this is safer and a more obvious
     * failure mode.  With older versions, simply prevent expenansion
     * of such entities. */
#ifdef HAVE_XML_STOPPARSER
    XML_SetEntityDeclHandler(p, (void *) _nad_parse_entity_declaration);
#else
    XML_SetDefaultHandler(p, NULL);
#endif

    bd.nad = nad_new();
    bd.depth = 0;

    XML_SetUserData(p, (void *) &bd);
    XML_SetElementHandler(p, _nad_parse_element_start, _nad_parse_element_end);
    XML_SetCharacterDataHandler(p, _nad_parse_cdata);
    XML_SetStartNamespaceDeclHandler(p, _nad_parse_namespace_start);

    if(!XML_Parse(p, buf, len, 1)) {
        XML_ParserFree(p);
        nad_free(bd.nad);
        return NULL;
    }

    XML_ParserFree(p);

    if(bd.depth != 0)
        return NULL;

    return bd.nad;
}
Beispiel #14
0
static void
init_parser(struct exmpp_xml_data *edd)
{

	/* Set Expat user data to be this structure. */
	XML_SetUserData(edd->parser, edd);

	/* Configure the parser. */
	XML_SetNamespaceDeclHandler(edd->parser,
	    expat_cb_start_namespace,
	    NULL);
	XML_SetElementHandler(edd->parser,
	    expat_cb_start_element,
	    expat_cb_end_element);
	XML_SetCharacterDataHandler(edd->parser,
	    expat_cb_character_data);
	XML_SetDefaultHandler(edd->parser, NULL);
}
Beispiel #15
0
APR_DECLARE(apr_xml_parser *) apr_xml_parser_create_ex(apr_pool_t *pool,
    void *start_func, void *end_func, void *cdata_func)
{
    apr_xml_parser *parser = apr_pcalloc(pool, sizeof(*parser));

    parser->impl = apr_xml_get_parser_impl();

    parser->p = pool;
    parser->doc = apr_pcalloc(pool, sizeof(*parser->doc));

    parser->doc->namespaces = apr_array_make(pool, 5, sizeof(const char *));

    /* ### is there a way to avoid hard-coding this? */
    apr_xml_insert_uri(parser->doc->namespaces, APR_KW_DAV);

    parser->xp = XML_ParserCreate(NULL);
    if (parser->xp == NULL) {
        (*apr_pool_abort_get(pool))(APR_ENOMEM);
        return NULL;
    }

    apr_pool_cleanup_register(pool, parser, cleanup_parser,
                              apr_pool_cleanup_null);

    XML_SetUserData(parser->xp, parser);
    XML_SetElementHandler(parser->xp, start_func, end_func);
    XML_SetCharacterDataHandler(parser->xp, cdata_func);

    /* Prevent the "billion laughs" attack against expat by disabling
     * internal entity expansion.  With 2.x, forcibly stop the parser
     * if an entity is declared - this is safer and a more obvious
     * failure mode.  With older versions, installing a noop
     * DefaultHandler means that internal entities will be expanded as
     * the empty string, which is also sufficient to prevent the
     * attack. */
#if XML_MAJOR_VERSION > 1
    XML_SetEntityDeclHandler(parser->xp, entity_declaration);
#else
    XML_SetDefaultHandler(parser->xp, default_handler);
#endif

    return parser;
}
Beispiel #16
0
static void
propclose(void *dat, const XML_Char *s)
{
	struct parse	*p = dat;
	enum calelem	 elem;

	switch ((elem = calelem_find(s))) {
	case (CALELEM__MAX):
		break;
	case (CALELEM_PROP):
		XML_SetElementHandler(p->xp, parseopen, parseclose);
		break;
	default:
		if (PROP__MAX == calprops[elem])
			break;
		propadd(p, s, calprops[elem], p->buf.buf);
		XML_SetDefaultHandler(p->xp, NULL);
		break;
	}
}
Beispiel #17
0
int64_t f_xml_parse_into_struct(CObjRef parser, CStrRef data, VRefParam values,
                            VRefParam index /* = null */) {
  int ret;
  XmlParser * p = parser.getTyped<XmlParser>();
  values = Array::Create();
  p->data.assignRef(values);
  index = Array::Create();
  p->info.assignRef(index);
  p->level = 0;
  p->ltags = (char**)malloc(XML_MAXLEVEL * sizeof(char*));

  XML_SetDefaultHandler(p->parser, _xml_defaultHandler);
  XML_SetElementHandler(p->parser, _xml_startElementHandler,
                        _xml_endElementHandler);
  XML_SetCharacterDataHandler(p->parser, _xml_characterDataHandler);

  p->isparsing = 1;
  ret = XML_Parse(p->parser, (const XML_Char*)data.data(), data.size(), 1);
  p->isparsing = 0;

  return ret;
}
Beispiel #18
0
static ErlDrvData expat_erl_start(ErlDrvPort port, char *buff)
{
   expat_data* d = (expat_data*)driver_alloc(sizeof(expat_data));
   d->port = port;
   d->parser = XML_ParserCreate_MM("UTF-8", &ms, "\n");
   XML_SetUserData(d->parser, d);

   set_port_control_flags(port, PORT_CONTROL_FLAG_BINARY);

   XML_SetStartElementHandler(
      d->parser, (XML_StartElementHandler)erlXML_StartElementHandler);
   XML_SetEndElementHandler(
      d->parser, (XML_EndElementHandler)erlXML_EndElementHandler);
   XML_SetCharacterDataHandler(
      d->parser, (XML_CharacterDataHandler)erlXML_CharacterDataHandler);

   XML_SetStartNamespaceDeclHandler(
      d->parser, (XML_StartNamespaceDeclHandler) erlXML_StartNamespaceDeclHandler);
   XML_SetReturnNSTriplet(d->parser, 1);

   XML_SetDefaultHandler(d->parser, NULL);

   return (ErlDrvData)d;
}
Beispiel #19
0
void bmx_expat_XML_SetDefaultHandler(XML_Parser parser) {
	XML_SetDefaultHandler(parser, bmx_expat_DefaultHandler);
}
Beispiel #20
0
bool wxXmlDocument::Load(wxInputStream& stream, const wxString& encoding, int flags)
{
#if wxUSE_UNICODE
    (void)encoding;
#else
    m_encoding = encoding;
#endif

    const size_t BUFSIZE = 1024;
    char buf[BUFSIZE];
    wxXmlParsingContext ctx;
    bool done;
    XML_Parser parser = XML_ParserCreate(NULL);

    ctx.root = ctx.node = NULL;
    ctx.encoding = wxT("UTF-8"); // default in absence of encoding=""
    ctx.conv = NULL;
#if !wxUSE_UNICODE
    if ( encoding.CmpNoCase(wxT("UTF-8")) != 0 )
        ctx.conv = new wxCSConv(encoding);
#endif
    ctx.removeWhiteOnlyNodes = (flags & wxXMLDOC_KEEP_WHITESPACE_NODES) == 0;

    XML_SetUserData(parser, (void*)&ctx);
    XML_SetElementHandler(parser, StartElementHnd, EndElementHnd);
    XML_SetCharacterDataHandler(parser, TextHnd);
    XML_SetStartCdataSectionHandler(parser, StartCdataHnd);
    XML_SetCommentHandler(parser, CommentHnd);
    XML_SetDefaultHandler(parser, DefaultHnd);
    XML_SetUnknownEncodingHandler(parser, UnknownEncodingHnd, NULL);

    bool ok = true;
    do
    {
        size_t len = stream.Read(buf, BUFSIZE).LastRead();
        done = (len < BUFSIZE);
        if (!XML_Parse(parser, buf, len, done))
        {
            wxString error(XML_ErrorString(XML_GetErrorCode(parser)),
                           *wxConvCurrent);
            wxLogError(_("XML parsing error: '%s' at line %d"),
                       error.c_str(),
                       XML_GetCurrentLineNumber(parser));
            ok = false;
            break;
        }
    } while (!done);

    if (ok)
    {
        if (!ctx.version.empty())
            SetVersion(ctx.version);
        if (!ctx.encoding.empty())
            SetFileEncoding(ctx.encoding);
        SetRoot(ctx.root);
    }
    else
    {
        delete ctx.root;
    }

    XML_ParserFree(parser);
#if !wxUSE_UNICODE
    if ( ctx.conv )
        delete ctx.conv;
#endif

    return ok;

}
Beispiel #21
0
bool f_xml_set_default_handler(CObjRef parser, CVarRef handler) {
  XmlParser * p = parser.getTyped<XmlParser>();
  xml_set_handler(&p->defaultHandler, handler);
  XML_SetDefaultHandler(p->parser, _xml_defaultHandler);
  return true;
}
Beispiel #22
0
struct xmlnode *
xmlloadfile(const char *file)
{
    char *buf;
    int fd, len;
    struct xmlnode *node;
    XML_Parser parser;

    if(file == NULL || file[0] == '\0')
        return NULL;

    /* read file content into buffer */
    fd = open(file, O_RDONLY);
    if(fd == -1)
        return NULL;
    len = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);
    buf = (char *) mmalloc(len + 1);
    if(buf == NULL) {
        close(fd);
        return NULL;
    }

    if(len != read(fd, buf, len)) {
        /* read error */
        free(buf);
        close(fd);
        return NULL;
    }
    buf[len] = '\0';
    close(fd);

    /* starting parsing */
    node = (struct xmlnode *) mcalloc(sizeof(struct xmlnode), 1);
    if(node == NULL) {
        free(buf);
        return NULL;
    }

    xml_depth = xml_error = 0;
    parent_depth = 1;
    max_parent_depth = 10;
    parser_parent =
        (struct xmlnode **) mcalloc(sizeof(struct xmlnode **),
                                    max_parent_depth);
    parser = XML_ParserCreate(NULL);
    if(parser == NULL || parser_parent == NULL) {
        if(parser)
            XML_ParserFree(parser);
        free(parser_parent);
        free(node);
        free(buf);
        return NULL;
    }

    parser_parent[0] = node;
    parser_node = NULL;
    XML_SetUserData(parser, NULL);
    XML_SetElementHandler(parser, startElement, endElement);
    XML_SetDefaultHandler(parser, setElement);
    if(XML_Parse(parser, buf, len, 1) == XML_STATUS_ERROR) {
        fprintf(stderr, "%s at line %u\n",
                XML_ErrorString(XML_GetErrorCode(parser)),
                (unsigned int) XML_GetCurrentLineNumber(parser));
        free(node);
        node = NULL;
    }

    XML_ParserFree(parser);

    free(buf);
    free(parser_parent);

    return node;
}
Beispiel #23
0
//
// rtv_get_device_info
// returns pointer to replaytv device.
//
int rtv_get_device_info(const char *address, char *queryStr, rtv_device_t **device_p)
{
    char               url[512];
    struct hc         *hc;
    int                rc, new_entry;
    rtv_device_t      *rtv;
    rtv_device_info_t *devinfo;

    RTV_DBGLOG(RTVLOG_DSCVR, "%s: Enter: address=%s: current_rtv_cnt=%d\n", __FUNCTION__, address, rtv_devices.num_rtvs);

    *device_p  = NULL;
    rtv     = rtv_get_device_struct(address, &new_entry);
    devinfo = &(rtv->device);

    if ( !(new_entry) ) {
        RTV_DBGLOG(RTVLOG_DSCVR, "%s: address=%s already exists in device struct. Decrement count.\n", __FUNCTION__, address);
        rtv_devices.num_rtvs--;
    }

    rtv_free_device_info(devinfo);
    devinfo->ipaddr = malloc(strlen(address) + 1);
    strcpy(devinfo->ipaddr, address);

    parser = XML_ParserCreate("US-ASCII");
    XML_SetElementHandler(parser, devinfo_xml_start, devinfo_xml_end);
    XML_SetCharacterDataHandler(parser, devinfo_xml_charhndlr);
    XML_SetDefaultHandler(parser, devinfo_default_handler);
    XML_SetUserData(parser, devinfo);

    if ( queryStr == NULL ) {
        sprintf(url, "http://%s/Device_Descr.xml", address);
        RTV_DBGLOG(RTVLOG_DSCVR, "%s: Build default query str: %s\n", __FUNCTION__, url);
    }
    else {
        strncpy(url, queryStr, 511);
        RTV_DBGLOG(RTVLOG_DSCVR, "%s: Use supplied query str: %s\n", __FUNCTION__, url);
    }

    hc = hc_start_request(url);
    if (!hc) {
        RTV_ERRLOG("%s: hc_start_request(): %d=>%s\n", __FUNCTION__, errno, strerror(errno));
        rtv_free_device_info(devinfo);
        return(-EPROTO);
    }

    hc_send_request(hc, NULL);
    rc = hc_read_pieces(hc, get_deviceinfo_callback, NULL, 0);
    hc_free(hc);
    if ( rc != 0 ) {
        RTV_ERRLOG("%s: hc_read_pieces call failed: rc=%d\n", __FUNCTION__, rc);
        rtv_free_device_info(devinfo);
        return(rc);
    }

    if ( (devinfo->status & RTV_EXPECTED_FIELDS) != RTV_EXPECTED_FIELDS ) {
        RTV_ERRLOG("%s: Missing XML Fields exp=%08X got=%08lX\n", __FUNCTION__, RTV_EXPECTED_FIELDS, devinfo->status);
        rtv_free_device_info(devinfo);
        return(-EBADE);
    }

    if ( (rc = parse_version_info(devinfo)) != 0 ) {

    }

    *device_p = rtv;
    rtv_devices.num_rtvs++;
    if ( RTVLOG_DSCVR ) {
        rtv_print_device_info(devinfo);
    }
    return (rc);
}
void _Expat_XML_SetDefaultHandler(struct ExpatIFace * Self, XML_Parser parser, XML_DefaultHandler handler)
{
	XML_SetDefaultHandler(parser, handler);
}
Beispiel #25
0
bool f_xml_set_default_handler(const Resource& parser, const Variant& handler) {
  XmlParser * p = parser.getTyped<XmlParser>();
  xml_set_handler(&p->defaultHandler, handler);
  XML_SetDefaultHandler(p->parser, _xml_defaultHandler);
  return true;
}
Beispiel #26
0
static void
parseclose(void *dat, const XML_Char *s)
{
	struct parse	 *p = dat;
	size_t		  i, j, sz, len;
	int		  c;
	char		**array;

	switch (calelem_find(s)) {
	case (CALELEM_CALENDAR_MULTIGET):
	case (CALELEM_CALENDAR_QUERY):
	case (CALELEM_PROPERTYUPDATE):
	case (CALELEM_PROPFIND):
		/* Clear our parsing context. */
		XML_SetDefaultHandler(p->xp, NULL);
		XML_SetElementHandler(p->xp, NULL, NULL);
		break;
	case (CALELEM_HREF):
		if (0 == p->buf.sz)
			break;
		/*
		 * According to the WebDAV RFC 4918, we need to URL
		 * decode this.
		 */
		array = reallocarray(p->p->hrefs, 
			p->p->hrefsz + 1, sizeof(char *));
		if (NULL == array) {
			caldav_err(p, "memory exhausted");
			break;
		}
		p->p->hrefs = array;
		sz = strlen(p->buf.buf);
		len = sz + 1;
		p->p->hrefs[p->p->hrefsz] = calloc(len, 1);
		if (NULL == p->p->hrefs[p->p->hrefsz]) {
			caldav_err(p, "memory exhausted");
			break;
		}
		p->p->hrefsz++;
		for (i = j = 0; i < sz; i++, j++) {
			c = p->buf.buf[i];
			if ('+' == c) {
				p->p->hrefs[p->p->hrefsz - 1][j] = ' ';
				continue;
			} else if ('%' != c) {
				p->p->hrefs[p->p->hrefsz - 1][j] = c;
				continue;
			}

			if ('\0' == p->buf.buf[i + 1] ||
			    '\0' == p->buf.buf[i + 2] ||
			    ! isalnum(p->buf.buf[i + 1]) ||
			    ! isalnum(p->buf.buf[i + 2])) {
				caldav_err(p, "bad percent-encoding");
				break;
			}

			p->p->hrefs[p->p->hrefsz - 1][j] = 
				parsehex(p->buf.buf[i + 1]) << 4 |
				parsehex(p->buf.buf[i + 2]);
			i += 2;
		}

		XML_SetDefaultHandler(p->xp, NULL);
		break;
	default:
		break;
	}
}
/****************************************************************
 ** Call from within a handler to print the currently recognized
 ** document fragment. Temporarily set the default handler and then
 ** invoke it via the the XML_DefaultCurrent call.
 */
void
printcurrent(XML_Parser p) {
  XML_SetDefaultHandler(p, default_hndl);
  XML_DefaultCurrent(p);
  XML_SetDefaultHandler(p, (XML_DefaultHandler) 0);
}  /* End printcurrent */