Пример #1
0
/*
 *  call-seq:
 *    transform(document, params = [])
 *
 *  Apply an XSLT stylesheet to an XML::Document.
 *  +params+ is an array of strings used as XSLT parameters.
 *  returns Nokogiri::XML::Document
 *
 *  Example:
 * 
 *    doc   = Nokogiri::XML(File.read(ARGV[0]))
 *    xslt  = Nokogiri::XSLT(File.read(ARGV[1]))
 *    puts xslt.transform(doc, ['key', 'value'])
 *
 */
static VALUE transform(int argc, VALUE* argv, VALUE self)
{
    VALUE xmldoc, paramobj, errstr, exception ;
    xmlDocPtr xml ;
    xmlDocPtr result ;
    nokogiriXsltStylesheetTuple *wrapper;
    const char** params ;
    long param_len, j ;
    int parse_error_occurred ;

    rb_scan_args(argc, argv, "11", &xmldoc, &paramobj);
    if (NIL_P(paramobj)) { paramobj = rb_ary_new2(0L) ; }
    if (!rb_obj_is_kind_of(xmldoc, cNokogiriXmlDocument))
      rb_raise(rb_eArgError, "argument must be a Nokogiri::XML::Document");

    /* handle hashes as arguments. */
    if(T_HASH == TYPE(paramobj)) {
      paramobj = rb_funcall(paramobj, rb_intern("to_a"), 0);
      paramobj = rb_funcall(paramobj, rb_intern("flatten"), 0);
    }

    Check_Type(paramobj, T_ARRAY);

    Data_Get_Struct(xmldoc, xmlDoc, xml);
    Data_Get_Struct(self, nokogiriXsltStylesheetTuple, wrapper);

    param_len = RARRAY_LEN(paramobj);
    params = calloc((size_t)param_len+1, sizeof(char*));
    for (j = 0 ; j < param_len ; j++) {
      VALUE entry = rb_ary_entry(paramobj, j);
      const char * ptr = StringValuePtr(entry);
      params[j] = ptr;
    }
    params[param_len] = 0 ;

    errstr = rb_str_new(0, 0);
    xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler);
    xmlSetGenericErrorFunc(NULL, (xmlGenericErrorFunc)&swallow_superfluous_xml_errors);

    result = xsltApplyStylesheet(wrapper->ss, xml, params);
    free(params);

    xsltSetGenericErrorFunc(NULL, NULL);
    xmlSetGenericErrorFunc(NULL, NULL);

    parse_error_occurred = (Qfalse == rb_funcall(errstr, rb_intern("empty?"), 0));

    if (parse_error_occurred) {
      exception = rb_exc_new3(rb_eRuntimeError, errstr);
      rb_exc_raise(exception);
    }

    return Nokogiri_wrap_xml_document((VALUE)0, result) ;
}
Пример #2
0
/*
 * call-seq:
 *   parse_stylesheet_doc(document)
 *
 * Parse a stylesheet from +document+.
 */
static VALUE parse_stylesheet_doc(VALUE klass, VALUE xmldocobj)
{
    xmlDocPtr xml ;
    xsltStylesheetPtr ss ;
    Data_Get_Struct(xmldocobj, xmlDoc, xml);
    exsltRegisterAll();

    xsltSetGenericErrorFunc(NULL, xslt_generic_error_handler);

    ss = xsltParseStylesheetDoc(xmlCopyDoc(xml, 1)); /* 1 => recursive */

    xsltSetGenericErrorFunc(NULL, NULL);

    return Data_Wrap_Struct(klass, NULL, dealloc, ss);
}
Пример #3
0
    void moduleInit() override {
      xsltSetGenericErrorFunc(nullptr, xslt_ext_error_handler);
      exsltRegisterAll();
      HHVM_RC_INT(XSL_SECPREF_NONE, k_XSL_SECPREF_NONE);
      HHVM_RC_INT(XSL_SECPREF_READ_FILE, k_XSL_SECPREF_READ_FILE);
      HHVM_RC_INT(XSL_SECPREF_WRITE_FILE, k_XSL_SECPREF_WRITE_FILE);
      HHVM_RC_INT(XSL_SECPREF_CREATE_DIRECTORY, k_XSL_SECPREF_CREATE_DIRECTORY);
      HHVM_RC_INT(XSL_SECPREF_READ_NETWORK, k_XSL_SECPREF_READ_NETWORK);
      HHVM_RC_INT(XSL_SECPREF_WRITE_NETWORK, k_XSL_SECPREF_WRITE_NETWORK);
      HHVM_RC_INT(XSL_SECPREF_DEFAULT, k_XSL_SECPREF_DEFAULT);

      HHVM_RC_INT_SAME(LIBXSLT_VERSION);
      HHVM_RC_STR_SAME(LIBXSLT_DOTTED_VERSION);

      HHVM_ME(XSLTProcessor, getParameter);
      HHVM_ME(XSLTProcessor, getSecurityPrefs);
      HHVM_ME(XSLTProcessor, importStylesheet);
      HHVM_ME(XSLTProcessor, removeParameter);
      HHVM_ME(XSLTProcessor, registerPHPFunctions);
      HHVM_ME(XSLTProcessor, setParameter);
      HHVM_ME(XSLTProcessor, setSecurityPrefs);
      HHVM_ME(XSLTProcessor, setProfiling);
      HHVM_ME(XSLTProcessor, transformToDoc);
      HHVM_ME(XSLTProcessor, transformToURI);
      HHVM_ME(XSLTProcessor, transformToXML);

      Native::
        registerNativeDataInfo<XSLTProcessorData>(s_XSLTProcessorData.get());

      loadSystemlib();
    }
