util.c 26.3 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 9 10 11 12
 *  Copyright 2012-2015 Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>
 *
 *  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 21
#include <stdio.h>
#include <string.h>
22
#include <stdlib.h>
Jack Moffitt's avatar
Jack Moffitt committed
23

24 25 26 27 28 29 30
#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
31
#ifndef _WIN32
32
#include <sys/time.h>
Jack Moffitt's avatar
Jack Moffitt committed
33
#include <unistd.h>
34 35 36
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
37 38
#else
#include <windows.h>
Jack Moffitt's avatar
Jack Moffitt committed
39 40
#endif

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

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

#define CATMODULE "util"

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

57 58 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
/* 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
};


109 110 111 112 113 114 115 116 117
/* 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.
 */
118
int util_timed_wait_for_fd(sock_t fd, int timeout)
119 120 121 122 123 124 125 126 127 128 129
{
#ifdef HAVE_POLL
    struct pollfd ufds;

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

    return poll(&ufds, 1, timeout);
#else
    fd_set rfds;
130
    struct timeval tv, *p=NULL;
131 132 133 134

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

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

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

152
    config = config_get_config();
Michael Smith's avatar
Michael Smith committed
153 154
    header_timeout = config->header_timeout;
    config_release_config();
Jack Moffitt's avatar
Jack Moffitt committed
155

156 157 158
    read_bytes = 1;
    pos = 0;
    ret = 0;
Jack Moffitt's avatar
Jack Moffitt committed
159

160 161
    while ((read_bytes == 1) && (pos < (len - 1))) {
        read_bytes = 0;
Jack Moffitt's avatar
Jack Moffitt committed
162

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

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

187
    return ret;
Jack Moffitt's avatar
Jack Moffitt committed
188 189
}

190
char *util_get_extension(const char *path) {
191 192 193 194 195 196 197 198
    char *ext = strrchr(path, '.');

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

199
int util_check_valid_extension(const char *uri) {
200
    const char    *p2;
201

202 203 204 205 206 207 208 209 210 211 212 213
    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;
214
    }
215 216

    return UNKNOWN_CONTENT;
217
}
Jack Moffitt's avatar
Jack Moffitt committed
218

219 220 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
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;
        }
251

252 253 254 255 256 257 258
        dir = 0;
        path++;
    }

    return 1;
}

259 260 261 262 263 264 265 266 267 268 269 270 271
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;
    }
}

272
char *util_get_path_from_normalised_uri(const char *uri) {
273
    char *fullpath;
Michael Smith's avatar
Michael Smith committed
274 275
    char *webroot;
    ice_config_t *config = config_get_config();
276

Michael Smith's avatar
Michael Smith committed
277 278 279
    webroot = config->webroot_dir;

    fullpath = malloc(strlen(uri) + strlen(webroot) + 1);
280 281 282
    if (fullpath)
        sprintf (fullpath, "%s%s", webroot, uri);
    config_release_config();
283 284 285 286

    return fullpath;
}

287
char *util_url_escape (const char *src)
288
{
289 290
    size_t len;
    char *dst;
291
    unsigned char *source = (unsigned char *)src;
292
    size_t i, j;
293

294 295 296 297 298 299 300 301
    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++) {
302 303
        if(safechars[source[i]]) {
            dst[j++] = source[i];
304 305 306 307
        } else {
            dst[j++] = '%';
            dst[j++] = hexchars[(source[i] >> 4) & 0x0F];
            dst[j++] = hexchars[ source[i]       & 0x0F];
308 309 310 311 312 313 314
        }
    }

    dst[j] = 0;
    return dst;
}

