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

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

Jack Moffitt's avatar
Jack Moffitt committed
19
#include <sys/types.h>
20
#include <ctype.h>
21 22
#include <stdio.h>
#include <string.h>
23
#include <stdlib.h>
Jack Moffitt's avatar
Jack Moffitt committed
24

25 26 27 28 29 30 31
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_WINSOCK2_H
#include <winsock2.h>
#endif

Jack Moffitt's avatar
Jack Moffitt committed
32
#ifndef _WIN32
33
#include <sys/time.h>
Jack Moffitt's avatar
Jack Moffitt committed
34
#include <unistd.h>
35
#ifdef HAVE_POLL
36
#include <poll.h>
37
#endif
38 39
#else
#include <windows.h>
Jack Moffitt's avatar
Jack Moffitt committed
40 41
#endif

42 43
#include "common/net/sock.h"
#include "common/thread/thread.h"
Jack Moffitt's avatar
Jack Moffitt committed
44

45
#include "util.h"
46
#include "compat.h"
47
#include "cfgfile.h"
48 49 50
#include "refbuf.h"
#include "connection.h"
#include "client.h"
51
#include "source.h"
52
#include "admin.h"
53
#include "auth.h"
54
#include "acl.h"
55 56 57 58

#define CATMODULE "util"

#include "logging.h"
Jack Moffitt's avatar
Jack Moffitt committed
59

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
/* first all static tables, then the code */

static const char hexchars[16] = {
    '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
};

static const char safechars[256] = {
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,
    0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,
    0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
};

static const char base64table[64] = {
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
};

static const signed char base64decode[256] = {
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
     52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -1, -2, -2,
     -2,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
     -2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
     41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
};


112 113 114 115 116 117 118 119 120
/* Abstract out an interface to use either poll or select depending on which
 * is available (poll is preferred) to watch a single fd.
 *
 * timeout is in milliseconds.
 *
 * returns > 0 if activity on the fd occurs before the timeout.
 *           0 if no activity occurs
 *         < 0 for error.
 */
121
int util_timed_wait_for_fd(sock_t fd, int timeout)
122 123 124 125 126 127 128 129 130 131 132
{
#ifdef HAVE_POLL
    struct pollfd ufds;

    ufds.fd = fd;
    ufds.events = POLLIN;
    ufds.revents = 0;

    return poll(&ufds, 1, timeout);
#else
    fd_set rfds;
133
    struct timeval tv, *p=NULL;
134 135 136 137

    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);

138 139 140 141 142 143
    if(timeout >= 0) {
        tv.tv_sec = timeout/1000;
        tv.tv_usec = (timeout % 1000)*1000;
        p = &tv;
    }
    return select(fd+1, &rfds, NULL, NULL, p);
144 145 146
#endif
}

147
int util_read_header(sock_t sock, char *buff, unsigned long len, int entire)
Jack Moffitt's avatar
Jack Moffitt committed
148
{
149 150 151 152
    int read_bytes, ret;
    unsigned long pos;
    char c;
    ice_config_t *config;
153
    int header_timeout;
Jack Moffitt's avatar
Jack Moffitt committed
154

155
    config = config_get_config();
156 157
    header_timeout = config->header_timeout;
    config_release_config();
Jack Moffitt's avatar
Jack Moffitt committed
158

159 160 161
    read_bytes = 1;
    pos = 0;
    ret = 0;
Jack Moffitt's avatar
Jack Moffitt committed
162

163 164
    while ((read_bytes == 1) && (pos < (len - 1))) {
        read_bytes = 0;
Jack Moffitt's avatar
Jack Moffitt committed
165

166
        if (util_timed_wait_for_fd(sock, header_timeout*1000) > 0) {
167 168
            if ((read_bytes = recv(sock, &c, 1, 0))) {
                if (c != '\r') buff[pos++] = c;
169
                if (entire) {
170
                    if ((pos > 1) && (buff[pos - 1] == '\n' &&
171 172 173 174 175 176 177 178 179 180
                                      buff[pos - 2] == '\n')) {
                        ret = 1;
                        break;
                    }
                }
                else {
                    if ((pos > 1) && (buff[pos - 1] == '\n')) {
                        ret = 1;
                        break;
                    }
181 182 183 184 185 186 187 188
                }
            }
        } else {
            break;
        }
    }

    if (ret) buff[pos] = '\0';
189

190
    return ret;
Jack Moffitt's avatar
Jack Moffitt committed
191 192
}

193
char *util_get_extension(const char *path) {
194 195 196 197 198 199 200 201
    char *ext = strrchr(path, '.');

    if(ext == NULL)
        return "";
    else
        return ext+1;
}