Пример #4
0
c_XSLTProcessor::c_XSLTProcessor(Class *cb) :
  ExtObjectData(cb),
  m_stylesheet(nullptr), m_doc(nullptr), m_secprefs(k_XSL_SECPREF_DEFAULT),
  m_registerPhpFunctions(0) {
  xsltSetGenericErrorFunc(nullptr, xslt_ext_error_handler);
  exsltRegisterAll();
}
Пример #5
0
static void
xml_tree_model_init (xmlTreeModel *model)
{
	xmlSetStructuredErrorFunc(model, throw_xml_error);
	xsltSetGenericErrorFunc(model, throw_xsl_error);
	
	model->n_columns       = XML_TREE_MODEL_N_COLUMNS;
	model->column_types[0] = G_TYPE_INT;	/* XML_TREE_MODEL_COL_TYPE	*/
	model->column_types[1] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_NS	*/
	model->column_types[2] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_NAME	*/
	model->column_types[3] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_CONTENT	*/
	model->column_types[4] = G_TYPE_INT;		/* XML_TREE_MODEL_COL_LINE	*/
	model->column_types[5] = G_TYPE_ULONG;		/* XML_TREE_MODEL_COL_POS	*/
	model->column_types[6] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_PATH	*/
	g_assert (XML_TREE_MODEL_N_COLUMNS == 7);
 
	model->stamp = g_random_int();  /* Random int to check whether an iter belongs to our model */
	model->xmldoc = NULL;
	model->xsldoc = NULL;
	model->xpath = NULL;
	model->valid = FALSE;
	
	model->parser = xmlNewParserCtxt();
	model->nodeinfo = NULL;
	model->offset = 0;
}
Пример #6
0
/* setup all application wide items */
int
xsldbgThreadInit(void)
{
    int result = 0;
    fprintf(stderr, "mainInit()\n");
    xsltSetGenericErrorFunc(0, xsldbgGenericErrorFunc);
    setThreadStatus(XSLDBG_MSG_THREAD_INIT);
    xsldbgSetAppFunc(qtNotifyXsldbgApp);
    xsldbgSetAppStateFunc(qtNotifyStateXsldbgApp); 
    xsldbgSetTextFunc(qtNotifyTextXsldbgApp);
    xsldbgSetReadlineFunc(qtXslDbgShellReadline);
    

    /* create the thread */
    if (pthread_create(&mythread, NULL, xsldbgThreadMain, NULL) != EAGAIN) {
      int counter;
      for (counter = 0; counter < 11; counter++){
	if (getThreadStatus() != XSLDBG_MSG_THREAD_INIT)
	  break;
	usleep(250000); /*guess that it will take at most 2.5 seconds to startup */
      }
      /* xsldbg should have started by now if it can */
      if (getThreadStatus() == XSLDBG_MSG_THREAD_RUN){
        fprintf(stderr, "Created thread\n");
	result++;
      }else
         fprintf(stderr, "Thread did not start\n");
    } else {
      fprintf(stderr, "Failed to create thread\n");
    }

    return result;
}
Пример #7
0
void initErrorHandler ()
{
    xmlSecErrorsSetCallback(secErrorCallback);
    xmlSetGenericErrorFunc(xml_error_str, xmlErrorCallback);
#ifndef XMLSEC_NO_XSLT
    xsltSetGenericErrorFunc(xslt_error_str, xmlErrorCallback);
#endif
}
Пример #8
0
XSLTUtils::XSLTUtils() :
m_xmlInput(nullptr), m_xmlOutput(nullptr), m_xmlStylesheet(nullptr), m_xsltStylesheet(nullptr)
{
  // initialize libxslt
  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 0;
  xsltSetGenericErrorFunc(NULL, err);
}
Пример #9
0
/**
 * Extrae la cadena original del comprobante fiscal
 *
 * La funcion regresa:
 *
 *	0	En caso de generar la cadena original exitosamente,
 *
 * y en caso de error:
 *
 *	1	Cuando la stylsheet, proporcionada para generar la cadena
 *		original no pudo ser compilada.
 *	2	Cuando las transformaciones, definidas en la stylesheet
 *		indicada no pudieron aplicarse al CFDi.
 *	3	No fue posible escribir la cadena original a un buffer
 *
 */