315
char *util_url_unescape (const char *src)
316 317
{
    int len = strlen(src);
318
    char *decoded;
319
    int i;
320
    char *dst;
321 322
    int done = 0;

323
    decoded = calloc(1, len + 1);
324

325
    dst = decoded;
326

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

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

    *dst = 0; /* null terminator */

360 361 362 363 364 365 366 367
    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.
 */
368
char *util_normalise_uri(const char *uri) {
369
    char *path;
370 371 372
#ifdef _WIN32
    size_t len;
#endif
373 374 375 376

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

377
    path = util_url_unescape(uri);
378 379

    if(path == NULL) {
380
        ICECAST_LOG_WARN("Error decoding URI: %s\n", uri);
381 382 383
        return NULL;
    }

384 385 386 387 388 389
#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

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

Michael Smith's avatar
Michael Smith committed
400 401 402 403 404
char *util_bin_to_hex(unsigned char *data, int len)
{
    char *hex = malloc(len*2 + 1);
    int i;

405
    for (i = 0; i < len; i++) {
Michael Smith's avatar
Michael Smith committed
406 407 408 409 410 411 412 413 414
        hex[i*2] = hexchars[(data[i]&0xf0) >> 4];
        hex[i*2+1] = hexchars[data[i]&0x0f];
    }

    hex[len*2] = 0;

    return hex;
}

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

    while(len > 0) {
422
        chunk = (len > 3) ? 3 : len;
423 424
        *out++ = base64table[(*data & 0xFC)>>2];
        *out++ = base64table[((*data & 0x03)<<4) | ((*(data+1) & 0xF0) >> 4)];
425

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

    return result;
}

448
char *util_base64_decode(const char *data)
449
{
450 451
    const unsigned char *input = (const unsigned char *)data;
    int len = strlen (data);
452 453 454 455 456 457 458 459 460 461 462
    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 */
        }

463 464 465 466
        vals[0] = base64decode[*input++];
        vals[1] = base64decode[*input++];
        vals[2] = base64decode[*input++];
        vals[3] = base64decode[*input++];
467 468

        if(vals[0] < 0 || vals[1] < 0 || vals[2] < -1 || vals[3] < -1) {
469
            len -= 4;
470 471 472 473
            continue;
        }

        *out++ = vals[0]<<2 | vals[1]>>4;
474 475 476 477
        /* 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. */
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        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;
}

495 496 497 498 499 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
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;
}

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
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;
}
553

554 555 556 557 558 559 560 561 562 563 564 565 566 567
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);
}

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
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;
}

597
/* TODO, FIXME: handle memory allocation errors better. */
598
static inline void   _build_headers_loop(char **ret, size_t *len, ice_config_http_header_t *header, int status) {
599 600 601
    size_t headerlen;
    const char *name;
    const char *value;
602 603
    char *r = *ret;
    char *n;
604

605 606 607 608 609 610 611 612
    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 */
613
        name = header->name;
614 615

        /* handle type of the header */
616
        value = NULL;
617 618 619 620 621
        switch (header->type) {
            case HTTP_HEADER_TYPE_STATIC:
                value = header->value;
                break;
        }
622

623 624 625 626
        /* check data */
        if (!name || !value)
            continue;

627
        /* append the header to the buffer */
628
        headerlen = strlen(name) + strlen(value) + 4;
629
        *len += headerlen;
630 631 632 633 634 635 636 637 638 639 640
        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;
        }
641
    } while ((header = header->next));
642 643 644 645 646 647 648 649 650 651 652 653 654
    *ret = r;
}
static inline char * _build_headers(int status, ice_config_t *config, source_t *source) {
    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;

655
    _build_headers_loop(&ret, &len, config->http_headers, status);
656
    if (mountproxy && mountproxy->http_headers)
657
        _build_headers_loop(&ret, &len, mountproxy->http_headers, status);
658

659 660 661
    return ret;
}

662 663 664 665
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,
666
        const char * datablock,
