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

13
/* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- */
14 15 16 17
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

Jack Moffitt's avatar
Jack Moffitt committed
18 19
#include <stdio.h>
#include <stdlib.h>
20
#include <errno.h>
Jack Moffitt's avatar
Jack Moffitt committed
21
#include <string.h>
22 23 24
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
25 26
#include <sys/types.h>
#include <sys/stat.h>
27 28

#ifndef _WIN32
Jack Moffitt's avatar
Jack Moffitt committed
29 30
#include <sys/socket.h>
#include <netinet/in.h>
31
#else
32
#include <winsock2.h>
33 34
#define snprintf _snprintf
#define strcasecmp stricmp
35
#define strncasecmp strnicmp
36
#endif
Jack Moffitt's avatar
Jack Moffitt committed
37

38
#include "compat.h"
Jack Moffitt's avatar
Jack Moffitt committed
39

Karl Heyes's avatar
Karl Heyes committed
40 41 42 43
#include "thread/thread.h"
#include "avl/avl.h"
#include "net/sock.h"
#include "httpp/httpp.h"
Jack Moffitt's avatar
Jack Moffitt committed
44

45
#include "cfgfile.h"
Jack Moffitt's avatar
Jack Moffitt committed
46 47 48 49 50 51 52
#include "global.h"
#include "util.h"
#include "connection.h"
#include "refbuf.h"
#include "client.h"
#include "stats.h"
#include "logging.h"
53
#include "xslt.h"
54
#include "fserve.h"
55
#include "sighandler.h"
56 57

#include "yp.h"
Jack Moffitt's avatar
Jack Moffitt committed
58
#include "source.h"
Michael Smith's avatar
Michael Smith committed
59
#include "format.h"
60
#include "format_mp3.h"
Michael Smith's avatar
Michael Smith committed
61
#include "event.h"
62
#include "admin.h"
Michael Smith's avatar
Michael Smith committed
63
#include "auth.h"
Jack Moffitt's avatar
Jack Moffitt committed
64 65 66

#define CATMODULE "connection"

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/* Two different major types of source authentication.
   Shoutcast style is used only by the Shoutcast DSP
   and is a crazy version of HTTP.  It looks like :
     Source Client -> Connects to port + 1
     Source Client -> sends encoder password (plaintext)\r\n
     Icecast -> reads encoder password, if ok, sends OK2\r\n, else disconnects
     Source Client -> reads OK2\r\n, then sends http-type request headers
                      that contain the stream details (icy-name, etc..)
     Icecast -> reads headers, stores them
     Source Client -> starts sending MP3 data
     Source Client -> periodically updates metadata via admin.cgi call

   Icecast auth style uses HTTP and Basic Authorization.
*/
#define SHOUTCAST_SOURCE_AUTH 1
#define ICECAST_SOURCE_AUTH 0

84 85 86 87 88
typedef struct client_queue_tag {
    client_t *client;
    int offset;
    int stream_offset;
    int shoutcast;
89
    char *shoutcast_mount;
90 91
    struct client_queue_tag *next;
} client_queue_t;
Jack Moffitt's avatar
Jack Moffitt committed
92 93

typedef struct _thread_queue_tag {
94 95
    thread_type *thread_id;
    struct _thread_queue_tag *next;
Jack Moffitt's avatar
Jack Moffitt committed
96 97
} thread_queue_t;

98 99 100 101 102 103 104 105
typedef struct
{
    char *filename;
    time_t file_recheck;
    time_t file_mtime;
    avl_tree *contents;
} cache_file_contents;

Jack Moffitt's avatar
Jack Moffitt committed
106
static mutex_t _connection_mutex;
107
static volatile unsigned long _current_id = 0;
Jack Moffitt's avatar
Jack Moffitt committed
108
static int _initialized = 0;
109
static thread_type *tid;
Jack Moffitt's avatar
Jack Moffitt committed
110

111 112 113 114
static volatile client_queue_t *_req_queue = NULL, **_req_queue_tail = &_req_queue;
static volatile client_queue_t *_con_queue = NULL, **_con_queue_tail = &_con_queue;
static mutex_t _con_queue_mutex;
static mutex_t _req_queue_mutex;
Jack Moffitt's avatar
Jack Moffitt committed
115

116 117 118 119 120
static int ssl_ok;
#ifdef HAVE_OPENSSL
static SSL_CTX *ssl_ctx;
#endif

121 122 123
/* filtering client connection based on IP */
cache_file_contents banned_ip, allowed_ip;

124
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
125 126 127