int
genera_cadena_original(const char *stylesheet, xmlDocPtr doc, xmlChar** cadena, int verbose)
{
  xsltStylesheetPtr style = NULL;
  xmlDocPtr result = NULL;
  int cadena_len = 0;
  int out = 0;

  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 1;

  xsltSetGenericErrorFunc(stderr, local_error_function);

  style = xsltParseStylesheetFile((const xmlChar *)stylesheet);
  if ( style == NULL ) {
    if ( verbose ) {
      fprintf(stderr, "%s:%d Ocurrio un Error. Stylesheet (%s) no analizada.\n", __FILE__, __LINE__, stylesheet);
    }
    xsltCleanupGlobals();
    return 1;
  }

  result = xsltApplyStylesheet(style, doc, NULL);
  if ( result == NULL ) {
    if ( verbose ) {
      fprintf(stderr, "%s:%d Ocurrio un Error. Transformaciones de stylesheet (%s) no aplicadas.\n", __FILE__, __LINE__, stylesheet);
    }
    xsltFreeStylesheet(style);
    xsltCleanupGlobals();
    return 2;
  }

  out = xsltSaveResultToString(cadena, &cadena_len, result, style);
  if ( out == -1 ) {
    if ( verbose ) {
      fprintf(stderr, "%s:%d Ocurrio un error. Error al salvar la cadena original en el buffer.\n", __FILE__, __LINE__);
    }
    return 3;
  }

  xsltFreeStylesheet(style);
  xmlFreeDoc(result);

  if ( verbose ) {
    printf("%s:%d Cadena original de la información del comprobante:\n%s\n", __FILE__, __LINE__, *cadena);
  }

  xsltCleanupGlobals();

  return 0;
}
Пример #10
0
    void moduleInit() override {
      xsltSetGenericErrorFunc(nullptr, xslt_ext_error_handler);
      exsltRegisterAll();
      Native::registerConstant<KindOfInt64>(
        s_XSL_SECPREF_NONE.get(), k_XSL_SECPREF_NONE
      );
      Native::registerConstant<KindOfInt64>(
        s_XSL_SECPREF_READ_FILE.get(), k_XSL_SECPREF_READ_FILE
      );
      Native::registerConstant<KindOfInt64>(
        s_XSL_SECPREF_WRITE_FILE.get(), k_XSL_SECPREF_WRITE_FILE
      );
      Native::registerConstant<KindOfInt64>(
        s_XSL_SECPREF_CREATE_DIRECTORY.get(), k_XSL_SECPREF_CREATE_DIRECTORY
      );
      Native::registerConstant<KindOfInt64>(
        s_XSL_SECPREF_READ_NETWORK.get(), k_XSL_SECPREF_READ_NETWORK
      );
      Native::registerConstant<KindOfInt64>(
        s_XSL_SECPREF_WRITE_NETWORK.get(), k_XSL_SECPREF_WRITE_NETWORK
      );
      Native::registerConstant<KindOfInt64>(
        s_XSL_SECPREF_DEFAULT.get(), k_XSL_SECPREF_DEFAULT
      );

      Native::registerConstant<KindOfInt64>(
        s_xslt_version.get(), LIBXSLT_VERSION
      );
      Native::registerConstant<KindOfString>(
        s_xslt_dotted_version.get(), s_xslt_dotted_version_value.get()
      );

      HHVM_ME(XSLTProcessor, getParameter);
      HHVM_ME(XSLTProcessor, getSecurityPrefs);
      HHVM_ME(XSLTProcessor, importStylesheet);
      HHVM_ME(XSLTProcessor, removeParameter);
      HHVM_ME(XSLTProcessor, registerPHPFunctions);
      HHVM_ME(XSLTProcessor, setParameter);
      HHVM_ME(XSLTProcessor, setSecurityPrefs);
      HHVM_ME(XSLTProcessor, setProfiling);
      HHVM_ME(XSLTProcessor, transformToDoc);
      HHVM_ME(XSLTProcessor, transformToURI);
      HHVM_ME(XSLTProcessor, transformToXML);

      Native::
        registerNativeDataInfo<XSLTProcessorData>(s_XSLTProcessorData.get());

      loadSystemlib();
    }
Пример #11
0
/*
 * call-seq:
 *   parse_stylesheet_doc(document)
 *
 * Parse a stylesheet from +document+.
 */