667
        struct source_tag * source, struct _client_tag * client) {
668 669 670 671
    const char * http_version = "1.0";
    ice_config_t *config;
    time_t now;
    struct tm result;
672 673
    struct tm *gmtime_result;
    char currenttime_buffer[80];
674 675 676
    char status_buffer[80];
    char contenttype_buffer[80];
    ssize_t ret;
677
    char * extra_headers;
678
    const char *connection_header = "Close";
679 680 681 682

    if (!out)
        return -1;

683 684 685 686 687 688 689 690
    if (client) {
        switch (client->reuse) {
            case ICECAST_REUSE_CLOSE:      connection_header = "Close"; break;
            case ICECAST_REUSE_KEEPALIVE:  connection_header = "Keep-Alive"; break;
            case ICECAST_REUSE_UPGRADETLS: connection_header = "Upgrade"; break;
        }
    }

691 692 693 694 695 696 697 698 699 700 701 702 703
    if (offset == -1)
        offset = strlen (out);

    out += offset;
    len -= offset;

    if (status == -1)
    {
        status_buffer[0] = '\0';
    }
    else
    {
        if (!statusmsg)
704 705 706
        {
            switch (status)
            {
707
                case 100: statusmsg = "Continue"; http_version = "1.1"; break;
708
                case 101: statusmsg = "Switching Protocols"; http_version = "1.1"; break;
709 710 711 712 713 714 715
                case 200: statusmsg = "OK"; break;
                case 206: statusmsg = "Partial Content"; http_version = "1.1"; break;
                case 400: statusmsg = "Bad Request"; break;
                case 401: statusmsg = "Authentication Required"; break;
                case 403: statusmsg = "Forbidden"; break;
                case 404: statusmsg = "File Not Found"; break;
                case 416: statusmsg = "Request Range Not Satisfiable"; break;
716
                case 426: statusmsg = "Upgrade Required"; http_version = "1.1"; break;
717
                case 501: statusmsg = "Unimplemented"; break;
718 719 720 721
                default:  statusmsg = "(unknown status code)"; break;
            }
        }
        snprintf (status_buffer, sizeof (status_buffer), "HTTP/%s %d %s\r\n", http_version, status, statusmsg);
722 723 724 725
    }

    if (contenttype)
    {
726
        if (charset)
727
            snprintf (contenttype_buffer, sizeof (contenttype_buffer), "Content-Type: %s; charset=%s\r\n",
728 729
                                                                       contenttype, charset);
        else
730 731 732 733 734 735 736 737 738
            snprintf (contenttype_buffer, sizeof (contenttype_buffer), "Content-Type: %s\r\n",
                                                                       contenttype);
    }
    else
    {
        contenttype_buffer[0] = '\0';
    }

    time(&now);
739 740 741 742 743 744 745 746 747 748
#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)
749
        strftime(currenttime_buffer, sizeof(currenttime_buffer), "Date: %a, %d %b %Y %X GMT\r\n", gmtime_result);
750 751
    else
        currenttime_buffer[0] = '\0';
752 753

    config = config_get_config();
754
    extra_headers = _build_headers(status, config, source);
755
    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",
756
                              status_buffer,
757
                              config->server_id,
758
                              connection_header,
759
                              (client && client->admin_command == ADMIN_COMMAND_ERROR ?
760
                                                "GET, SOURCE" : "GET"),
761
                              (config->tls_ok ? "Upgrade: TLS/1.0\r\n" : ""),
762 763 764
                              currenttime_buffer,
                              contenttype_buffer,
                              (status == 401 ? "WWW-Authenticate: Basic realm=\"Icecast2 Server\"\r\n" : ""),
765 766 767
                              (cache     ? "" : "Cache-Control: no-cache\r\n"
                                                "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n"
                                                "Pragma: no-cache\r\n"),
768
                              extra_headers,
769 770
                              (datablock ? "\r\n" : ""),
                              (datablock ? datablock : ""));
771
    free(extra_headers);
772 773 774 775 776 777
    config_release_config();

    return ret;
}


778 779
util_dict *util_dict_new(void)
{
780
    return (util_dict *)calloc(1, sizeof(util_dict));
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
}

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)
{
802
    while (dict) {
803
        if (dict->key && !strcmp(key, dict->key))
804 805 806
            return dict->val;
        dict = dict->next;
    }
Michael Smith's avatar
Michael Smith committed
807
    return NULL;
808 809 810 811
}

int util_dict_set(util_dict *dict, const char *key, const char *val)
{
812
    util_dict *prev;
813

814
    if (!dict || !key) {
815
        ICECAST_LOG_ERROR("NULL values passed to util_dict_set()");
816 817 818
        return 0;
    }

819 820 821 822 823 824 825 826 827 828 829
    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) {
830
            ICECAST_LOG_ERROR("unable to allocate new dictionary");
831
            return 0;
832
        }
833 834 835
        if (prev)
            prev->next = dict;
    }
836

837 838 839 840 841 842
    if (dict->key)
        free (dict->val);
    else if (!(dict->key = strdup(key))) {
        if (prev)
            prev->next = NULL;
        util_dict_free (dict);
843

844
        ICECAST_LOG_ERROR("unable to allocate new dictionary key");
845
        return 0;
846
    }
847

848 849
    dict->val = strdup(val);
    if (!dict->val) {
850
        ICECAST_LOG_ERROR("unable to allocate new dictionary value");
851
        return 0;
852
    }
853

854
    return 1;
855 856
}

857 858 859
/* 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. */
860 861
char *util_dict_urlencode(util_dict *dict, char delim)
{
862 863 864 865 866 867 868 869 870
    char *res, *tmp;
    char *enc;
    int start = 1;

    for (res = NULL; dict; dict = dict->next) {
        /* encode key */
        if (!dict->key)
            continue;
        if (start) {
871
            if (!(res = malloc(strlen(dict->key) + 1))) {
872 873
                return NULL;
            }
874
            sprintf(res, "%s", dict->key);
875 876
            start = 0;
        } else {
877
            if (!(tmp = realloc(res, strlen(res) + strlen(dict->key) + 2))) {
878 879 880 881
                free(res);
                return NULL;
            } else
                res = tmp;
882
            sprintf(res + strlen(res), "%c%s", delim, dict->key);
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
        }

        /* 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;
904
}
Michael Smith's avatar
Michael Smith committed
905

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
#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
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946


/* 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 ();

947
        ICECAST_LOG_INFO("converting metadata from %s to %s", in_charset, out_charset);
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
        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;
}

965 966 967 968 969 970 971 972 973 974 975 976 977 978

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;
}