static void *_handle_connection(void *arg);

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
static int compare_ip (void *arg, void *a, void *b)
{
    const char *ip = (const char *)a;
    const char *pattern = (const char *)b;

    return strcmp (pattern, ip);
}


static int free_filtered_ip (void*x)
{
    free (x);
    return 1;
}


Jack Moffitt's avatar
Jack Moffitt committed
144 145
void connection_initialize(void)
{
146 147 148
    if (_initialized) return;
    
    thread_mutex_create(&_connection_mutex);
149 150
    thread_mutex_create(&_con_queue_mutex);
    thread_mutex_create(&_req_queue_mutex);
151
    thread_mutex_create(&move_clients_mutex);
152
    thread_rwlock_create(&_source_shutdown_rwlock);
153
    thread_cond_create(&global.shutdown_cond);
154 155 156 157
    _req_queue = NULL;
    _req_queue_tail = &_req_queue;
    _con_queue = NULL;
    _con_queue_tail = &_con_queue;
Jack Moffitt's avatar
Jack Moffitt committed
158

159 160 161 162 163 164
    banned_ip.contents = NULL;
    banned_ip.file_mtime = 0;

    allowed_ip.contents = NULL;
    allowed_ip.file_mtime = 0;

165
    _initialized = 1;
Jack Moffitt's avatar
Jack Moffitt committed
166 167 168 169
}