static VALUE parse_stylesheet_doc(VALUE klass, VALUE xmldocobj)
{
    xmlDocPtr xml, xml_cpy;
    VALUE errstr, exception;
    xsltStylesheetPtr ss ;
    Data_Get_Struct(xmldocobj, xmlDoc, xml);
    exsltRegisterAll();

    errstr = rb_str_new(0, 0);
    xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler);

    xml_cpy = xmlCopyDoc(xml, 1); /* 1 => recursive */
    ss = xsltParseStylesheetDoc(xml_cpy);

    xsltSetGenericErrorFunc(NULL, NULL);

    if (!ss) {
	xmlFreeDoc(xml_cpy);
	exception = rb_exc_new3(rb_eRuntimeError, errstr);
	rb_exc_raise(exception);
    }

    return Nokogiri_wrap_xslt_stylesheet(ss);
}
Пример #12
0
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client)
{
    xmlDocPtr    res;
    xsltStylesheetPtr cur;
    xmlChar *string;
    int len, problem = 0;

    xmlSetGenericErrorFunc ("", log_parse_failure);
    xsltSetGenericErrorFunc ("", log_parse_failure);

    thread_mutex_lock(&xsltlock);
    cur = xslt_get_stylesheet(xslfilename);

    if (cur == NULL)
    {
        thread_mutex_unlock(&xsltlock);
        ERROR1 ("problem reading stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "Could not parse XSLT file");
        return;
    }

    res = xsltApplyStylesheet(cur, doc, NULL);

    if (xsltSaveResultToString (&string, &len, res, cur) < 0)
        problem = 1;
    thread_mutex_unlock(&xsltlock);
    if (problem == 0)
    {
        const char *http = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: ";
        int buf_len = strlen (http) + 20 + len;

        if (string == NULL)
            string = xmlStrdup ("");
        client->respcode = 200;
        client_set_queue (client, NULL);
        client->refbuf = refbuf_new (buf_len);
        len = snprintf (client->refbuf->data, buf_len, "%s%d\r\n\r\n%s", http, len, string);
        client->refbuf->len = len;
        fserve_add_client (client, NULL);
        xmlFree (string);
    }
    else
    {
        WARN1 ("problem applying stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "XSLT problem");
    }
    xmlFreeDoc(res);
}
Пример #13
0
/* thread to read xsl file and add to the cache */
void *xslt_update (void *arg)
{
    xsl_req *x = arg;
    client_t *client = x->client;
    char *fn = x->cache.filename;
    xsltStylesheetPtr sheet;

    xmlSetStructuredErrorFunc ("xsl/file", config_xml_parse_failure);
    xsltSetGenericErrorFunc ("", log_parse_failure);

    sheet = x->cache.stylesheet = xsltParseStylesheetFile (XMLSTR(fn));
    if (sheet)
    {
        int i;

        INFO1 ("loaded stylesheet %s", x->cache.filename);
        if (sheet->mediaType && strcmp ((char*)sheet->mediaType, "text/html") != 0)
        {
            // avoid this lookup for html pages
            const char _hdr[] = "Content-Disposition: attachment; filename=\"file.";
            const size_t _hdrlen = sizeof (_hdr);
            size_t len = _hdrlen + 12;
            char *filename = malloc (len); // enough for name and extension
            strcpy (filename, _hdr);
            fserve_write_mime_ext ((char*)sheet->mediaType, filename + _hdrlen - 1, len - _hdrlen - 4);
            strcat (filename, "\"\r\n");
            x->cache.disposition = filename;
        }
        // we now have a sheet, find and update.
        thread_rwlock_wlock (&xslt_lock);
        i = xslt_cached (fn, &x->cache, time(NULL));
        xslt_send_sheet (client, x->doc, i);
    }
    else
    {
        WARN1 ("problem reading stylesheet \"%s\"", x->cache.filename);
        free (fn);
        xmlFreeDoc (x->doc);
        free (x->cache.disposition);
        client->shared_data = NULL;
        client_send_404 (client, "Could not parse XSLT file");
    }
    thread_spin_lock (&update_lock);
    xsl_updating--;
    thread_spin_unlock (&update_lock);
    free (x);
    return NULL;
}
Пример #14
0
void xslt::init::init_library() {
    xsltInit();

    // set some defautls
    process_xincludes(true);
    set_allow_extension_functions_leak(false);

    // keep libxslt silent
    xsltSetGenericErrorFunc(0, xslt_error);
    xsltSetGenericDebugFunc(0, xslt_error);

    #ifdef HAVE_LIBEXSLT
        // load EXSLT
        exsltRegisterAll();
    #endif
}
Пример #15
0
//!
//! Initialize the XML local parameters from the NC state structure.
//!
//! @param[in] nc_state a pointer to the NC state structure to initialize
//!
static void init_xml(void)
{
    pthread_mutex_lock(&xml_mutex);
    {
        if (!initialized) {
            xmlIndentTreeOutput = 1;
            xmlKeepBlanksDefault(0);
            xmlInitParser();
            LIBXML_TEST_VERSION;       // verifies that loaded library matches the compiled library
            xmlSubstituteEntitiesDefault(1);    // substitute entities while parsing
            xmlSetGenericErrorFunc(NULL, error_handler);    // catches errors/warnings that libxml2 writes to stderr
            xsltSetGenericErrorFunc(NULL, error_handler);   // catches errors/warnings that libslt writes to stderr
            initialized = TRUE;
        }
    }
    pthread_mutex_unlock(&xml_mutex);
}
Пример #16
0
static void init (struct nc_state_t * nc_state)
{
    pthread_mutex_lock (&xml_mutex);
    if (!initialized) {
        xmlInitParser();
        LIBXML_TEST_VERSION; // verifies that loaded library matches the compiled library
        xmlSubstituteEntitiesDefault (1); // substitute entities while parsing
        xmlSetGenericErrorFunc (NULL, error_handler); // catches errors/warnings that libxml2 writes to stderr
        xsltSetGenericErrorFunc (NULL, error_handler); // catches errors/warnings that libslt writes to stderr
        if (nc_state!=NULL) {
            config_use_virtio_root = nc_state->config_use_virtio_root;
            config_use_virtio_disk = nc_state->config_use_virtio_disk;
            config_use_virtio_net =  nc_state->config_use_virtio_net;
            strncpy (xslt_path, nc_state->libvirt_xslt_path, sizeof (xslt_path));
        }
        initialized = 1;
    }
    pthread_mutex_unlock (&xml_mutex);
}
Пример #17
0
/**
 * Transform a document and return it.
 * @param in	document to transform.
 * @return		transformed document.
 */
Document *XSLTransform::transformDocument(Document *in) throw(XSLException) {
	xsltInit();

	// prepare parameters
	const char **aparams = new const char *[params.count() * 2 + 1];
	ASSERT(aparams);
	int i = 0;
	for(genstruct::AssocList<string, string>::PairIterator iter(params); iter; iter++) {
		aparams[i] = new char[(*iter).fst.length() + 1];
		strcpy((char *)aparams[i], &(*iter).fst);
		i++;
		aparams[i] = new char[(*iter).snd.length() + 1];
		strcpy((char *)aparams[i], &(*iter).snd);
		i++;
	}
	aparams[params.count() * 2] = 0;

	// perform the transformation
	xsltSetGenericErrorFunc(this, handle_error);
	xmlDoc *new_doc = xmlCopyDoc(DOC(ss->getNode()), 1);
	xsltStylesheetPtr stylesheet = xsltParseStylesheetDoc(new_doc);
	if(!stylesheet)
		throw XSLException("can not compile stylesheet");
	xmlDoc *res = xsltApplyStylesheet(stylesheet, DOC(in->getNode()), aparams);

	// clean up
	for(int i = 0; aparams[i]; i++)
		delete [] aparams[i];
	delete [] aparams;
	xmlSetStructuredErrorFunc(0, 0);
	xsltFreeStylesheet(stylesheet);
	if(!res)
		throw XSLException("error during XSLT transformation");

	// return result
	return fact->makeDocument(res);
}
Пример #18
0
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client)
{
    xmlDocPtr    res;
    xsltStylesheetPtr cur;
    xmlChar *string;
    int len, problem = 0;
    const char *mediatype = NULL;
    const char *charset = NULL;

    xmlSetGenericErrorFunc ("", log_parse_failure);
    xsltSetGenericErrorFunc ("", log_parse_failure);

    thread_mutex_lock(&xsltlock);
    cur = xslt_get_stylesheet(xslfilename);

    if (cur == NULL)
    {
        thread_mutex_unlock(&xsltlock);
        ICECAST_LOG_ERROR("problem reading stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "Could not parse XSLT file");
        return;
    }

    res = xsltApplyStylesheet(cur, doc, NULL);

    if (xsltSaveResultToString (&string, &len, res, cur) < 0)
        problem = 1;

    /* lets find out the content type and character encoding to use */
    if (cur->encoding)
       charset = (char *)cur->encoding;

    if (cur->mediaType)
        mediatype = (char *)cur->mediaType;
    else
    {
        /* check method for the default, a missing method assumes xml */
        if (cur->method && xmlStrcmp (cur->method, XMLSTR("html")) == 0)
            mediatype = "text/html";
        else
            if (cur->method && xmlStrcmp (cur->method, XMLSTR("text")) == 0)
                mediatype = "text/plain";
            else
                mediatype = "text/xml";
    }
    if (problem == 0)
    {
        ssize_t ret;
        int failed = 0;
        refbuf_t *refbuf;
        size_t full_len = strlen (mediatype) + len + 1024;
        if (full_len < 4096)
            full_len = 4096;
        refbuf = refbuf_new (full_len);

        if (string == NULL)
            string = xmlCharStrdup ("");
        ret = util_http_build_header(refbuf->data, full_len, 0, 0, 200, NULL, mediatype, charset, NULL, NULL);
        if (ret == -1) {
            ICECAST_LOG_ERROR("Dropping client as we can not build response headers.");
            client_send_500(client, "Header generation failed.");
        } else {
            if ( full_len < (ret + len + 64) ) {
                void *new_data;
                full_len = ret + len + 64;
                new_data = realloc(refbuf->data, full_len);
                if (new_data) {
                    ICECAST_LOG_DEBUG("Client buffer reallocation succeeded.");
                    refbuf->data = new_data;
                    refbuf->len = full_len;
                    ret = util_http_build_header(refbuf->data, full_len, 0, 0, 200, NULL, mediatype, charset, NULL, NULL);
                    if (ret == -1) {
                        ICECAST_LOG_ERROR("Dropping client as we can not build response headers.");
                        client_send_500(client, "Header generation failed.");
                        failed = 1;
                    }
                } else {
                    ICECAST_LOG_ERROR("Client buffer reallocation failed. Dropping client.");
                    client_send_500(client, "Buffer reallocation failed.");
                    failed = 1;
                }
            }

            if (!failed) {
                  snprintf(refbuf->data + ret, full_len - ret, "Content-Length: %d\r\n\r\n%s", len, string);

                client->respcode = 200;
                client_set_queue (client, NULL);
                client->refbuf = refbuf;
                refbuf->len = strlen (refbuf->data);
                fserve_add_client (client, NULL);
            }
        }
        xmlFree (string);
    }
    else
    {
        ICECAST_LOG_WARN("problem applying stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "XSLT problem");
    }
    thread_mutex_unlock (&xsltlock);
    xmlFreeDoc(res);
}
Пример #19
0
int xslt_transform (xmlDocPtr doc, const char *xslfilename, client_t *client)
{
    xmlDocPtr    res;
    xsltStylesheetPtr cur;
    int len;
    refbuf_t *content = NULL;
    char **params = NULL;

    xmlSetGenericErrorFunc ("", log_parse_failure);
    xsltSetGenericErrorFunc ("", log_parse_failure);

    thread_mutex_lock(&xsltlock);
    cur = xslt_get_stylesheet(xslfilename);

    if (cur == NULL)
    {
        thread_mutex_unlock(&xsltlock);
        ERROR1 ("problem reading stylesheet \"%s\"", xslfilename);
        return client_send_404 (client, "Could not parse XSLT file");
    }
    if (client->parser->queryvars)
    {
        // annoying but we need to surround the args with ' when passing them in
        int i, arg_count = client->parser->queryvars->length * 2;
        avl_node *node = avl_get_first (client->parser->queryvars);

        params = calloc (arg_count+1, sizeof (char *));
        for (i = 0; node && i < arg_count; node = avl_get_next (node))
        {
            http_var_t *param = (http_var_t *)node->key;
            char *tmp = util_url_escape (param->value);
            params[i++] = param->name;
            // use alloca for now, should really url esc into a supplied buffer
            params[i] = (char*)alloca (strlen (tmp) + 3);
            sprintf (params[i++], "\'%s\'", tmp);
            free (tmp);
        }
        params[i] = NULL;
    }

    res = xsltApplyStylesheet (cur, doc, (const char **)params);
    free (params);

    if (res == NULL || xslt_SaveResultToBuf (&content, &len, res, cur) < 0)
    {
        thread_mutex_unlock (&xsltlock);
        xmlFreeDoc (res);
        WARN1 ("problem applying stylesheet \"%s\"", xslfilename);
        return client_send_404 (client, "XSLT problem");
    }
    else
    {
        /* the 100 is to allow for the hardcoded headers */
        refbuf_t *refbuf = refbuf_new (100);
        const char *mediatype = NULL;

        /* lets find out the content type to use */
        if (cur->mediaType)
            mediatype = (char *)cur->mediaType;
        else
        {
            /* check method for the default, a missing method assumes xml */
            if (cur->method && xmlStrcmp (cur->method, XMLSTR("html")) == 0)
                mediatype = "text/html";
            else
                if (cur->method && xmlStrcmp (cur->method, XMLSTR("text")) == 0)
                    mediatype = "text/plain";
                else
                    mediatype = "text/xml";
        }
        snprintf (refbuf->data, 100,
                "HTTP/1.0 200 OK\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n",
                mediatype, len);

        thread_mutex_unlock (&xsltlock);
        client->respcode = 200;
        client_set_queue (client, NULL);
        client->refbuf = refbuf;
        refbuf->len = strlen (refbuf->data);
        refbuf->next = content;
    }
    xmlFreeDoc(res);
    return fserve_setup_client (client);
}
Пример #20
0
Xslt_Convert::Xslt_Convert( const QString xmlfile , const QString xsltfile ,  QString resulterxml )
 :EndingJob(false),xmlcodec(0),xsltcodec(0)
{
    ////////qDebug() << "### Start Xslt_Convert ...................  ->" << UmanTimeFromUnix(QTime_Null());
    qt_unlink(XMLERROR_FILE);  /* remove debug or error message from last */
    qt_unlink(resulterxml);  /* if exist */
    
    ///////QTimer::singleShot(1000, this, SLOT(CheckError()));
    QFile *xfile = new QFile( xmlfile );
    if (!xfile->exists()) {
    emit ErrorMsg(QString("File %1 not exist!").arg(xmlfile));
    return;
    }
    QFile *sfile = new QFile( xsltfile );
    if (!sfile->exists()) {
    emit ErrorMsg(QString("File %1 not exist!").arg(xsltfile));
    return;
    }
    xmlcodec = GetcodecfromXml(xmlfile);
    xsltcodec = GetcodecfromXml(xsltfile);
    
    ///////////qDebug() << "### xmlfile ..........................  " << xmlfile;
    ////////qDebug() << "### xsltfile ..........................  " << xsltfile;
  
    ////////qDebug() << "### codec ..........................  " << xmlcodec->mibEnum();
    ////////qDebug() << "### codec ..........................  " << xmlcodec->name();
    //////qDebug() << "### codec ..........................  " << xsltcodec->mibEnum();
    ////////qDebug() << "### codec ..........................  " << xsltcodec->name();
  
    const QString maildate = QString("\"%1\"").arg(UmanTimeFromUnix(QTime_Null()));
    const QString unixtime = QString("\"%1\"").arg(QTime_Null());
    
    const char* params[2];  
    params[0] = NULL;
    params[1] = NULL; 
    
    
    /* ######################################### */
         xsltStylesheetPtr cur = NULL;
         xmlDocPtr doc, outputDoc;
         xmlSubstituteEntitiesDefault(1);
         xmlLoadExtDtdDefaultValue = 1;
    /* ######################################### */
        char* xslt_errors;
        xsltSetGenericErrorFunc(&xslt_errors, qt_libxml_error_handler);
        xmlSetGenericErrorFunc(&xslt_errors, qt_libxml_error_handler);
        xsltSetGenericDebugFunc(&xslt_errors, qt_libxml_error_handler);
        QByteArray gocharxslt = QFile::encodeName(xsltfile); 
        cur = xsltParseStylesheetFile( (const xmlChar*)gocharxslt.data() );
        doc = xmlParseFile( QFile::encodeName(xmlfile) );
        outputDoc = xsltApplyStylesheet(cur, doc, params);
        xmlFreeDoc( doc ); /* free ram from xml! */
        doc = outputDoc; /* swap input and output */
        FILE* outfile = fopen( QFile::encodeName( resulterxml ), "w" );
        xsltSaveResultToFile( outfile, doc, cur );
        fclose( outfile );
        xsltFreeStylesheet(cur);
        xmlFreeDoc( outputDoc );
        xsltCleanupGlobals();
        xmlCleanupParser();
       //////// qDebug() << "### resulterxml ..........................  " << resulterxml;
       //////// qDebug() << "### XMLERROR_FILE ..........................  " << XMLERROR_FILE;
        Rstream = StreamFromFile(resulterxml);
        debug_msg = ReadFileUtf8Xml(XMLERROR_FILE);
        /////////qDebug() << "### resulterxml ..........................  " << debug_msg;
        qt_unlink(XMLERROR_FILE); 
        EndingJob = true;
        emit DebugMsg(debug_msg);

}
Пример #21
0
/*
 * Internal handler function
 */
static Datum
handler_internal(Oid function_oid, FunctionCallInfo fcinfo, bool execute)
{
	HeapTuple	proctuple;
	Form_pg_proc pg_proc_entry;
	char	   *sourcecode;
	Datum		prosrcdatum;
	bool		isnull;
	const char **xslt_params;
	int			i;
	Oid		   *argtypes;
	char	  **argnames;
	char	   *argmodes;
	int			numargs;
	xmlDocPtr	ssdoc;
	xmlDocPtr	xmldoc;
	xmlDocPtr	resdoc;
	xsltStylesheetPtr stylesheet;
	int			reslen;
	xmlChar	   *resstr;
	Datum		resdatum;

	if (CALLED_AS_TRIGGER(fcinfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("trigger functions not supported")));

	proctuple = SearchSysCache(PROCOID, ObjectIdGetDatum(function_oid), 0, 0, 0);
	if (!HeapTupleIsValid(proctuple))
		elog(ERROR, "cache lookup failed for function %u", function_oid);

	prosrcdatum = SysCacheGetAttr(PROCOID, proctuple, Anum_pg_proc_prosrc, &isnull);
	if (isnull)
		elog(ERROR, "null prosrc");

	sourcecode = pstrdup(DatumGetCString(DirectFunctionCall1(textout,
															 prosrcdatum)));
	/* allow one blank line at the start */
	if (sourcecode[0] == '\n')
		sourcecode++;

	numargs = get_func_arg_info(proctuple,
								&argtypes, &argnames, &argmodes);

	if (numargs < 1)
		ereport(ERROR,
				(errmsg("XSLT function must have at least one argument")));

				if (argtypes[0] != XMLOID)
		ereport(ERROR,
				(errmsg("first argument of XSLT function must have type XML")));

#if 0
	xsltSetGenericErrorFunc(NULL, xmlGenericError);
#endif

	ssdoc = xmlParseDoc((xmlChar *) sourcecode); /* XXX use backend's xml_parse here() */
	stylesheet = xsltParseStylesheetDoc(ssdoc); /* XXX check error handling */
	if (!stylesheet)
		ereport(ERROR,
				(errmsg("could not parse stylesheet")));

	pg_proc_entry = (Form_pg_proc) GETSTRUCT(proctuple);

	{
		char	   *method;

		method = (char *) stylesheet->method;
		/*
		 * TODO: This is strictly speaking not correct because the
		 * default output method may be "html", but that can only
		 * detected at run time, so punt for now.
		 */
		if (!method)
			method = "xml";

		if (strcmp(method, "xml") == 0 && pg_proc_entry->prorettype != XMLOID)
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
					 errmsg("XSLT stylesheet has output method \"xml\" but return type of function is not xml")));
		else if ((strcmp(method, "html") == 0 || strcmp(method, "text") == 0)
				 && pg_proc_entry->prorettype != TEXTOID && pg_proc_entry->prorettype != VARCHAROID)
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
					 errmsg("XSLT stylesheet has output method \"%s\" but return type of function is not text or varchar", method)));
	}

	/* validation stops here */
	if (!execute)
	{
		ReleaseSysCache(proctuple);
		PG_RETURN_VOID();
	}

	/* execution begins here */

	xslt_params = palloc(((numargs - 1) * 2 + 1) * sizeof(*xslt_params));
	for (i = 0; i < numargs-1; i++)
	{
		xslt_params[i*2] = argnames[i+1];
		xslt_params[i*2+1] = type_to_cstring(PG_GETARG_DATUM(i+1),
											 argtypes[i+1]);
	}
	xslt_params[i*2] = NULL;

	{
		xmltype *arg0 = PG_GETARG_XML_P(0);
		// XXX this ought to use xml_parse()
		xmldoc = xmlParseMemory((char *) VARDATA(arg0), VARSIZE(arg0) - VARHDRSZ);
	}

	resdoc = xsltApplyStylesheet(stylesheet, xmldoc, xslt_params);
	if (!resdoc)
		elog(ERROR, "xsltApplyStylesheet() failed");

	xmlFreeDoc(xmldoc);

	if (xsltSaveResultToString(&resstr, &reslen, resdoc, stylesheet) != 0)
		elog(ERROR, "result serialization failed");

	xsltFreeStylesheet(stylesheet);
	xmlFreeDoc(resdoc);

	xsltCleanupGlobals();
	xmlCleanupParser();

	resdatum = cstring_to_type(resstr ? (char *) resstr : "", pg_proc_entry->prorettype);
	ReleaseSysCache(proctuple);
	PG_RETURN_DATUM(resdatum);
}
Пример #22
0
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client)
{
    xmlDocPtr    res;
    xsltStylesheetPtr cur;
    xmlChar *string;
    int len, problem = 0;
    const char *mediatype = NULL;

    xmlSetGenericErrorFunc ("", log_parse_failure);
    xsltSetGenericErrorFunc ("", log_parse_failure);

    thread_mutex_lock(&xsltlock);
    cur = xslt_get_stylesheet(xslfilename);

    if (cur == NULL)
    {
        thread_mutex_unlock(&xsltlock);
        ERROR1 ("problem reading stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "Could not parse XSLT file");
        return;
    }

    res = xsltApplyStylesheet(cur, doc, NULL);

    if (xsltSaveResultToString (&string, &len, res, cur) < 0)
        problem = 1;

    /* lets find out the content type to use */
    if (cur->mediaType)
        mediatype = (char *)cur->mediaType;
    else
    {
        /* check method for the default, a missing method assumes xml */
        if (cur->method && xmlStrcmp (cur->method, XMLSTR("html")) == 0)
            mediatype = "text/html";
        else
            if (cur->method && xmlStrcmp (cur->method, XMLSTR("text")) == 0)
                mediatype = "text/plain";
            else
                mediatype = "text/xml";
    }
    if (problem == 0)
    {
        /* the 100 is to allow for the hardcoded headers */
        unsigned int full_len = strlen (mediatype) + len + 256;
        refbuf_t *refbuf = refbuf_new (full_len);
	ssize_t ret;

        if (string == NULL)
            string = xmlCharStrdup ("");
        ret = util_http_build_header(refbuf->data, full_len, 0, 0, 200, NULL, mediatype, NULL, NULL);
	snprintf (refbuf->data + ret, full_len - ret,
                "Content-Length: %d\r\n\r\n%s",
                len, string);

        client->respcode = 200;
        client_set_queue (client, NULL);
        client->refbuf = refbuf;
        refbuf->len = strlen (refbuf->data);
        fserve_add_client (client, NULL);
        xmlFree (string);
    }
    else
    {
        WARN1 ("problem applying stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "XSLT problem");
    }
    thread_mutex_unlock (&xsltlock);
    xmlFreeDoc(res);
}