202
int util_check_valid_extension(const char *uri) {
203
    const char    *p2;
204

205 206 207 208 209 210 211 212 213 214 215 216
    if (!uri)
        return UNKNOWN_CONTENT;

    p2 = strrchr(uri, '.');
    if (!p2)
        return UNKNOWN_CONTENT;
    p2++;

    if (strcmp(p2, "xsl") == 0 || strcmp(p2, "xslt") == 0) {
        return XSLT_CONTENT;
    } else if (strcmp(p2, "htm") == 0 || strcmp(p2, "html") == 0) {
        return HTML_CONTENT;
217
    }
218 219

    return UNKNOWN_CONTENT;
220
}
Jack Moffitt's avatar
Jack Moffitt committed
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
static int hex(char c)
{
    if(c >= '0' && c <= '9')
        return c - '0';
    else if(c >= 'A' && c <= 'F')
        return c - 'A' + 10;
    else if(c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    else
        return -1;
}

static int verify_path(char *path) {
    int dir = 0, indotseq = 0;

    while(*path) {
        if(*path == '/' || *path == '\\') {
            if(indotseq)
                return 0;
            if(dir)
                return 0;
            dir = 1;
            path++;
            continue;
        }

        if(dir || indotseq) {
            if(*path == '.')
                indotseq = 1;
            else
                indotseq = 0;
        }
254

255 256 257 258 259 260 261
        dir = 0;
        path++;
    }

    return 1;
}

262 263 264 265 266 267 268 269 270 271 272 273 274
char *util_get_path_from_uri(char *uri) {
    char *path = util_normalise_uri(uri);
    char *fullpath;

    if(!path)
        return NULL;
    else {
        fullpath = util_get_path_from_normalised_uri(path);
        free(path);
        return fullpath;
    }
}

275
char *util_get_path_from_normalised_uri(const char *uri) {
276
    char *fullpath;
277 278
    char *webroot;
    ice_config_t *config = config_get_config();
279

280 281 282
    webroot = config->webroot_dir;

    fullpath = malloc(strlen(uri) + strlen(webroot) + 1);
283 284 285
    if (fullpath)
        sprintf (fullpath, "%s%s", webroot, uri);
    config_release_config();
286 287 288 289

    return fullpath;
}

290
char *util_url_escape (const char *src)
291
{
292 293
    size_t len;
    char *dst;
294
    unsigned char *source = (unsigned char *)src;
295
    size_t i, j;
296

297 298 299 300 301 302 303 304
    if (!src)
        return NULL;

    len = strlen(src);
    /* Efficiency not a big concern here, keep the code simple/conservative */
    dst = calloc(1, len*3 + 1);

    for(i = 0, j = 0; i < len; i++) {
305 306
        if(safechars[source[i]]) {
            dst[j++] = source[i];
307 308 309 310
        } else {
            dst[j++] = '%';
            dst[j++] = hexchars[(source[i] >> 4) & 0x0F];
            dst[j++] = hexchars[ source[i]       & 0x0F];
311 312 313 314 315 316 317
        }
    }

    dst[j] = 0;
    return dst;
}

318
char *util_url_unescape (const char *src)
319 320
{
    int len = strlen(src);
321
    char *decoded;
322
    int i;
323
    char *dst;
324 325
    int done = 0;

326
    decoded = calloc(1, len + 1);
327

328
    dst = decoded;
329

330 331
    for(i=0; i < len; i++) {
        switch(src[i]) {
332
            case '%':
333 334
                if(i+2 >= len) {
                    free(decoded);
335 336
                    return NULL;
                }
337 338
                if(hex(src[i+1]) == -1 || hex(src[i+2]) == -1 ) {
                    free(decoded);
339 340 341
                    return NULL;
                }

342
                *dst++ = hex(src[i+1]) * 16  + hex(src[i+2]);
343 344 345 346 347 348
                i+= 2;
                break;
            case '#':
                done = 1;
                break;
            case 0:
349
                ICECAST_LOG_ERROR("Fatal internal logic error in util_url_unescape()");
350
                free(decoded);
351 352 353
                return NULL;
                break;
            default:
354
                *dst++ = src[i];
355 356 357 358 359 360 361 362
                break;
        }
        if(done)
            break;
    }

    *dst = 0; /* null terminator */

363 364 365 366 367 368 369 370
    return decoded;
}

/* Get an absolute path (from the webroot dir) from a URI. Return NULL if the
 * path contains 'disallowed' sequences like foo/../ (which could be used to
 * escape from the webroot) or if it cannot be URI-decoded.
 * Caller should free the path.
 */
371
char *util_normalise_uri(const char *uri) {
372
    char *path;
373 374 375
#ifdef _WIN32
    size_t len;
#endif
376 377 378 379

    if(uri[0] != '/')
        return NULL;

380
    path = util_url_unescape(uri);
381 382

    if(path == NULL) {
383
        ICECAST_LOG_WARN("Error decoding URI: %s\n", uri);
384 385 386
        return NULL;
    }

387 388 389 390 391 392
#ifdef _WIN32
    /* If we are on Windows, strip trailing dots, as Win API strips it anyway */
    for (len = strlen(path); len > 0 && path[len-1] == '.'; len--)
        path[len-1] = '\0';
#endif

393 394
    /* We now have a full URI-decoded path. Check it for allowability */
    if(verify_path(path))
395
        return path;
396
    else {
397
        ICECAST_LOG_WARN("Rejecting invalid path \"%s\"", path);
398 399 400 401
        free(path);
        return NULL;
    }
}
Jack Moffitt's avatar
Jack Moffitt committed
402

403 404 405 406 407
char *util_bin_to_hex(unsigned char *data, int len)
{
    char *hex = malloc(len*2 + 1);
    int i;

408
    for (i = 0; i < len; i++) {
409 410 411 412 413 414 415 416 417
        hex[i*2] = hexchars[(data[i]&0xf0) >> 4];
        hex[i*2+1] = hexchars[data[i]&0x0f];
    }

    hex[len*2] = 0;

    return hex;
}

418
/* This isn't efficient, but it doesn't need to be */
419
char *util_base64_encode(const char *data, size_t len) {
420 421
    char *out = malloc(len*4/3 + 4);
    char *result = out;
422
    size_t chunk;
423 424

    while(len > 0) {
425
        chunk = (len > 3) ? 3 : len;
426
        *out++ = base64table[(*data & 0xFC)>>2];
427

428 429
        switch(chunk) {
            case 3:
430
                *out++ = base64table[((*data & 0x03)<<4) | ((*(data+1) & 0xF0) >> 4)];
431 432
                *out++ = base64table[((*(data+1) & 0x0F)<<2) | ((*(data+2) & 0xC0)>>6)];
                *out++ = base64table[(*(data+2)) & 0x3F];
433
            break;
434
            case 2:
435
                *out++ = base64table[((*data & 0x03)<<4) | ((*(data+1) & 0xF0) >> 4)];
436 437
                *out++ = base64table[((*(data+1) & 0x0F)<<2)];
                *out++ = '=';
438
            break;
439
            case 1:
440
                *out++ = base64table[((*data & 0x03)<<4)];
441 442
                *out++ = '=';
                *out++ = '=';
443
            break;
444 445 446 447
        }
        data += chunk;
        len -= chunk;
    }
448
    *out = 0;
449 450 451 452

    return result;
}

453
char *util_base64_decode(const char *data)
454
{
455 456
    const unsigned char *input = (const unsigned char *)data;
    int len = strlen (data);
457 458 459 460 461 462 463 464 465 466 467
    char *out = malloc(len*3/4 + 5);
    char *result = out;
    signed char vals[4];

    while(len > 0) {
        if(len < 4)
        {
            free(result);
            return NULL; /* Invalid Base64 data */
        }

468 469 470 471
        vals[0] = base64decode[*input++];
        vals[1] = base64decode[*input++];
        vals[2] = base64decode[*input++];
        vals[3] = base64decode[*input++];
472 473

        if(vals[0] < 0 || vals[1] < 0 || vals[2] < -1 || vals[3] < -1) {
474
            len -= 4;
475 476 477 478
            continue;
        }

        *out++ = vals[0]<<2 | vals[1]>>4;
479 480 481 482
        /* vals[3] and (if that is) vals[2] can be '=' as padding, which is
           looked up in the base64decode table as '-1'. Check for this case,
           and output zero-terminators instead of characters if we've got
           padding. */
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        if(vals[2] >= 0)
            *out++ = ((vals[1]&0x0F)<<4) | (vals[2]>>2);
        else
            *out++ = 0;

        if(vals[3] >= 0)
            *out++ = ((vals[2]&0x03)<<6) | (vals[3]);
        else
            *out++ = 0;

        len -= 4;
    }
    *out = 0;

    return result;
}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
util_hostcheck_type util_hostcheck(const char *hostname) {
    const char * p;
    size_t colon_count;

    if (!hostname)
        return HOSTCHECK_ERROR;

    if (strcmp(hostname, "localhost") == 0 ||
        strcmp(hostname, "localhost.localdomain") == 0 ||
        strcmp(hostname, "localhost.localnet") == 0)
        return HOSTCHECK_IS_LOCALHOST;

    for (p = hostname; *p; p++)
        if (!( (*p >= '0' && *p <= '9') || *p == '.'))
            break;
    if (!*p)
        return HOSTCHECK_IS_IPV4;

    for (p = hostname, colon_count = 0; *p; p++) {
        if (*p == ':') {
            colon_count++;
            continue;
        }
        if (!((*p >= 'a' && *p <= 'f') || (*p >= '0' && *p <= '9') || *p == ':'))
            break;
    }
    if (!*p && colon_count)
        return HOSTCHECK_IS_IPV6;

    for (p = hostname; *p; p++)
        if (!( (*p >= 'a' && *p <= 'z') || (*p >= '0' && *p <= '9') || *p == '.' || *p == '-' ))
            return HOSTCHECK_BADCHAR;

    for (p = hostname, colon_count = 0; *p && *p != '.'; p++);
    if (!*p)
        return HOSTCHECK_NOT_FQDN;

    return HOSTCHECK_SANE;
}

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
int util_str_to_bool(const char *str) {
    /* consider NULL and empty strings false */
    if (!str || !*str)
        return 0;

    /* common words for true values */
    if (strcasecmp(str, "true") == 0 ||
        strcasecmp(str, "yes")  == 0 ||
        strcasecmp(str, "on")   == 0 )
        return 1;

    /* old style numbers: consider everyting non-zero true */
    if (atoi(str))
        return 1;

    /* we default to no */
    return 0;
}
558

559 560 561 562 563 564 565 566 567 568 569 570 571 572
int util_str_to_loglevel(const char *str) {
    if (strcasecmp(str, "debug") == 0 || strcasecmp(str, "DBUG") == 0)
        return ICECAST_LOGLEVEL_DEBUG;
    if (strcasecmp(str, "information") == 0 || strcasecmp(str, "INFO") == 0)
        return ICECAST_LOGLEVEL_INFO;
    if (strcasecmp(str, "warning") == 0 || strcasecmp(str, "WARN") == 0)
        return ICECAST_LOGLEVEL_WARN;
    if (strcasecmp(str, "error") == 0 || strcasecmp(str, "EROR") == 0)
        return ICECAST_LOGLEVEL_ERROR;

    /* gussing it is old-style numerical setting */
    return atoi(str);
}

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
int util_str_to_int(const char *str, const int default_value)
{
    /* consider NULL and empty strings default */
    if (!str || !*str)
        return default_value;
    return atoi(str);
}

unsigned int util_str_to_unsigned_int(const char *str, const unsigned int default_value)
{
    long int val;
    char *rem = NULL;

    /* consider NULL and empty strings default */
    if (!str || !*str)
        return default_value;

    val = strtol(str, &rem, 10);

    /* There is a left over */
    if (rem && *rem)
        return default_value;

    if (val < 0)
        return default_value;

    return (unsigned int)(unsigned long int)val;
}

602
/* TODO, FIXME: handle memory allocation errors better. */
603
static inline void   _build_headers_loop(char **ret, size_t *len, const ice_config_http_header_t *header, int status, const char *allow, client_t *client) {
604 605 606
    size_t headerlen;
    const char *name;
    const char *value;
607 608
    char *r = *ret;
    char *n;
609

610 611 612 613 614 615 616 617
    if (!header)
        return;

    do {
        /* filter out header's we don't use. */
        if (header->status != 0 && header->status != status) continue;

        /* get the name of the header */
618
        name = header->name;
619 620

        /* handle type of the header */
621
        value = NULL;
622 623 624
        switch (header->type) {
            case HTTP_HEADER_TYPE_STATIC:
                value = header->value;
625 626 627 628 629 630 631 632
            break;
            case HTTP_HEADER_TYPE_CORS:
                if (name && client && client->parser) {
                    const char *origin = httpp_getvar(client->parser, "origin");
                    if (origin) {
                        value = header->value;
                        if (!value) {
                            if (strcasecmp(name, "Access-Control-Allow-Origin") == 0) {
633 634 635 636 637 638 639
                                if (status >= 200 && status <= 299) {
                                    value = origin;
                                } else if (status >= 400 && status <= 599) {
                                    value = "null";
                                } else {
                                    /* do not set as we do not have a default for that. */
                                }
640
                            } else if (strcasecmp(name, "Access-Control-Allow-Methods") == 0) {
641 642 643 644 645 646 647 648 649 650 651 652
                                if (status >= 200 && status <= 299) {
                                    /* only use the default if we are posive reply. */
                                    value = allow;
                                }
                            } else if (strcasecmp(name, "Access-Control-Expose-Headers") == 0) {
                                value = "icy-br, icy-description, icy-genre, icy-name, icy-pub, icy-url";
                            } else if (strcasecmp(name, "Access-Control-Max-Age") == 0) {
                                value = "300"; /* 300s = 5 minutes */
                            /* No default (yet)
                             * } else if (strcasecmp(name, "Access-Control-Allow-Credentials") == 0) {
                             * } else if (strcasecmp(name, "Access-Control-Allow-Headers") == 0) {
                             */
653 654 655 656 657
                            }
                        }
                    }
                }
            break;
658
        }
659

660 661 662 663
        /* check data */
        if (!name || !value)
            continue;

664
        /* append the header to the buffer */
665
        headerlen = strlen(name) + strlen(value) + 4;
666
        *len += headerlen;
667 668 669 670 671 672 673 674 675 676 677
        n = realloc(r, *len);
        if (n) {
            r = n;
            strcat(r, name);
            strcat(r, ": ");
            strcat(r, value);
            strcat(r, "\r\n");
        } else {
            /* FIXME: we skip this header. We should do better. */
            *len -= headerlen;
        }
678
    } while ((header = header->next));
679 680
    *ret = r;
}
681
static inline char * _build_headers(int status, const char *allow, ice_config_t *config, source_t *source, client_t *client) {
682
    const ice_config_http_header_t *header;
683 684 685 686 687 688 689 690 691 692
    mount_proxy *mountproxy = NULL;
    char *ret = NULL;
    size_t len = 1;

    if (source)
        mountproxy = config_find_mount(config, source->mount, MOUNT_TYPE_NORMAL);

    ret = calloc(1, 1);
    *ret = 0;

693
    _build_headers_loop(&ret, &len, config->http_headers, status, allow, client);
694
    if (mountproxy && mountproxy->http_headers)
695
        _build_headers_loop(&ret, &len, mountproxy->http_headers, status, allow, client);
696 697 698 699
    if (client && client->auth && (header = client->auth->http_headers))
        _build_headers_loop(&ret, &len, header, status, allow, client);
    if (client && client->acl && (header = acl_get_http_headers(client->acl)))
        _build_headers_loop(&ret, &len, header, status, allow, client);
700

701 702 703
    return ret;
}

704 705 706 707
ssize_t util_http_build_header(char * out, size_t len, ssize_t offset,
        int cache,
        int status, const char * statusmsg,
        const char * contenttype, const char * charset,
708
        const char * datablock,
709
        source_t * source, client_t * client) {
710
    const char * http_version = "1.1";
711 712 713
    ice_config_t *config;
    time_t now;
    struct tm result;
714 715
    struct tm *gmtime_result;
    char currenttime_buffer[80];
716 717 718
    char status_buffer[80];
    char contenttype_buffer[80];
    ssize_t ret;
719
    char * extra_headers;
720
    const char *connection_header = "Close";
721
    const char *upgrade_header = "";
722
    const char *allow_header;
723 724 725 726

    if (!out)
        return -1;

727
    if (client) {
728 729
        if (client->con->tlsmode != ICECAST_TLSMODE_DISABLED)
            upgrade_header = "Upgrade: TLS/1.0\r\n";
730 731 732
        switch (client->reuse) {
            case ICECAST_REUSE_CLOSE:      connection_header = "Close"; break;
            case ICECAST_REUSE_KEEPALIVE:  connection_header = "Keep-Alive"; break;
733
            case ICECAST_REUSE_UPGRADETLS: connection_header = "Upgrade"; upgrade_header = ""; break;
734 735 736
        }
    }

737 738 739 740 741 742 743 744 745 746 747 748 749
    if (offset == -1)
        offset = strlen (out);

    out += offset;
    len -= offset;

    if (status == -1)
    {
        status_buffer[0] = '\0';
    }
    else
    {
        if (!statusmsg)
750 751 752
        {
            switch (status)
            {
753 754
                case 100: statusmsg = "Continue"; break;
                case 101: statusmsg = "Switching Protocols"; break;
755
                case 200: statusmsg = "OK"; break;
756
                case 204: statusmsg = "No Content"; break;
757
                case 206: statusmsg = "Partial Content"; break;
758 759 760 761 762 763 764 765
                case 300: statusmsg = "Multiple Choices"; break;
                case 301: statusmsg = "Moved Permanently"; break;
                case 302: statusmsg = "Found"; break;
                case 303: statusmsg = "See Other"; break;
                case 304: statusmsg = "Not Modified"; break;
                case 305: statusmsg = "Use Proxy"; break;
                case 307: statusmsg = "Temporary Redirect"; break;
                case 308: statusmsg = "Permanent Redirect"; break;
766 767 768 769
                case 400: statusmsg = "Bad Request"; break;
                case 401: statusmsg = "Authentication Required"; break;
                case 403: statusmsg = "Forbidden"; break;
                case 404: statusmsg = "File Not Found"; break;
770 771 772
                case 405: statusmsg = "Method Not Allowed"; break;
                case 409: statusmsg = "Conflict"; break;
                case 415: statusmsg = "Unsupported Media Type"; break;
773
                case 416: statusmsg = "Request Range Not Satisfiable"; break;
774
                case 426: statusmsg = "Upgrade Required"; break;
775 776
                case 429: statusmsg = "Too Many Requests"; break;
                /* case of 500 is handled differently. No need to list it here. -- ph3-der-loewe, 2018-05-05 */
777
                case 501: statusmsg = "Unimplemented"; break;
778
                case 503: statusmsg = "Service Unavailable"; break;
779 780 781 782
                default:  statusmsg = "(unknown status code)"; break;
            }
        }
        snprintf (status_buffer, sizeof (status_buffer), "HTTP/%s %d %s\r\n", http_version, status, statusmsg);
783 784 785 786
    }

    if (contenttype)
    {
787
        if (charset)
788
            snprintf (contenttype_buffer, sizeof (contenttype_buffer), "Content-Type: %s; charset=%s\r\n",
789 790
                                                                       contenttype, charset);
        else
791 792 793 794 795 796 797 798 799
            snprintf (contenttype_buffer, sizeof (contenttype_buffer), "Content-Type: %s\r\n",
                                                                       contenttype);
    }
    else
    {
        contenttype_buffer[0] = '\0';
    }

    time(&now);
800 801 802 803 804 805 806 807 808 809
#ifndef _WIN32
    gmtime_result = gmtime_r(&now, &result);
#else
    /* gmtime() on W32 breaks POSIX and IS thread-safe (uses TLS) */
    gmtime_result = gmtime (&now);
    if (gmtime_result)
        memcpy (&result, gmtime_result, sizeof (result));
#endif

    if (gmtime_result)
810
        strftime(currenttime_buffer, sizeof(currenttime_buffer), "Date: %a, %d %b %Y %X GMT\r\n", gmtime_result);
811 812
    else
        currenttime_buffer[0] = '\0';
813

814 815 816 817 818 819 820 821 822 823 824 825
    if (client) {
        if (client->admin_command != ADMIN_COMMAND_ERROR) {
            allow_header = "GET, POST, OPTIONS";
        } else if (source) {
            allow_header = "GET, DELETE, OPTIONS";
        } else {
            allow_header = "GET, PUT, OPTIONS, SOURCE";
        }
    } else {
        allow_header = "GET, OPTIONS";
    }

826
    config = config_get_config();
827
    extra_headers = _build_headers(status, allow_header, config, source, client);
828
    ret = snprintf (out, len, "%sServer: %s\r\nConnection: %s\r\nAccept-Encoding: identity\r\nAllow: %s\r\n%s%s%s%s%s%s%s%s",
829
                              status_buffer,
830
                              config->server_id,
831
                              connection_header,
832
                              allow_header,
833
                              upgrade_header,
834 835 836
                              currenttime_buffer,
                              contenttype_buffer,
                              (status == 401 ? "WWW-Authenticate: Basic realm=\"Icecast2 Server\"\r\n" : ""),
837
                              (cache     ? "" : "Cache-Control: no-cache, no-store\r\n"
838 839
                                                "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n"
                                                "Pragma: no-cache\r\n"),
840
                              extra_headers,
841 842
                              (datablock ? "\r\n" : ""),
                              (datablock ? datablock : ""));
843
    free(extra_headers);
844 845 846 847 848
    config_release_config();

    return ret;
}

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
#define __SELECT_BEST_MAX_ARGS  8

struct __args {
    const char *comp;
    char *group;
    int best_comp;
    int best_group;
    int best_all;
};

static inline int __fill_arg(struct __args *arg, const char *str)
{
    char *delm;
    size_t len;

    arg->comp = str;
    arg->best_comp = 0;
    arg->best_group = 0;
    arg->best_all = 0;

    len = strlen(str);
    arg->group = malloc(len + 2);
    if (!arg->group)
        return -1;

    memcpy(arg->group, str, len + 1);

    delm = strstr(arg->group, "/");
    if (delm) {
        delm[0] = '/';
        delm[1] = '*';
        delm[2] = 0;
    }

    return 0;
}

static inline void __free_args(struct __args *arg, size_t len)
{
    size_t i;

    for (i = 0; i < len; i++) {
891
        free(arg[i].group);
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    }
}

static inline int __parse_q(const char *str)
{
    int ret = 0;
    int mul = 1000;

    for (; *str; str++) {
        if (*str >= '0' && *str <= '9') {
            ret += mul * (*str - '0');
            mul /= 10;
        } else if (*str == '.') {
            mul = 100;
        } else {
            ICECAST_LOG_ERROR("Badly formated quality parameter found.");
            return -1;
        }
    }

    return ret;
}

static inline int __find_q_in_index(icecast_kva_t *kv, size_t idx)
{
    size_t i = kv->index[idx] + 1;
    size_t last;

    if (kv->indexlen <= (idx + 1)) {
        last = kv->kvlen - 1;
    } else {
        last = kv->index[idx + 1] - 1;
    }

    for (; i <= last; i++) {
        if (kv->kv[i].key && kv->kv[i].key && strcasecmp(kv->kv[i].key, "q") == 0) {
            return __parse_q(kv->kv[i].value);
        }
    }

    return 1000;
}

const char *util_http_select_best(const char *input, const char *first, ...)
{
    struct __args arg[__SELECT_BEST_MAX_ARGS];
    icecast_kva_t *kv;
    const char *p;
    size_t arglen = 1;
    size_t i, h;
    va_list ap;
    int q;
    int best_q = 0;

    if (__fill_arg(&(arg[0]), first) == -1) {
        ICECAST_LOG_ERROR("Can not allocate memory. Selecting first option.");
        return first;
    }
    va_start(ap, first);
    while ((p = (const char*)va_arg(ap, const char*))) {
        if (arglen == __SELECT_BEST_MAX_ARGS) {
            ICECAST_LOG_ERROR("More arguments given than supported. Currently %zu args are supported.", (size_t)__SELECT_BEST_MAX_ARGS);
            break;
        }
        if (__fill_arg(&(arg[arglen]), p) == -1) {
            ICECAST_LOG_ERROR("Can not allocate memory. Selecting first option.");
            __free_args(arg, arglen);
            return first;
        }

        arglen++;
    }
    va_end(ap);

    kv = util_parse_http_cn(input);
    if (!kv) {
        ICECAST_LOG_ERROR("Input string does not parse as KVA. Selecting first option.");
        __free_args(arg, arglen);
        return first;
    }

973
    ICECAST_LOG_DDEBUG("--- DUMP ---");
974
    for (i = 0; i < kv->kvlen; i++) {
975
        ICECAST_LOG_DDEBUG("kv[%zu] = {.key='%H', .value='%H'}", i, kv->kv[i].key, kv->kv[i].value);
976 977
    }
    for (i = 0; i < kv->indexlen; i++) {
978
        ICECAST_LOG_DDEBUG("index[%zu] = %zu", i, kv->index[i]);
979
    }
980
    ICECAST_LOG_DDEBUG("--- END OF DUMP ---");
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

    for (h = 0; h < arglen; h++) {
        for (i = 0; i < kv->indexlen; i++) {
            p = kv->kv[kv->index[i]].key;
            if (!p) {
                continue;
            }

            q = __find_q_in_index(kv, i);
            if (best_q < q) {
                best_q = q;
            }

            if (strcasecmp(p, arg[h].comp) == 0) {
                if (arg[h].best_comp < q) {
                    arg[h].best_comp = q;
                }
            }

            if (strcasecmp(p, arg[h].group) == 0) {
                if (arg[h].best_group < q) {
                    arg[h].best_group = q;
                }
            }
        }
    }

    util_kva_free(kv);

    p = NULL;
    for (h = 0; p == NULL && h < arglen; h++) {
        if (arg[h].best_comp == best_q) {
            p = arg[h].comp;
        }
    }
    for (h = 0; p == NULL && h < arglen; h++) {
        if (arg[h].best_group == best_q) {
            p = arg[h].comp;
        }
    }

    __free_args(arg, arglen);

    if (p == NULL) {
        p = first;
    }

    return p;
}

static inline void __skip_space(char **p)
{
    for (; **p == ' '; (*p)++);
}

static inline int __is_token(const char p)
{
    return (p >= 'a' && p <= 'z') || (p >= 'A' && p <= 'Z') || (p >= '0' && p <= '9') ||
            p == '!' || p == '#'  ||  p == '$' || p == '%'  ||  p == '&' || p == '\'' ||
            p == '*' || p == '+'  ||  p == '-' || p == '.'  ||  p == '^' || p == '_'  ||
            p == '|' || p == '~'  ||  p == '/';

}

enum __tokenizer_result {
    __TOKENIZER_RESULT_COMMA,
    __TOKENIZER_RESULT_EQ,
    __TOKENIZER_RESULT_SEMICOLON,
    __TOKENIZER_RESULT_ILSEQ,
    __TOKENIZER_RESULT_EOS
};

static inline enum __tokenizer_result __tokenizer_res_from_char(const char p)
{
    switch (p) {
        case 0:
            return __TOKENIZER_RESULT_EOS;
        break;
        case ',':
            return __TOKENIZER_RESULT_COMMA;
        break;
        case '=':
            return __TOKENIZER_RESULT_EQ;
        break;
        case ';':
            return __TOKENIZER_RESULT_SEMICOLON;
        break;
        default:
            return __TOKENIZER_RESULT_ILSEQ;
        break;
    }
}

static enum __tokenizer_result __tokenizer_str(char **out, char **in)
{
    char *p, *o;
    char c;

    __skip_space(in);

    p = *in;
    if (*p != '"')
        return __TOKENIZER_RESULT_ILSEQ;

    p++;
    o = p;

    for (; (c = *p); p++) {
1089
        if (c == '\t' || c == ' ' || c == 0x21 || (c >= 0x23 && c <= 0x5B) || (c >= 0x5D && c <= 0x7E) || ((unsigned char)c >= 0x80)) {
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
            *(o++) = c;
        } else if (c == '\\') {
            p++;
            c = *p;
            if (c == 0) {
                return __TOKENIZER_RESULT_ILSEQ;
            } else {
                *(o++) = c;
            }
        } else if (c == '"') {
            *o = 0;
            break;
        } else {
            return __TOKENIZER_RESULT_ILSEQ;
        }
    }

    if (*p == '"') {
        p++;
        *in = p + 1;
        __skip_space(in);
        return __tokenizer_res_from_char(*p);
    } else {
        return __TOKENIZER_RESULT_ILSEQ;
    }
}

static enum __tokenizer_result __tokenizer(char **out, char **in)
{
    char *p;
    char c = 0;

    __skip_space(in);

    p = *in;

    switch (*p) {
        case '=':
        /* fall through */
        case ',':
        /* fall through */
        case ';':
            return __TOKENIZER_RESULT_ILSEQ;
        break;
        case 0:
            return __TOKENIZER_RESULT_EOS;
        break;
        case '"':
            return __tokenizer_str(out, in);
        break;
    }

    *out = p;
    for (; __is_token(*p); p++);

    *in = p;
    if (*p) {
        __skip_space(in);
        c = **in;
        if (c != 0) {
            (*in)++;
        }
    }
    *p = 0;

    return __tokenizer_res_from_char(c);
}

#define HTTP_CN_INDEX_INCREMENT     8
#define HTTP_CN_KV_INCREMENT        8

static inline int __resize_array(void **also_ptr, void **array, size_t size, size_t *len, size_t revlen, size_t inc)
{
    void *n;

    if (*len > revlen)
        return 0;

    n = realloc(*array, size*(*len + inc));
    if (!n) {
        return -1;
    }

    memset(n + size * *len, 0, size * inc);

    *also_ptr = *array = n;
    *len += inc;

    return 0;
}

icecast_kva_t * util_parse_http_cn(const char *cnstr)
{
    icecast_kva_t *ret;
    char *in;
    int eos = 0;
    size_t indexphylen = HTTP_CN_INDEX_INCREMENT;
    size_t kvphylen = HTTP_CN_KV_INCREMENT;

    if (!cnstr || !*cnstr)
        return NULL;

    ret = calloc(1, sizeof(*ret));

    if (!ret)
        return NULL;

    ret->_tofree[0] = in = strdup(cnstr);
    ret->_tofree[1] = ret->index = calloc(HTTP_CN_INDEX_INCREMENT, sizeof(*(ret->index)));
    ret->_tofree[2] = ret->kv = calloc(HTTP_CN_KV_INCREMENT, sizeof(*(ret->kv)));
    if (!ret->_tofree[0] || !ret->_tofree[1] || !ret->_tofree[2]) {
        util_kva_free(ret);
        return NULL;
    }


    /* we have at minimum one token */
    ret->indexlen = 1;
    ret->kvlen = 1;

    while (!eos) {
        char *out = NULL;
        enum __tokenizer_result res = __tokenizer(&out, &in);

        switch (res) {
            case __TOKENIZER_RESULT_ILSEQ:
                ICECAST_LOG_DEBUG("Illegal byte sequence error from tokenizer.");
                util_kva_free(ret);
                return NULL;
            break;
            case __TOKENIZER_RESULT_EOS:
            /* fall through */
            case __TOKENIZER_RESULT_COMMA:
            /* fall through */
            case __TOKENIZER_RESULT_EQ:
            /* fall through */
            case __TOKENIZER_RESULT_SEMICOLON:
1227
                ICECAST_LOG_DDEBUG("OK from tokenizer.");
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
                /* no-op */
            break;
        }

        if (__resize_array(&(ret->_tofree[2]), (void**)&(ret->kv), sizeof(*(ret->kv)), &kvphylen, ret->kvlen, HTTP_CN_KV_INCREMENT) == -1 ||
            __resize_array(&(ret->_tofree[1]), (void**)&(ret->index), sizeof(*(ret->index)), &indexphylen, ret->indexlen, HTTP_CN_INDEX_INCREMENT) == -1) {
            util_kva_free(ret);
            return NULL;
        }

        if (ret->kv[ret->kvlen-1].key == NULL) {
            ret->kv[ret->kvlen-1].key = out;
        } else if (ret->kv[ret->kvlen-1].value == NULL) {
            ret->kv[ret->kvlen-1].value = out;
        } else {
            util_kva_free(ret);
            return NULL;
        }

        switch (res) {
            case __TOKENIZER_RESULT_EOS:
1249
                ICECAST_LOG_DDEBUG("End of string from tokenizer.");
1250 1251 1252 1253
                eos = 1;
                continue;
            break;
            case __TOKENIZER_RESULT_COMMA:
1254
                ICECAST_LOG_DDEBUG("Comma from tokenizer.");
1255 1256 1257 1258
                ret->index[ret->indexlen++] = ret->kvlen;
                ret->kvlen++;
            break;
            case __TOKENIZER_RESULT_EQ:
1259
                ICECAST_LOG_DDEBUG("Eq from tokenizer.");
1260 1261 1262
                /* no-op */
            break;
            case __TOKENIZER_RESULT_SEMICOLON:
1263
                ICECAST_LOG_DDEBUG("Semicolon from tokenizer.");
1264 1265 1266 1267 1268 1269 1270 1271
                ret->kvlen++;
            break;
            default:
                util_kva_free(ret);
                return NULL;
            break;
        }

1272
        ICECAST_LOG_DDEBUG("next...");
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    }

    return ret;
}

void util_kva_free(icecast_kva_t *kva)
{
    size_t i;

    if (!kva)
        return;

    for (i = 0; i < (sizeof(kva->_tofree)/sizeof(*(kva->_tofree))); i++)
        free(kva->_tofree[i]);

    free(kva);
}
1290

1291 1292
util_dict *util_dict_new(void)
{
1293
    return (util_dict *)calloc(1, sizeof(util_dict));
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
}

void util_dict_free(util_dict *dict)
{
    util_dict *next;

    while (dict) {
        next = dict->next;

        if (dict->key)
            free (dict->key);
        if (dict->val)
            free (dict->val);
        free (dict);

        dict = next;
    }
}

const char *util_dict_get(util_dict *dict, const char *key)
{
1315
    while (dict) {
1316
        if (dict->key && !strcmp(key, dict->key))
1317 1318 1319
            return dict->val;
        dict = dict->next;
    }
Michael Smith's avatar
Michael Smith committed
1320
    return NULL;
1321 1322 1323 1324
}

int util_dict_set(util_dict *dict, const char *key, const char *val)
{
1325
    util_dict *prev;
1326

1327
    if (!dict || !key) {
1328
        ICECAST_LOG_ERROR("NULL values passed to util_dict_set()");
1329 1330 1331
        return 0;
    }

1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    prev = NULL;
    while (dict) {
        if (!dict->key || !strcmp(dict->key, key))
            break;
        prev = dict;
        dict = dict->next;
    }

    if (!dict) {
        dict = util_dict_new();
        if (!dict) {
1343
            ICECAST_LOG_ERROR("unable to allocate new dictionary");
1344
            return 0;
1345
        }
1346 1347 1348
        if (prev)
            prev->next = dict;
    }
1349

1350 1351 1352 1353 1354 1355
    if (dict->key)
        free (dict->val);
    else if (!(dict->key = strdup(key))) {
        if (prev)
            prev->next = NULL;
        util_dict_free (dict);
1356

1357
        ICECAST_LOG_ERROR("unable to allocate new dictionary key");
1358
        return 0;
1359
    }
1360

1361 1362
    dict->val = strdup(val);
    if (!dict->val) {
1363
        ICECAST_LOG_ERROR("unable to allocate new dictionary value");
1364
        return 0;
1365
    }
1366

1367
    return 1;
1368 1369
}

1370 1371 1372
/* given a dictionary, URL-encode each val and stringify it in order as
   key=val&key=val... if val is set, or just key&key if val is NULL.
   TODO: Memory management needs overhaul. */
1373 1374
char *util_dict_urlencode(util_dict *dict, char delim)
{
1375 1376 1377 1378 1379 1380 1381 1382 1383
    char *res, *tmp;
    char *enc;
    int start = 1;

    for (res = NULL; dict; dict = dict->next) {
        /* encode key */
        if (!dict->key)
            continue;
        if (start) {
1384
            if (!(res = malloc(strlen(dict->key) + 1))) {
1385 1386
                return NULL;
            }
1387
            sprintf(res, "%s", dict->key);
1388 1389
            start = 0;
        } else {
1390
            if (!(tmp = realloc(res, strlen(res) + strlen(dict->key) + 2))) {
1391 1392 1393 1394
                free(res);
                return NULL;
            } else
                res = tmp;
1395
            sprintf(res + strlen(res), "%c%s", delim, dict->key);
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
        }

        /* encode value */
        if (!dict->val)
            continue;
        if (!(enc = util_url_escape(dict->val))) {
            free(res);
            return NULL;
        }

        if (!(tmp = realloc(res, strlen(res) + strlen(enc) + 2))) {
            free(enc);
            free(res);
            return NULL;
        } else
            res = tmp;
        sprintf(res + strlen(res), "=%s", enc);
        free(enc);
    }

    return res;
1417
}
Michael Smith's avatar
Michael Smith committed
1418

1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
#ifndef HAVE_LOCALTIME_R
struct tm *localtime_r (const time_t *timep, struct tm *result)
{
     static mutex_t localtime_lock;
     static int initialised = 0;
     struct tm *tm;

     if (initialised == 0)
     {
         thread_mutex_create (&localtime_lock);
         initialised = 1;
     }
     thread_mutex_lock (&localtime_lock);
     tm = localtime (timep);
     memcpy (result, tm, sizeof (*result));
     thread_mutex_unlock (&localtime_lock);
     return result;
}
#endif
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459


/* helper function for converting a passed string in one character set to another
 * we use libxml2 for this
 */
char *util_conv_string (const char *string, const char *in_charset, const char *out_charset)
{
    xmlCharEncodingHandlerPtr in, out;
    char *ret = NULL;

    if (string == NULL || in_charset == NULL || out_charset == NULL)
        return NULL;

    in  = xmlFindCharEncodingHandler (in_charset);
    out = xmlFindCharEncodingHandler (out_charset);

    if (in && out)
    {
        xmlBufferPtr orig = xmlBufferCreate ();
        xmlBufferPtr utf8 = xmlBufferCreate ();
        xmlBufferPtr conv = xmlBufferCreate ();

1460
        ICECAST_LOG_INFO("converting metadata from %s to %s", in_charset, out_charset);
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
        xmlBufferCCat (orig, string);
        if (xmlCharEncInFunc (in, utf8, orig) > 0)
        {
            xmlCharEncOutFunc (out, conv, NULL);
            if (xmlCharEncOutFunc (out, conv, utf8) >= 0)
                ret = strdup ((const char *)xmlBufferContent (conv));
        }
        xmlBufferFree (orig);
        xmlBufferFree (utf8);
        xmlBufferFree (conv);
    }
    xmlCharEncCloseFunc (in);
    xmlCharEncCloseFunc (out);

    return ret;
}

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491

int get_line(FILE *file, char *buf, size_t siz)
{
    if(fgets(buf, (int)siz, file)) {
        size_t len = strlen(buf);
        if(len > 0 && buf[len-1] == '\n') {
            buf[--len] = 0;
            if(len > 0 && buf[len-1] == '\r')
                buf[--len] = 0;
        }
        return 1;
    }
    return 0;
}
1492

1493
int util_replace_string(char **dst, const char *src)
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
{
    char *n;

    if (!dst)
        return -1;

    if (src) {
        n = strdup(src);
        if (!n)
            return -1;
    } else {
        n = NULL;
    }

    free(*dst);
    *dst = n;

    return 0;
}
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523

int util_strtolower(char *str)
{
    if (!str)
        return -1;

    for (; *str; str++)
        *str = tolower(*str);

    return 0;
}