xslt.c 11.9 KB
Newer Older
1 2 3 4 5
/* Icecast
 *
 * This program is distributed under the GNU General Public License, version 2.
 * A copy of this license is included with this source.
 *
6
 * Copyright 2000-2004, Jack Moffitt <jack@xiph.org,
7 8 9 10
 *                      Michael Smith <msmith@xiph.org>,
 *                      oddsock <oddsock@xiph.org>,
 *                      Karl Heyes <karl@xiph.org>
 *                      and others (see AUTHORS for details).
11
 * Copyright 2012-2018, Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>,
12 13
 */

14 15 16 17
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

18 19 20 21 22 23 24
#include <string.h>
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
25
#include <libxml/uri.h>
26 27 28 29
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
30
#include <libxslt/documents.h>
31

32 33 34 35
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

36
#ifdef  HAVE_SYS_TIME_H
37 38 39
#include <sys/time.h>
#endif

40 41 42
#ifdef WIN32
#define snprintf _snprintf
#endif
43

Marvin Scholz's avatar
Marvin Scholz committed
44 45 46 47
#include "common/thread/thread.h"
#include "common/avl/avl.h"
#include "common/httpp/httpp.h"
#include "common/net/sock.h"
48

49
#include "xslt.h"
50 51
#include "refbuf.h"
#include "client.h"
52
#include "errors.h"
53
#include "stats.h"
54
#include "fserve.h"
Philipp Schafft's avatar
Philipp Schafft committed
55
#include "util.h"
56
#include "cfgfile.h"
57

58
#define CATMODULE "xslt"
Karl Heyes's avatar
Karl Heyes committed
59

60 61 62
#include "logging.h"

typedef struct {
63 64 65 66
    char *filename;
    time_t last_modified;
    time_t cache_age;
    xsltStylesheetPtr stylesheet;
67 68
} stylesheet_cache_t;

69 70 71 72 73 74 75
#ifndef HAVE_XSLTSAVERESULTTOSTRING
int xsltSaveResultToString(xmlChar **doc_txt_ptr, int * doc_txt_len, xmlDocPtr result, xsltStylesheetPtr style) {
    xmlOutputBufferPtr buf;

    *doc_txt_ptr = NULL;
    *doc_txt_len = 0;
    if (result->children == NULL)
76
        return (0);
77

78
    buf = xmlAllocOutputBuffer(NULL);
79 80

    if (buf == NULL)
81
        return (-1);
82 83
    xsltSaveResultTo(buf, result, style);
    if (buf->conv != NULL) {
84 85
        *doc_txt_len = buf->conv->use;
        *doc_txt_ptr = xmlStrndup(buf->conv->content, *doc_txt_len);
86
    } else {
87 88
        *doc_txt_len = buf->buffer->use;
        *doc_txt_ptr = xmlStrndup(buf->buffer->content, *doc_txt_len);
89
    }
90
    (void) xmlOutputBufferClose(buf);
91 92 93 94
    return 0;
}
#endif

95 96 97
/* Keep it small... */
#define CACHESIZE 3

98 99
static stylesheet_cache_t cache[CACHESIZE];
static mutex_t xsltlock;
100

101 102 103 104 105
/* Reference to the original xslt loader func */
static xsltDocLoaderFunc xslt_loader;
/* Admin path cache */
static xmlChar *admin_path = NULL;

106
void xslt_initialize(void)
107
{
108
    memset(cache, 0, sizeof(stylesheet_cache_t) * CACHESIZE);
109
    thread_mutex_create(&xsltlock);
110 111
    xmlInitParser();
    LIBXML_TEST_VERSION
112 113
    xmlSubstituteEntitiesDefault(1);
    xmlLoadExtDtdDefaultValue = 1;
114
    xslt_loader = xsltDocDefaultLoader;
115 116
}

117
void xslt_shutdown(void) {
118 119 120 121 122 123 124 125 126
    int i;

    for(i=0; i < CACHESIZE; i++) {
        if(cache[i].filename)
            free(cache[i].filename);
        if(cache[i].stylesheet)
            xsltFreeStylesheet(cache[i].stylesheet);
    }

127
    thread_mutex_destroy (&xsltlock);
128
    xmlCleanupParser();
129
    xsltCleanupGlobals();
130 131
    if (admin_path)
        xmlFree(admin_path);
132 133
}

134
static int evict_cache_entry(void) {
brendan's avatar
brendan committed
135
    int i, age=0, oldest=0;
136 137 138 139 140 141 142 143 144 145 146 147 148 149

    for(i=0; i < CACHESIZE; i++) {
        if(cache[i].cache_age > age) {
            age = cache[i].cache_age;
            oldest = i;
        }
    }

    xsltFreeStylesheet(cache[oldest].stylesheet);
    free(cache[oldest].filename);

    return oldest;
}