void connection_shutdown(void)
{
170 171
    if (!_initialized) return;
    
172 173 174
#ifdef HAVE_OPENSSL
    SSL_CTX_free (ssl_ctx);
#endif
175 176 177
    if (banned_ip.contents)  avl_tree_free (banned_ip.contents, free_filtered_ip);
    if (allowed_ip.contents) avl_tree_free (allowed_ip.contents, free_filtered_ip);
 
178
    thread_cond_destroy(&global.shutdown_cond);
179
    thread_rwlock_destroy(&_source_shutdown_rwlock);
180 181
    thread_mutex_destroy(&_con_queue_mutex);
    thread_mutex_destroy(&_req_queue_mutex);
182
    thread_mutex_destroy(&_connection_mutex);
183
    thread_mutex_destroy(&move_clients_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
184

185
    _initialized = 0;
Jack Moffitt's avatar
Jack Moffitt committed
186 187 188 189
}

static unsigned long _next_connection_id(void)
{
190
    unsigned long id;
Jack Moffitt's avatar
Jack Moffitt committed
191

192 193 194
    thread_mutex_lock(&_connection_mutex);
    id = _current_id++;
    thread_mutex_unlock(&_connection_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
195

196
    return id;
Jack Moffitt's avatar
Jack Moffitt committed
197 198
}

199 200

#ifdef HAVE_OPENSSL
201
static void get_ssl_certificate (ice_config_t *config)
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
{
    SSL_METHOD *method;
    ssl_ok = 0;

    SSL_load_error_strings();                /* readable error messages */
    SSL_library_init();                      /* initialize library */

    method = SSLv23_server_method();
    ssl_ctx = SSL_CTX_new (method);

    do
    {
        if (config->cert_file == NULL)
            break;
        if (SSL_CTX_use_certificate_file (ssl_ctx, config->cert_file, SSL_FILETYPE_PEM) <= 0)
        {
            WARN1 ("Invalid cert file %s", config->cert_file);
            break;
        }
        if (SSL_CTX_use_PrivateKey_file (ssl_ctx, config->cert_file, SSL_FILETYPE_PEM) <= 0)
        {
            WARN1 ("Invalid private key file %s", config->cert_file);
            break;
        }
        if (!SSL_CTX_check_private_key (ssl_ctx))
        {
228
            ERROR1 ("Invalid %s - Private key does not match cert public key", config->cert_file);
229 230 231 232
            break;
        }
        ssl_ok = 1;
        INFO1 ("SSL certificate found at %s", config->cert_file);
233
        return;
234
    } while (0);
235
    INFO0 ("No SSL capability on any configured ports");
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
}


/* handlers for reading and writing a connection_t when there is ssl
 * configured on the listening port
 */
static int connection_read_ssl (connection_t *con, void *buf, size_t len)
{
    int bytes = SSL_read (con->ssl, buf, len);

    if (bytes < 0)
    {
        switch (SSL_get_error (con->ssl, bytes))
        {
            case SSL_ERROR_WANT_READ:
            case SSL_ERROR_WANT_WRITE:
                return -1;
        }
        con->error = 1;
    }
    return bytes;
}

static int connection_send_ssl (connection_t *con, const void *buf, size_t len)
{
    int bytes = SSL_write (con->ssl, buf, len);

    if (bytes < 0)
    {
        switch (SSL_get_error (con->ssl, bytes))
        {
            case SSL_ERROR_WANT_READ:
            case SSL_ERROR_WANT_WRITE:
                return -1;
        }
        con->error = 1;
    }
    else
        con->sent_bytes += bytes;
    return bytes;
}
#else

/* SSL not compiled in, so at least log it */
280
static void get_ssl_certificate (ice_config_t *config)
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
{
    ssl_ok = 0;
    INFO0 ("No SSL capability");
}
#endif /* HAVE_OPENSSL */


/* handlers (default) for reading and writing a connection_t, no encrpytion
 * used just straight access to the socket
 */
static int connection_read (connection_t *con, void *buf, size_t len)
{
    int bytes = sock_read_bytes (con->sock, buf, len);
    if (bytes == 0)
        con->error = 1;
    if (bytes == -1 && !sock_recoverable (sock_error()))
        con->error = 1;
    return bytes;
}

static int connection_send (connection_t *con, const void *buf, size_t len)
{
    int bytes = sock_write_bytes (con->sock, buf, len);
    if (bytes < 0)
    {
        if (!sock_recoverable (sock_error()))
            con->error = 1;
    }
    else
        con->sent_bytes += bytes;
    return bytes;
}


315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
/* function to handle the re-populating of the avl tree containing IP addresses
 * for deciding whether a connection of an incoming request is to be dropped.
 */
static void recheck_ip_file (cache_file_contents *cache)
{
    time_t now = time(NULL);
    if (now >= cache->file_recheck)
    {
        struct stat file_stat;
        FILE *file = NULL;
        int count = 0;
        avl_tree *new_ips;
        char line [MAX_LINE_LEN];

        cache->file_recheck = now + 10;
        if (cache->filename == NULL)
        {
            if (cache->contents)
            {
                avl_tree_free (cache->contents, free_filtered_ip);
                cache->contents = NULL;
            }
            return;
        }
        if (stat (cache->filename, &file_stat) < 0)
        {
            WARN2 ("failed to check status of \"%s\": %s", cache->filename, strerror(errno));
            return;
        }
        if (file_stat.st_mtime == cache->file_mtime)
            return; /* common case, no update to file */

        cache->file_mtime = file_stat.st_mtime;

        file = fopen (cache->filename, "r");
        if (file == NULL)
        {
            WARN2("Failed to open file \"%s\": %s", cache->filename, strerror (errno));
            return;
        }

        new_ips = avl_tree_new (compare_ip, NULL);

        while (get_line (file, line, MAX_LINE_LEN))
        {
            char *str;
            if(!line[0] || line[0] == '#')
                continue;
            count++;
            str = strdup (line);
            if (str)
                avl_insert (new_ips, str);
        }
        fclose (file);
        INFO2 ("%d entries read from file \"%s\"", count, cache->filename);

        if (cache->contents) avl_tree_free (cache->contents, free_filtered_ip);
        cache->contents = new_ips;
    }
}


/* return 0 if the passed ip address is not to be handled by icecast, non-zero otherwise */
static int accept_ip_address (char *ip)
{
    void *result;

    recheck_ip_file (&banned_ip);
    recheck_ip_file (&allowed_ip);

    if (banned_ip.contents)
    {
        if (avl_get_by_key (banned_ip.contents, ip, &result) == 0)
        {
            DEBUG1 ("%s is banned", ip);
            return 0;
        }
    }
    if (allowed_ip.contents)
    {
        if (avl_get_by_key (allowed_ip.contents, ip, &result) == 0)
        {
            DEBUG1 ("%s is allowed", ip);
            return 1;
        }
        else
        {
            DEBUG1 ("%s is not allowed", ip);
            return 0;
        }
    }
    return 1;
}


410 411
connection_t *connection_create (sock_t sock, sock_t serversock, char *ip)
{
412
    connection_t *con;
413 414 415 416 417 418 419 420
    con = (connection_t *)calloc(1, sizeof(connection_t));
    if (con)
    {
        con->sock = sock;
        con->serversock = serversock;
        con->con_time = time(NULL);
        con->id = _next_connection_id();
        con->ip = ip;
421 422
        con->read = connection_read;
        con->send = connection_send;
423
    }
Michael Smith's avatar
Michael Smith committed
424

425
    return con;
426 427
}

428 429 430 431 432 433 434 435 436 437 438 439 440
/* prepare connection for interacting over a SSL connection
 */
void connection_uses_ssl (connection_t *con)
{
#ifdef HAVE_OPENSSL
    con->read = connection_read_ssl;
    con->send = connection_send_ssl;
    con->ssl = SSL_new (ssl_ctx);
    SSL_set_accept_state (con->ssl);
    SSL_set_fd (con->ssl, con->sock);
#endif
}

441
static sock_t wait_for_serversock(int timeout)
442 443
{
#ifdef HAVE_POLL
444
    struct pollfd ufds [global.server_sockets];
445 446 447 448 449 450 451 452 453 454
    int i, ret;

    for(i=0; i < global.server_sockets; i++) {
        ufds[i].fd = global.serversock[i];
        ufds[i].events = POLLIN;
        ufds[i].revents = 0;
    }

    ret = poll(ufds, global.server_sockets, timeout);
    if(ret < 0) {
455
        return SOCK_ERROR;
456 457
    }
    else if(ret == 0) {
458
        return SOCK_ERROR;
459 460
    }
    else {
461
        int dst;
462
        for(i=0; i < global.server_sockets; i++) {
463
            if(ufds[i].revents & POLLIN)
464
                return ufds[i].fd;
465 466 467 468
            if(ufds[i].revents & (POLLHUP|POLLERR|POLLNVAL))
            {
                if (ufds[i].revents & (POLLHUP|POLLERR))
                {
469
                    sock_close (global.serversock[i]);
470 471
                    WARN0("Had to close a listening socket");
                }
472
                global.serversock[i] = SOCK_ERROR;
473
            }
474
        }
475 476 477
        /* remove any closed sockets */
        for(i=0, dst=0; i < global.server_sockets; i++)
        {
478
            if (global.serversock[i] == SOCK_ERROR)
479 480 481 482 483 484
                continue;
            if (i!=dst)
                global.serversock[dst] = global.serversock[i];
            dst++;
        }
        global.server_sockets = dst;
485
        return SOCK_ERROR;
486 487 488 489 490
    }
#else
    fd_set rfds;
    struct timeval tv, *p=NULL;
    int i, ret;
491
    sock_t max = SOCK_ERROR;
492 493 494 495 496

    FD_ZERO(&rfds);

    for(i=0; i < global.server_sockets; i++) {
        FD_SET(global.serversock[i], &rfds);
497
        if (max == SOCK_ERROR || global.serversock[i] > max)
498 499 500 501 502
            max = global.serversock[i];
    }

    if(timeout >= 0) {
        tv.tv_sec = timeout/1000;
503
        tv.tv_usec = (timeout % 1000) * 1000;
504 505 506 507 508
        p = &tv;
    }

    ret = select(max+1, &rfds, NULL, NULL, p);
    if(ret < 0) {
509
        return SOCK_ERROR;
510 511
    }
    else if(ret == 0) {
512
        return SOCK_ERROR;
513 514 515 516 517 518
    }
    else {
        for(i=0; i < global.server_sockets; i++) {
            if(FD_ISSET(global.serversock[i], &rfds))
                return global.serversock[i];
        }
519
        return SOCK_ERROR; /* Should be impossible, stop compiler warnings */
520 521 522 523
    }
#endif
}

Jack Moffitt's avatar
Jack Moffitt committed
524 525
static connection_t *_accept_connection(void)
{
526
    sock_t sock, serversock; 
527
    char *ip;
Jack Moffitt's avatar
Jack Moffitt committed
528

529
    serversock = wait_for_serversock(100);
530
    if (serversock == SOCK_ERROR)
531
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
532

533 534
    /* malloc enough room for a full IP address (including ipv6) */
    ip = (char *)malloc(MAX_ADDR_LEN);
Jack Moffitt's avatar
Jack Moffitt committed
535

536
    sock = sock_accept(serversock, ip, MAX_ADDR_LEN);
537
    if (sock != SOCK_ERROR)
538
    {
539
        connection_t *con = NULL;
540 541 542
        /* Make any IPv4 mapped IPv6 address look like a normal IPv4 address */
        if (strncmp (ip, "::ffff:", 7) == 0)
            memmove (ip, ip+7, strlen (ip+7)+1);
Jack Moffitt's avatar
Jack Moffitt committed
543

544 545
        if (accept_ip_address (ip))
            con = connection_create (sock, serversock, ip);
546 547 548 549 550 551 552 553 554 555 556
        if (con)
            return con;
        sock_close (sock);
    }
    else
    {
        if (!sock_recoverable(sock_error()))
        {
            WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
            thread_sleep (500000);
        }
557 558 559
    }
    free(ip);
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
560 561 562
}


563 564 565 566 567
/* add client to connection queue. At this point some header information
 * has been collected, so we now pass it onto the connection thread for
 * further processing
 */
static void _add_connection (client_queue_t *node)
Jack Moffitt's avatar
Jack Moffitt committed
568
{
569 570 571 572
    thread_mutex_lock (&_con_queue_mutex);
    *_con_queue_tail = node;
    _con_queue_tail = (volatile client_queue_t **)&node->next;
    thread_mutex_unlock (&_con_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
573 574 575
}


576 577 578 579 580 581
/* this returns queued clients for the connection thread. headers are
 * already provided, but need to be parsed.
 */
static client_queue_t *_get_connection(void)
{
    client_queue_t *node = NULL;
Jack Moffitt's avatar
Jack Moffitt committed
582

583 584 585 586 587 588 589 590 591
    /* common case, no new connections so don't bother taking locks */
    if (_con_queue)
    {
        thread_mutex_lock (&_con_queue_mutex);
        node = (client_queue_t *)_con_queue;
        _con_queue = node->next;
        if (_con_queue == NULL)
            _con_queue_tail = &_con_queue;
        thread_mutex_unlock (&_con_queue_mutex);
592
        node->next = NULL;
593
    }
594 595
    return node;
}
Jack Moffitt's avatar
Jack Moffitt committed
596 597


598
/* run along queue checking for any data that has come in or a timeout */
599
static void process_request_queue (void)
600 601 602 603 604
{
    client_queue_t **node_ref = (client_queue_t **)&_req_queue;
    ice_config_t *config = config_get_config ();
    int timeout = config->header_timeout;
    config_release_config();
Jack Moffitt's avatar
Jack Moffitt committed
605

606 607 608 609 610 611
    while (*node_ref)
    {
        client_queue_t *node = *node_ref;
        client_t *client = node->client;
        int len = PER_CLIENT_REFBUF_SIZE - 1 - node->offset;
        char *buf = client->refbuf->data + node->offset;
Jack Moffitt's avatar
Jack Moffitt committed
612

613 614 615 616 617 618 619
        if (len > 0)
        {
            if (client->con->con_time + timeout <= time(NULL))
                len = 0;
            else
                len = client_read_bytes (client, buf, len);
        }
Jack Moffitt's avatar
Jack Moffitt committed
620

621 622 623 624 625
        if (len > 0)
        {
            int pass_it = 1;
            char *ptr;

626 627
            /* handle \n, \r\n and nsvcap which for some strange reason has
             * EOL as \r\r\n */
628 629 630 631 632 633 634
            node->offset += len;
            client->refbuf->data [node->offset] = '\000';
            do
            {
                if (node->shoutcast == 1)
                {
                    /* password line */
635 636
                    if (strstr (client->refbuf->data, "\r\r\n") != NULL)
                        break;
637 638 639 640 641 642 643
                    if (strstr (client->refbuf->data, "\r\n") != NULL)
                        break;
                    if (strstr (client->refbuf->data, "\n") != NULL)
                        break;
                }
                /* stream_offset refers to the start of any data sent after the
                 * http style headers, we don't want to lose those */
644 645 646 647 648 649
                ptr = strstr (client->refbuf->data, "\r\r\n\r\r\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+6) - client->refbuf->data;
                    break;
                }
650 651 652 653 654 655 656 657 658 659 660 661 662 663
                ptr = strstr (client->refbuf->data, "\r\n\r\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+4) - client->refbuf->data;
                    break;
                }
                ptr = strstr (client->refbuf->data, "\n\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+2) - client->refbuf->data;
                    break;
                }
                pass_it = 0;
            } while (0);
Jack Moffitt's avatar
Jack Moffitt committed
664

665 666
            if (pass_it)
            {
667
                thread_mutex_lock (&_req_queue_mutex);
668 669 670 671
                if ((client_queue_t **)_req_queue_tail == &(node->next))
                    _req_queue_tail = (volatile client_queue_t **)node_ref;
                *node_ref = node->next;
                node->next = NULL;
672
                thread_mutex_unlock (&_req_queue_mutex);
673
                _add_connection (node);
674
                continue;
675 676 677 678 679 680
            }
        }
        else
        {
            if (len == 0 || client->con->error)
            {
681
                thread_mutex_lock (&_req_queue_mutex);
682 683 684
                if ((client_queue_t **)_req_queue_tail == &node->next)
                    _req_queue_tail = (volatile client_queue_t **)node_ref;
                *node_ref = node->next;
685
                thread_mutex_unlock (&_req_queue_mutex);
686 687 688 689 690 691
                client_destroy (client);
                free (node);
                continue;
            }
        }
        node_ref = &node->next;
692
    }
Jack Moffitt's avatar
Jack Moffitt committed
693 694
}

695

696 697 698 699 700 701 702 703 704
/* add node to the queue of requests. This is where the clients are when
 * initial http details are read.
 */
static void _add_request_queue (client_queue_t *node)
{
    thread_mutex_lock (&_req_queue_mutex);
    *_req_queue_tail = node;
    _req_queue_tail = (volatile client_queue_t **)&node->next;
    thread_mutex_unlock (&_req_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
705 706
}

707

Jack Moffitt's avatar
Jack Moffitt committed
708 709
void connection_accept_loop(void)
{
710
    connection_t *con;
711 712 713 714 715
    ice_config_t *config;

    config = config_get_config ();
    get_ssl_certificate (config);
    config_release_config ();
Jack Moffitt's avatar
Jack Moffitt committed
716

717
    tid = thread_create ("connection thread", _handle_connection, NULL, THREAD_ATTACHED);
Jack Moffitt's avatar
Jack Moffitt committed
718

719 720
    while (global.running == ICE_RUNNING)
    {
721 722 723
        con = _accept_connection();

        if (con)
724
        {
725 726 727
            client_queue_t *node;
            ice_config_t *config;
            client_t *client = NULL;
728
            listener_t *listener;
729

730 731 732 733
            global_lock();
            if (client_create (&client, con, NULL) < 0)
            {
                global_unlock();
734
                client_send_403 (client, "Icecast connection limit reached");
735 736
                /* don't be too eager as this is an imposed hard limit */
                thread_sleep (400000);
737 738 739
                continue;
            }
            global_unlock();
740

741 742 743 744 745 746 747 748 749 750 751 752
            /* setup client for reading incoming http */
            client->refbuf->data [PER_CLIENT_REFBUF_SIZE-1] = '\000';

            node = calloc (1, sizeof (client_queue_t));
            if (node == NULL)
            {
                client_destroy (client);
                continue;
            }
            node->client = client;

            config = config_get_config();
753 754 755
            listener = config_get_listen_sock (config, client->con);

            if (listener)
756
            {
757 758 759 760
                if (listener->shoutcast_compat)
                    node->shoutcast = 1;
                if (listener->ssl && ssl_ok)
                    connection_uses_ssl (client->con);
761 762
                if (listener->shoutcast_mount)
                    node->shoutcast_mount = strdup (listener->shoutcast_mount);
763
            }
764
            config_release_config();
765 766 767

            sock_set_blocking (client->con->sock, SOCK_NONBLOCK);
            sock_set_nodelay (client->con->sock);
Jack Moffitt's avatar
Jack Moffitt committed
768

769 770
            _add_request_queue (node);
            stats_event_inc (NULL, "connections");
771
        }
772
        process_request_queue ();
773
    }
Jack Moffitt's avatar
Jack Moffitt committed
774

775 776 777
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

778 779
    if (tid)
        thread_join (tid);
Jack Moffitt's avatar
Jack Moffitt committed
780

781 782 783
    /* wait for all the sources to shutdown */
    thread_rwlock_wlock(&_source_shutdown_rwlock);
    thread_rwlock_unlock(&_source_shutdown_rwlock);
Jack Moffitt's avatar
Jack Moffitt committed
784 785
}

786 787 788

/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
789
 */
790
int connection_complete_source (source_t *source, int response)
791 792 793 794 795 796 797 798
{
    ice_config_t *config = config_get_config();

    global_lock ();
    DEBUG1 ("sources count is %d", global.sources);

    if (global.sources < config->source_limit)
    {
799
        const char *contenttype;
800
        mount_proxy *mountinfo;
801 802 803 804 805 806 807 808 809 810 811 812
        format_type_t format_type;

        /* setup format handler */
        contenttype = httpp_getvar (source->parser, "content-type");
        if (contenttype != NULL)
        {
            format_type = format_get_type (contenttype);

            if (format_type == FORMAT_ERROR)
            {
                global_unlock();
                config_release_config();
813 814
                if (response)
                {
815
                    client_send_403 (source->client, "Content-type not supported");
816 817
                    source->client = NULL;
                }
818 819 820 821 822 823
                WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
                return -1;
            }
        }
        else
        {
824
            WARN0("No content-type header, falling back to backwards compatibility mode "
825
                    "for icecast 1.x relays. Assuming content is mp3.");
826
            format_type = FORMAT_TYPE_GENERIC;
827 828
        }

Karl Heyes's avatar
Karl Heyes committed
829
        if (format_get_plugin (format_type, source) < 0)
830 831 832
        {
            global_unlock();
            config_release_config();
833 834
            if (response)
            {
835
                client_send_403 (source->client, "internal format allocation problem");
836 837
                source->client = NULL;
            }
838 839 840 841
            WARN1 ("plugin format failed for \"%s\"", source->mount);
            return -1;
        }

842 843 844
        global.sources++;
        stats_event_args (NULL, "sources", "%d", global.sources);
        global_unlock();
845

846 847
        source->running = 1;
        mountinfo = config_find_mount (config, source->mount);
848
        source_update_settings (config, source, mountinfo);
849
        config_release_config();
850
        slave_rebuild_mounts();
851 852 853 854 855 856

        source->shutdown_rwlock = &_source_shutdown_rwlock;
        DEBUG0 ("source is ready to start");

        return 0;
    }
857
    WARN1("Request to add source when maximum source limit "
858 859 860 861 862
            "reached %d", global.sources);

    global_unlock();
    config_release_config();

863 864
    if (response)
    {
865
        client_send_403 (source->client, "too many sources connected");
866 867
        source->client = NULL;
    }
868 869 870 871 872

    return -1;
}


873
static int _check_pass_http(http_parser_t *parser, 
874
        const char *correctuser, const char *correctpass)
875 876
{
    /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
877
    const char *header = httpp_getvar(parser, "authorization");
878 879 880 881 882 883 884 885 886 887
    char *userpass, *tmp;
    char *username, *password;

    if(header == NULL)
        return 0;

    if(strncmp(header, "Basic ", 6))
        return 0;

    userpass = util_base64_decode(header+6);
888 889 890
    if(userpass == NULL) {
        WARN1("Base64 decode of Authorization header \"%s\" failed",
                header+6);
891
        return 0;
892
    }
893 894 895 896 897 898 899 900 901 902

    tmp = strchr(userpass, ':');
    if(!tmp) {
        free(userpass);
        return 0;
    }
    *tmp = 0;
    username = userpass;
    password = tmp+1;

903
    if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
904 905 906
        free(userpass);
        return 0;
    }
907
    free(userpass);
908 909 910 911

    return 1;
}

912
static int _check_pass_icy(http_parser_t *parser, const char *correctpass)
913
{
914
    const char *password;
915 916 917 918 919

    password = httpp_getvar(parser, HTTPP_VAR_ICYPASSWORD);
    if(!password)
        return 0;

920
    if (strcmp(password, correctpass))
921 922 923 924 925
        return 0;
    else
        return 1;
}

926
static int _check_pass_ice(http_parser_t *parser, const char *correctpass)
927
{
928
    const char *password;
929 930 931 932 933

    password = httpp_getvar(parser, "ice-password");
    if(!password)
        password = "";

934
    if (strcmp(password, correctpass))
935 936 937 938 939
        return 0;
    else
        return 1;
}

940
int connection_check_admin_pass(http_parser_t *parser)
941
{
942
    int ret;
Michael Smith's avatar
Michael Smith committed
943 944 945
    ice_config_t *config = config_get_config();
    char *pass = config->admin_password;
    char *user = config->admin_username;
946
    const char *protocol;
947 948 949 950 951 952

    if(!pass || !user) {
        config_release_config();
        return 0;
    }

953 954 955 956 957
    protocol = httpp_getvar (parser, HTTPP_VAR_PROTOCOL);
    if (protocol && strcmp (protocol, "ICY") == 0)
        ret = _check_pass_icy (parser, pass);
    else 
        ret = _check_pass_http (parser, user, pass);
Michael Smith's avatar
Michael Smith committed
958
    config_release_config();
959 960
    return ret;
}
Michael Smith's avatar
Michael Smith committed
961

962 963 964 965 966
int connection_check_relay_pass(http_parser_t *parser)
{
    int ret;
    ice_config_t *config = config_get_config();
    char *pass = config->relay_password;
967
    char *user = config->relay_username;
Michael Smith's avatar
Michael Smith committed
968

969 970
    if(!pass || !user) {
        config_release_config();
971
        return 0;
972
    }
973

974 975 976
    ret = _check_pass_http(parser, user, pass);
    config_release_config();
    return ret;
977 978
}

979
int connection_check_source_pass(http_parser_t *parser, const char *mount)
980
{
Michael Smith's avatar
Michael Smith committed
981 982
    ice_config_t *config = config_get_config();
    char *pass = config->source_password;
983
    char *user = "source";
984
    int ret;
Michael Smith's avatar
Michael Smith committed
985
    int ice_login = config->ice_login;
986
    const char *protocol;
Michael Smith's avatar
Michael Smith committed
987

988
    mount_proxy *mountinfo = config_find_mount (config, mount);
989

990 991 992 993 994 995
    if (mountinfo)
    {
        if (mountinfo->password)
            pass = mountinfo->password;
        if (mountinfo->username)
            user = mountinfo->username;
996 997 998 999
    }

    if(!pass) {
        WARN0("No source password set, rejecting source");
1000
        config_release_config();
1001 1002 1003
        return 0;
    }

1004
    protocol = httpp_getvar(parser, HTTPP_VAR_PROTOCOL);
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    if(protocol != NULL && !strcmp(protocol, "ICY")) {
        ret = _check_pass_icy(parser, pass);
    }
    else {
        ret = _check_pass_http(parser, user, pass);
        if(!ret && ice_login)
        {
            ret = _check_pass_ice(parser, pass);
            if(ret)
                WARN0("Source is using deprecated icecast login");
        }
1016
    }
1017
    config_release_config();
1018
    return ret;
1019 1020
}

1021

1022
static void _handle_source_request (client_t *client, char *uri, int auth_style)
1023
{
1024
    source_t *source;
1025

1026
    INFO1("Source logging in at mountpoint \"%s\"", uri);
1027

1028 1029 1030 1031 1032 1033
    if (uri[0] != '/')
    {
        WARN0 ("source mountpoint not starting with /");
        client_send_401 (client);
        return;
    }
1034
    if (auth_style == ICECAST_SOURCE_AUTH) {
1035 1036
        if (connection_check_source_pass (client->parser, uri) == 0)
        {
1037 1038 1039 1040
            /* We commonly get this if the source client is using the wrong
             * protocol: attempt to diagnose this and return an error
             */
            /* TODO: Do what the above comment says */
1041
            INFO1("Source (%s) attempted to login with invalid or missing password", uri);
1042 1043 1044
            client_send_401(client);
            return;
        }
1045
    }
1046 1047 1048
    source = source_reserve (uri);
    if (source)
    {
1049 1050 1051
        if (auth_style == SHOUTCAST_SOURCE_AUTH) {
            source->shoutcast_compat = 1;
        }
1052
        source->client = client;
1053 1054
        source->parser = client->parser;
        source->con = client->con;
1055
        if (connection_complete_source (source, 1) < 0)
1056
        {
1057
            source_clear_source (source);
1058 1059 1060
            source_free_source (source);
        }
        else
1061
        {
1062
            refbuf_t *ok = refbuf_new (PER_CLIENT_REFBUF_SIZE);
1063
            client->respcode = 200;
1064
            snprintf (ok->data, PER_CLIENT_REFBUF_SIZE,
1065
                    "HTTP/1.0 200 OK\r\n\r\n");
1066 1067 1068 1069
            ok->len = strlen (ok->data);
            /* we may have unprocessed data read in, so don't overwrite it */
            ok->associated = client->refbuf;
            client->refbuf = ok;
1070 1071
            fserve_add_client_callback (client, source_client_callback, source);
        }
1072 1073 1074
    }
    else
    {
1075
        client_send_403 (client, "Mountpoint in use");
1076
        WARN1 ("Mountpoint %s in use", uri);
1077
    }
1078 1079
}

1080

1081
static void _handle_stats_request (client_t *client, char *uri)
Jack Moffitt's avatar
Jack Moffitt committed
1082
{
1083
    stats_event_inc(NULL, "stats_connections");
1084 1085 1086 1087

    if (connection_check_admin_pass (client->parser) == 0)
    {
        client_send_401 (client);
1088 1089
        ERROR0("Bad password for stats connection");
        return;
1090
    }
1091

1092
    client->respcode = 200;
1093 1094 1095 1096
    snprintf (client->refbuf->data, PER_CLIENT_REFBUF_SIZE,
            "HTTP/1.0 200 OK\r\n\r\n");
    client->refbuf->len = strlen (client->refbuf->data);
    fserve_add_client_callback (client, stats_callback, NULL);
1097 1098
}

1099
static void _handle_get_request (client_t *client, char *passed_uri)
1100
{
Michael Smith's avatar
Michael Smith committed
1101
    int port;
Karl Heyes's avatar
Karl Heyes committed
1102 1103
    char *serverhost = NULL;
    int serverport = 0;
1104
    aliases *alias;
Michael Smith's avatar
Michael Smith committed
1105
    ice_config_t *config;
1106
    char *uri = passed_uri;