150
static xsltStylesheetPtr xslt_get_stylesheet(const char *fn) {
151 152 153 154
    int i;
    int empty = -1;
    struct stat file;

Philipp Schafft's avatar
Philipp Schafft committed
155
    if (stat(fn, &file) != 0) {
156
        ICECAST_LOG_WARN("Error checking for stylesheet file \"%s\": %s", fn,
157
                strerror(errno));
158 159 160
        return NULL;
    }

Philipp Schafft's avatar
Philipp Schafft committed
161
    for (i = 0; i < CACHESIZE; i++) {
Philipp Schafft's avatar
Philipp Schafft committed
162
        if(cache[i].filename) {
163
#ifdef _WIN32
Philipp Schafft's avatar
Philipp Schafft committed
164
            if(!stricmp(fn, cache[i].filename)) {
165
#else
Philipp Schafft's avatar
Philipp Schafft committed
166
            if(!strcmp(fn, cache[i].filename)) {
167
#endif
Philipp Schafft's avatar
Philipp Schafft committed
168
                if(file.st_mtime > cache[i].last_modified) {
169
                    xsltFreeStylesheet(cache[i].stylesheet);
170

171
                    cache[i].last_modified = file.st_mtime;
172
                    cache[i].stylesheet = xsltParseStylesheetFile(XMLSTR(fn));
173 174
                    cache[i].cache_age = time(NULL);
                }
175
                ICECAST_LOG_DEBUG("Using cached sheet %i", i);
176 177
                return cache[i].stylesheet;
            }
Philipp Schafft's avatar
Philipp Schafft committed
178
        } else {
179
            empty = i;
Philipp Schafft's avatar
Philipp Schafft committed
180
        }
181 182
    }

Philipp Schafft's avatar
Philipp Schafft committed
183
    if (empty >= 0) {
184
        i = empty;
Philipp Schafft's avatar
Philipp Schafft committed
185
    } else {
186
        i = evict_cache_entry();
Philipp Schafft's avatar
Philipp Schafft committed
187
    }
188 189 190

    cache[i].last_modified = file.st_mtime;
    cache[i].filename = strdup(fn);
191
    cache[i].stylesheet = xsltParseStylesheetFile(XMLSTR(fn));
192
    cache[i].cache_age = time(NULL);
Philipp Schafft's avatar
Philipp Schafft committed
193

194 195
    return cache[i].stylesheet;
}
196

197 198 199 200 201 202 203 204
/* Custom xslt loader */
static xmlDocPtr custom_loader(const        xmlChar *URI,
                               xmlDictPtr   dict,
                               int          options,
                               void        *ctxt,
                               xsltLoadType type)
{
    xmlDocPtr ret;
205
    xmlChar *rel_path, *fn, *final_URI = NULL;
206
    char *path_URI = NULL;
207
    xsltStylesheet *c;
208 209
    ice_config_t *config;

210 211 212
    switch (type) {
        /* In case an include is loaded */
        case XSLT_LOAD_STYLESHEET:
213 214 215 216 217 218
            /* URI is an escaped URI, make an unescaped version */
            path_URI = util_url_unescape((const char*)URI);
            /* Error if we can't unescape */
            if (path_URI == NULL)
                return NULL;

219
            /* Not look in admindir if the include file exists */
220 221
            if (access(path_URI, F_OK) == 0) {
                free(path_URI);
222
                break;
223 224
            }
            free(path_URI);
225

226 227 228 229
            c = (xsltStylesheet *) ctxt;
            /* Check if we actually have context/path */
            if (ctxt == NULL || c->doc->URL == NULL)
                break;
230

231
            /* Construct the right path */
232 233 234
            rel_path = xmlBuildRelativeURI(URI, c->doc->URL);
            if (rel_path != NULL && admin_path != NULL) {
                fn = xmlBuildURI(rel_path, admin_path);
235 236 237
                final_URI = fn;
                xmlFree(rel_path);
            }
238

239 240 241 242 243
            /* Fail if there was an error constructing the path */
            if (final_URI == NULL) {
                if (rel_path)
                    xmlFree(rel_path);
                return NULL;
244 245 246 247
            }
        break;
        /* In case a top stylesheet is loaded */
        case XSLT_LOAD_START:
248
            config = config_get_config();
249 250 251 252 253
            /* Admin path is cached, so that we don't need to get it from
             * the config every time we load a xsl include.
             * Whenever a new top stylesheet is loaded, we check here
             * if the path in the config has changed and adjust it, if needed.
             */
254
            if (admin_path != NULL &&
255
                strcmp(config->adminroot_dir, (char *)admin_path) != 0) {
256 257 258
                xmlFree(admin_path);
                admin_path = NULL;
            }
259 260 261 262
            /* Do we need to load the admin path? */
            if (!admin_path) {
                size_t len = strlen(config->adminroot_dir);

263
                admin_path = xmlMalloc(len+2);
264
                if (!admin_path)
265
                    return NULL;
266 267 268

                /* Copy over admin path and add a tailing slash. */
                xmlStrPrintf(admin_path, len+2, XMLSTR("%s/"), XMLSTR(config->adminroot_dir));
269
            }
270 271 272
            config_release_config();
        break;

273
        /* Avoid warnings about other events we don't care for */
274 275 276
        default:
        break;
    }
277

278
    /* Get the actual xmlDoc */
279 280 281 282 283 284
    if (final_URI) {
        ret = xslt_loader(final_URI, dict, options, ctxt, type);
        xmlFree(final_URI);
    } else {
        ret = xslt_loader(URI, dict, options, ctxt, type);
    }
285 286 287
    return ret;
}

288 289 290 291 292 293 294 295 296
static inline void _send_error(client_t *client, icecast_error_id_t id, int old_status) {
    if (old_status >= 400) {
        client_send_error_by_id(client, ICECAST_ERROR_RECURSIVE_ERROR);
        return;
    }

    client_send_error_by_id(client, id);
}

297
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client, int status)
298
{
299
    xmlDocPtr res;
300
    xsltStylesheetPtr cur;
301
    xmlChar *string;
302
    int len, problem = 0;
303
    const char *mediatype = NULL;
304
    const char *charset = NULL;
305

306 307
    xmlSetGenericErrorFunc("", log_parse_failure);
    xsltSetGenericErrorFunc("", log_parse_failure);
308
    xsltSetLoaderFunc(custom_loader);
309

310 311 312
    thread_mutex_lock(&xsltlock);
    cur = xslt_get_stylesheet(xslfilename);

313 314
    if (cur == NULL)
    {
315
        thread_mutex_unlock(&xsltlock);
316
        ICECAST_LOG_ERROR("problem reading stylesheet \"%s\"", xslfilename);
317
        _send_error(client, ICECAST_ERROR_XSLT_PARSE, status);
318
        return;
319
    }
320

321
    res = xsltApplyStylesheet(cur, doc, NULL);
322 323 324 325
    if (res != NULL) {
        if (xsltSaveResultToString(&string, &len, res, cur) < 0)
            problem = 1;
    } else {
326
        problem = 1;
327
    }
328

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

333 334 335 336 337
    if (cur->mediaType)
        mediatype = (char *)cur->mediaType;
    else
    {
        /* check method for the default, a missing method assumes xml */
338
        if (cur->method && xmlStrcmp (cur->method, XMLSTR("html")) == 0)
339 340
            mediatype = "text/html";
        else
341
            if (cur->method && xmlStrcmp (cur->method, XMLSTR("text")) == 0)
342 343 344 345
                mediatype = "text/plain";
            else
                mediatype = "text/xml";
    }
346
    if (problem == 0)
347
    {
ePirat's avatar
ePirat committed
348 349 350
        ssize_t ret;
        int failed = 0;
        refbuf_t *refbuf;
Philipp Schafft's avatar
Philipp Schafft committed
351
        ssize_t full_len = strlen(mediatype) + (ssize_t)len + (ssize_t)1024;
352 353
        if (full_len < 4096)
            full_len = 4096;
ePirat's avatar
ePirat committed
354
        refbuf = refbuf_new (full_len);
355

356
        if (string == NULL)
357
            string = xmlCharStrdup ("");
358
        ret = util_http_build_header(refbuf->data, full_len, 0, 0, status, NULL, mediatype, charset, NULL, NULL, client);
359 360
        if (ret == -1) {
            ICECAST_LOG_ERROR("Dropping client as we can not build response headers.");
361
            _send_error(client, ICECAST_ERROR_GEN_HEADER_GEN_FAILED, status);
362
        } else {
Philipp Schafft's avatar
Philipp Schafft committed
363
            if ( full_len < (ret + (ssize_t)len + (ssize_t)64) ) {
364
                void *new_data;
Philipp Schafft's avatar
Philipp Schafft committed
365
                full_len = ret + (ssize_t)len + (ssize_t)64;
366 367 368 369 370
                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;
371
                    ret = util_http_build_header(refbuf->data, full_len, 0, 0, status, NULL, mediatype, charset, NULL, NULL, client);
372 373
                    if (ret == -1) {
                        ICECAST_LOG_ERROR("Dropping client as we can not build response headers.");
374
                        _send_error(client, ICECAST_ERROR_GEN_HEADER_GEN_FAILED, status);
375 376 377 378
                        failed = 1;
                    }
                } else {
                    ICECAST_LOG_ERROR("Client buffer reallocation failed. Dropping client.");
379
                    _send_error(client, ICECAST_ERROR_GEN_BUFFER_REALLOC, status);
380 381 382 383 384 385 386
                    failed = 1;
                }
            }

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

387
                client->respcode = status;
388 389 390 391 392 393
                client_set_queue (client, NULL);
                client->refbuf = refbuf;
                refbuf->len = strlen (refbuf->data);
                fserve_add_client (client, NULL);
            }
        }
394 395
        xmlFree (string);
    }
396 397
    else
    {
398
        ICECAST_LOG_WARN("problem applying stylesheet \"%s\"", xslfilename);
399
        _send_error(client, ICECAST_ERROR_XSLT_problem, status);
400
    }
401
    thread_mutex_unlock (&xsltlock);
402 403 404
    xmlFreeDoc(res);
}