connection.c 40.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* 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).
11
 * Copyright 2011,      Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>
12 13
 */

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

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

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

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

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

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

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

#define CATMODULE "connection"

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/* 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

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

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

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

107
static spin_t _connection_lock;
108
static volatile unsigned long _current_id = 0;
Jack Moffitt's avatar
Jack Moffitt committed
109 110
static int _initialized = 0;

111 112
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;
113 114 115 116 117
static int ssl_ok;
#ifdef HAVE_OPENSSL
static SSL_CTX *ssl_ctx;
#endif

118 119 120
/* filtering client connection based on IP */
cache_file_contents banned_ip, allowed_ip;

121
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
122

123
static void _handle_connection(void);
Jack Moffitt's avatar
Jack Moffitt committed
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
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
141 142
void connection_initialize(void)
{
143 144
    if (_initialized) return;
    
145
    thread_spin_create (&_connection_lock);
146
    thread_mutex_create(&move_clients_mutex);
147
    thread_rwlock_create(&_source_shutdown_rwlock);
148
    thread_cond_create(&global.shutdown_cond);
149 150 151 152
    _req_queue = NULL;
    _req_queue_tail = &_req_queue;
    _con_queue = NULL;
    _con_queue_tail = &_con_queue;
Jack Moffitt's avatar
Jack Moffitt committed
153

154 155 156 157 158 159
    banned_ip.contents = NULL;
    banned_ip.file_mtime = 0;

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

160
    _initialized = 1;
Jack Moffitt's avatar
Jack Moffitt committed
161 162 163 164
}

void connection_shutdown(void)
{
165 166
    if (!_initialized) return;
    
167 168 169
#ifdef HAVE_OPENSSL
    SSL_CTX_free (ssl_ctx);
#endif
170 171 172
    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);
 
173
    thread_cond_destroy(&global.shutdown_cond);
174
    thread_rwlock_destroy(&_source_shutdown_rwlock);
175
    thread_spin_destroy (&_connection_lock);
176
    thread_mutex_destroy(&move_clients_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
177

178
    _initialized = 0;
Jack Moffitt's avatar
Jack Moffitt committed
179 180 181 182
}

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

185
    thread_spin_lock (&_connection_lock);
186
    id = _current_id++;
187
    thread_spin_unlock (&_connection_lock);
Jack Moffitt's avatar
Jack Moffitt committed
188

189
    return id;
Jack Moffitt's avatar
Jack Moffitt committed
190 191
}

192 193

#ifdef HAVE_OPENSSL
194
static void get_ssl_certificate (ice_config_t *config)
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
{
    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))
        {
221
            ERROR1 ("Invalid %s - Private key does not match cert public key", config->cert_file);
222 223 224 225
            break;
        }
        ssl_ok = 1;
        INFO1 ("SSL certificate found at %s", config->cert_file);
226
        return;
227
    } while (0);
228
    INFO0 ("No SSL capability on any configured ports");
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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
}


/* 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 */
273
static void get_ssl_certificate (ice_config_t *config)
274 275 276 277 278 279 280 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
{
    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;
}


308 309 310 311 312 313 314 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
/* 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;
}


403 404
connection_t *connection_create (sock_t sock, sock_t serversock, char *ip)
{
405
    connection_t *con;
406 407 408 409 410 411 412 413
    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;
414 415
        con->read = connection_read;
        con->send = connection_send;
416
    }
417

418
    return con;
419 420
}

421 422 423 424 425 426 427 428 429 430 431 432 433
/* 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
}

434
static sock_t wait_for_serversock(int timeout)
435 436
{
#ifdef HAVE_POLL
437
    struct pollfd ufds [global.server_sockets];
438 439 440 441 442 443 444 445 446 447
    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) {
448
        return SOCK_ERROR;
449 450
    }
    else if(ret == 0) {
451
        return SOCK_ERROR;
452 453
    }
    else {
454
        int dst;
455
        for(i=0; i < global.server_sockets; i++) {
456
            if(ufds[i].revents & POLLIN)
457
                return ufds[i].fd;
458 459 460 461
            if(ufds[i].revents & (POLLHUP|POLLERR|POLLNVAL))
            {
                if (ufds[i].revents & (POLLHUP|POLLERR))
                {
462
                    sock_close (global.serversock[i]);
463 464
                    WARN0("Had to close a listening socket");
                }
465
                global.serversock[i] = SOCK_ERROR;
466
            }
467
        }
468 469 470
        /* remove any closed sockets */
        for(i=0, dst=0; i < global.server_sockets; i++)
        {
471
            if (global.serversock[i] == SOCK_ERROR)
472 473 474 475 476 477
                continue;
            if (i!=dst)
                global.serversock[dst] = global.serversock[i];
            dst++;
        }
        global.server_sockets = dst;
478
        return SOCK_ERROR;
479 480 481 482 483
    }
#else
    fd_set rfds;
    struct timeval tv, *p=NULL;
    int i, ret;
484
    sock_t max = SOCK_ERROR;
485 486 487 488 489

    FD_ZERO(&rfds);

    for(i=0; i < global.server_sockets; i++) {
        FD_SET(global.serversock[i], &rfds);
490
        if (max == SOCK_ERROR || global.serversock[i] > max)
491 492 493 494 495
            max = global.serversock[i];
    }

    if(timeout >= 0) {
        tv.tv_sec = timeout/1000;
496
        tv.tv_usec = (timeout % 1000) * 1000;
497 498 499 500 501
        p = &tv;
    }

    ret = select(max+1, &rfds, NULL, NULL, p);
    if(ret < 0) {
502
        return SOCK_ERROR;
503 504
    }
    else if(ret == 0) {
505
        return SOCK_ERROR;
506 507 508 509 510 511
    }
    else {
        for(i=0; i < global.server_sockets; i++) {
            if(FD_ISSET(global.serversock[i], &rfds))
                return global.serversock[i];
        }
512
        return SOCK_ERROR; /* Should be impossible, stop compiler warnings */
513 514 515 516
    }
#endif
}

517
static connection_t *_accept_connection(int duration)
Jack Moffitt's avatar
Jack Moffitt committed
518
{
519
    sock_t sock, serversock;
520
    char *ip;
Jack Moffitt's avatar
Jack Moffitt committed
521

522
    serversock = wait_for_serversock (duration);
523
    if (serversock == SOCK_ERROR)
524
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
525

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

529
    sock = sock_accept(serversock, ip, MAX_ADDR_LEN);
530
    if (sock != SOCK_ERROR)
531
    {
532
        connection_t *con = NULL;
533 534 535
        /* 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
536

537 538
        if (accept_ip_address (ip))
            con = connection_create (sock, serversock, ip);
539 540 541 542 543 544 545 546 547 548 549
        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);
        }
550 551 552
    }
    free(ip);
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
553 554 555
}


556 557 558 559 560
/* 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
561
{
562 563
    *_con_queue_tail = node;
    _con_queue_tail = (volatile client_queue_t **)&node->next;
Jack Moffitt's avatar
Jack Moffitt committed
564 565 566
}


567 568 569 570 571 572
/* 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
573

574 575 576 577 578 579 580
    /* common case, no new connections so don't bother taking locks */
    if (_con_queue)
    {
        node = (client_queue_t *)_con_queue;
        _con_queue = node->next;
        if (_con_queue == NULL)
            _con_queue_tail = &_con_queue;
581
        node->next = NULL;
582
    }
583 584
    return node;
}
Jack Moffitt's avatar
Jack Moffitt committed
585 586


587
/* run along queue checking for any data that has come in or a timeout */
588
static void process_request_queue (void)
589 590 591 592 593
{
    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
594

595 596 597 598 599 600
    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
601

602 603 604 605 606 607 608
        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
609

610 611 612 613 614
        if (len > 0)
        {
            int pass_it = 1;
            char *ptr;

615 616
            /* handle \n, \r\n and nsvcap which for some strange reason has
             * EOL as \r\r\n */
617 618 619 620 621 622 623
            node->offset += len;
            client->refbuf->data [node->offset] = '\000';
            do
            {
                if (node->shoutcast == 1)
                {
                    /* password line */
624 625
                    if (strstr (client->refbuf->data, "\r\r\n") != NULL)
                        break;
626 627 628 629 630 631 632
                    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 */
633 634 635 636 637 638
                ptr = strstr (client->refbuf->data, "\r\r\n\r\r\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+6) - client->refbuf->data;
                    break;
                }
639 640 641 642 643 644 645 646 647 648 649 650 651 652
                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
653

654 655 656 657 658 659 660
            if (pass_it)
            {
                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;
                _add_connection (node);
661
                continue;
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
            }
        }
        else
        {
            if (len == 0 || client->con->error)
            {
                if ((client_queue_t **)_req_queue_tail == &node->next)
                    _req_queue_tail = (volatile client_queue_t **)node_ref;
                *node_ref = node->next;
                client_destroy (client);
                free (node);
                continue;
            }
        }
        node_ref = &node->next;
677
    }
678
    _handle_connection();
Jack Moffitt's avatar
Jack Moffitt committed
679 680
}

681

682 683 684 685 686 687 688
/* 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)
{
    *_req_queue_tail = node;
    _req_queue_tail = (volatile client_queue_t **)&node->next;
Jack Moffitt's avatar
Jack Moffitt committed
689 690
}

691

692
void connection_accept_loop (void)
Jack Moffitt's avatar
Jack Moffitt committed
693
{
694
    connection_t *con;
695
    ice_config_t *config;
696
    int duration = 300;
697 698 699 700

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

702 703
    while (global.running == ICE_RUNNING)
    {
704
        con = _accept_connection (duration);
705 706

        if (con)
707
        {
708 709 710
            client_queue_t *node;
            ice_config_t *config;
            client_t *client = NULL;
711
            listener_t *listener;
712

713 714 715 716
            global_lock();
            if (client_create (&client, con, NULL) < 0)
            {
                global_unlock();
717
                client_send_403 (client, "Icecast connection limit reached");
718 719
                /* don't be too eager as this is an imposed hard limit */
                thread_sleep (400000);
720 721
                continue;
            }
722

723 724 725
            /* setup client for reading incoming http */
            client->refbuf->data [PER_CLIENT_REFBUF_SIZE-1] = '\000';

726 727
            if (sock_set_blocking (client->con->sock, 0) || sock_set_nodelay (client->con->sock))
            {
728
                global_unlock();
729 730 731 732 733
                WARN0 ("failed to set tcp options on client connection, dropping");
                client_destroy (client);
                continue;
            }

734 735 736
            node = calloc (1, sizeof (client_queue_t));
            if (node == NULL)
            {
737
                global_unlock();
738 739 740 741 742 743
                client_destroy (client);
                continue;
            }
            node->client = client;

            config = config_get_config();
744 745 746
            listener = config_get_listen_sock (config, client->con);

            if (listener)
747
            {
748 749 750 751
                if (listener->shoutcast_compat)
                    node->shoutcast = 1;
                if (listener->ssl && ssl_ok)
                    connection_uses_ssl (client->con);
752 753
                if (listener->shoutcast_mount)
                    node->shoutcast_mount = strdup (listener->shoutcast_mount);
754
            }
755
            global_unlock();
756
            config_release_config();
757 758 759

            _add_request_queue (node);
            stats_event_inc (NULL, "connections");
760 761 762 763 764 765
            duration = 5;
        }
        else
        {
            if (_req_queue == NULL)
                duration = 300; /* use longer timeouts when nothing waiting */
766
        }
767
        process_request_queue ();
768
    }
Jack Moffitt's avatar
Jack Moffitt committed
769

770 771 772
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

773 774 775
    /* 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
776 777
}

778 779 780

/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
781
 */
782
int connection_complete_source (source_t *source, int response)
783
{
784
    ice_config_t *config;
785 786 787 788

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

789
    config = config_get_config();
790 791
    if (global.sources < config->source_limit)
    {
792
        const char *contenttype;
793
        mount_proxy *mountinfo;
794 795 796 797 798 799 800 801 802 803 804
        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)
            {
                config_release_config();
805
                global_unlock();
806 807
                if (response)
                {
808
                    client_send_403 (source->client, "Content-type not supported");
809 810
                    source->client = NULL;
                }
811 812 813 814 815 816
                WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
                return -1;
            }
        }
        else
        {
817
            WARN0("No content-type header, falling back to backwards compatibility mode "
818
                    "for icecast 1.x relays. Assuming content is mp3.");
819
            format_type = FORMAT_TYPE_GENERIC;
820 821
        }

Karl Heyes's avatar
Karl Heyes committed
822
        if (format_get_plugin (format_type, source) < 0)
823 824 825
        {
            global_unlock();
            config_release_config();
826 827
            if (response)
            {
828
                client_send_403 (source->client, "internal format allocation problem");
829 830
                source->client = NULL;
            }
831 832 833 834
            WARN1 ("plugin format failed for \"%s\"", source->mount);
            return -1;
        }

835 836 837
        global.sources++;
        stats_event_args (NULL, "sources", "%d", global.sources);
        global_unlock();
838

839 840
        source->running = 1;
        mountinfo = config_find_mount (config, source->mount);
841
        source_update_settings (config, source, mountinfo);
842
        config_release_config();
843
        slave_rebuild_mounts();
844 845 846 847 848 849

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

        return 0;
    }
850
    WARN1("Request to add source when maximum source limit "
851 852 853 854 855
            "reached %d", global.sources);

    global_unlock();
    config_release_config();

856 857
    if (response)
    {
858
        client_send_403 (source->client, "too many sources connected");
859 860
        source->client = NULL;
    }
861 862 863 864 865

    return -1;
}


866
static int _check_pass_http(http_parser_t *parser, 
867
        const char *correctuser, const char *correctpass)
868 869
{
    /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
870
    const char *header = httpp_getvar(parser, "authorization");
871 872 873 874 875 876 877 878 879 880
    char *userpass, *tmp;
    char *username, *password;

    if(header == NULL)
        return 0;

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

    userpass = util_base64_decode(header+6);
881 882 883
    if(userpass == NULL) {
        WARN1("Base64 decode of Authorization header \"%s\" failed",
                header+6);
884
        return 0;
885
    }
886 887 888 889 890 891 892 893 894 895

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

896
    if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
897 898 899
        free(userpass);
        return 0;
    }
900
    free(userpass);
901 902 903 904

    return 1;
}

905
static int _check_pass_icy(http_parser_t *parser, const char *correctpass)
906
{
907
    const char *password;
908 909 910 911 912

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

913
    if (strcmp(password, correctpass))
914 915 916 917 918
        return 0;
    else
        return 1;
}

919
static int _check_pass_ice(http_parser_t *parser, const char *correctpass)
920
{
921
    const char *password;
922 923 924 925 926

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

927
    if (strcmp(password, correctpass))
928 929 930 931 932
        return 0;
    else
        return 1;
}

933
int connection_check_admin_pass(http_parser_t *parser)
934
{
935
    int ret;
936 937 938
    ice_config_t *config = config_get_config();
    char *pass = config->admin_password;
    char *user = config->admin_username;
939
    const char *protocol;
940 941 942 943 944 945

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

946 947 948 949 950
    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);
951
    config_release_config();
952 953
    return ret;
}
Michael Smith's avatar
Michael Smith committed
954

955 956 957 958 959
int connection_check_relay_pass(http_parser_t *parser)
{
    int ret;
    ice_config_t *config = config_get_config();
    char *pass = config->relay_password;
960
    char *user = config->relay_username;
961

962 963
    if(!pass || !user) {
        config_release_config();
964
        return 0;
965
    }
966

967 968 969
    ret = _check_pass_http(parser, user, pass);
    config_release_config();
    return ret;
970 971
}

972 973 974 975

/* return 0 for failed, 1 for ok
 */
int connection_check_pass (http_parser_t *parser, const char *user, const char *pass)
976
{
977
    int ret;
978
    const char *protocol;
979

980 981
    if(!pass) {
        WARN0("No source password set, rejecting source");
982
        return -1;
983 984
    }

985
    protocol = httpp_getvar(parser, HTTPP_VAR_PROTOCOL);
986 987 988 989 990
    if(protocol != NULL && !strcmp(protocol, "ICY")) {
        ret = _check_pass_icy(parser, pass);
    }
    else {
        ret = _check_pass_http(parser, user, pass);
991
        if (!ret)
992
        {
993 994 995 996 997 998 999
            ice_config_t *config = config_get_config_unlocked();
            if (config->ice_login)
            {
                ret = _check_pass_ice(parser, pass);
                if(ret)
                    WARN0("Source is using deprecated icecast login");
            }
1000
        }
1001 1002
    }
    return ret;
1003 1004
}

1005

1006 1007
/* only called for native icecast source clients */
static void _handle_source_request (client_t *client, const char *uri)
1008 1009
{
    INFO1("Source logging in at mountpoint \"%s\"", uri);
1010

1011 1012 1013 1014 1015 1016
    if (uri[0] != '/')
    {
        WARN0 ("source mountpoint not starting with /");
        client_send_401 (client);
        return;
    }
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    switch (client_check_source_auth (client, uri))
    {
        case 0: /* authenticated from config file */
            source_startup (client, uri, ICECAST_SOURCE_AUTH);
            break;

        case 1: /* auth pending */
            break;

        default: /* failed */
1027
            INFO1("Source (%s) attempted to login with invalid or missing password", uri);
1028
            client_send_401(client);
1029
            break;
1030
    }
1031 1032 1033 1034 1035 1036
}


void source_startup (client_t *client, const char *uri, int auth_style)
{
    source_t *source;
1037
    source = source_reserve (uri);
1038

1039 1040 1041
    if (source)
    {
        source->client = client;
1042 1043
        source->parser = client->parser;
        source->con = client->con;
1044
        if (connection_complete_source (source, 1) < 0)
1045
        {
1046
            source_clear_source (source);
1047
            source_free_source (source);
1048 1049 1050 1051 1052 1053 1054
            return;
        }
        client->respcode = 200;
        if (auth_style == SHOUTCAST_SOURCE_AUTH)
        {
            source->shoutcast_compat = 1;
            source_client_callback (client, source);
1055 1056
        }
        else
1057
        {
1058
            refbuf_t *ok = refbuf_new (PER_CLIENT_REFBUF_SIZE);
1059
            client->respcode = 200;
1060
            snprintf (ok->data, PER_CLIENT_REFBUF_SIZE,
1061
                    "HTTP/1.0 200 OK\r\n\r\n");
1062 1063 1064 1065
            ok->len = strlen (ok->data);
            /* we may have unprocessed data read in, so don't overwrite it */
            ok->associated = client->refbuf;
            client->refbuf = ok;
1066 1067
            fserve_add_client_callback (client, source_client_callback, source);
        }
1068 1069 1070
    }
    else
    {
1071
        client_send_403 (client, "Mountpoint in use");
1072
        WARN1 ("Mountpoint %s in use", uri);
1073
    }
1074 1075
}

1076

1077
static void _handle_stats_request (client_t *client, char *uri)
Jack Moffitt's avatar
Jack Moffitt committed
1078
{
1079
    stats_event_inc(NULL, "stats_connections");
1080 1081 1082 1083

    if (connection_check_admin_pass (client->parser) == 0)
    {
        client_send_401 (client);
1084 1085
        ERROR0("Bad password for stats connection");
        return;
1086
    }
1087

1088
    client->respcode = 200;
1089 1090 1091 1092
    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);
1093 1094
}

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

    config = config_get_config();
    port = config->port;
1107 1108 1109 1110 1111 1112

    listen_sock = config_get_listen_sock (config, client->con);
    if (listen_sock)
    {
        serverhost = listen_sock->bind_address;
        serverport = listen_sock->port;
1113 1114
    }
    alias = config->aliases;
1115

1116 1117 1118
    /* there are several types of HTTP GET clients
    ** media clients, which are looking for a source (eg, URI = /stream.ogg)
    ** stats clients, which are looking for /admin/stats.xml
1119
    ** and directory server authorizers, which are looking for /GUID-xxxxxxxx 
1120
    ** (where xxxxxx is the GUID in question) - this isn't implemented yet.
1121 1122 1123 1124
    ** we need to handle the latter two before the former, as the latter two
    ** aren't subject to the limits.
    */
    /* TODO: add GUID-xxxxxx */
1125

1126 1127 1128
    /* Handle aliases */
    while(alias) {
        if(strcmp(uri, alias->source) == 0 && (alias->port == -1 || alias->port == serverport) && (alias->bind_address == NULL || (serverhost != NULL && strcmp(alias->bind_address, serverhost) == 0))) {
1129 1130
            uri = strdup (alias->destination);
            DEBUG2 ("alias has made %s into %s", passed_uri, uri);
1131 1132 1133 1134
            break;
        }
        alias = alias->next;
    }
1135 1136 1137
    config_release_config();

    stats_event_inc(NULL, "client_connections");
1138

1139
    /* Dispatch all admin requests */
1140 1141
    if ((strcmp(uri, "/admin.cgi") == 0) ||
        (strncmp(uri, "/admin/", 7) == 0)) {
1142
        admin_handle_request(client, uri);
1143
        if (uri != passed_uri) free (uri);
Michael Smith's avatar
Michael Smith committed
1144 1145
        return;
    }
1146
    auth_add_listener (uri, client);
1147
    if (uri != passed_uri) free (uri);
1148 1149
}

1150 1151
static void _handle_shoutcast_compatible (client_queue_t *node)
{
1152 1153 1154
    char *http_compliant;
    int http_compliant_len = 0;
    http_parser_t *parser;
1155 1156 1157
    ice_config_t *config = config_get_config ();
    char *shoutcast_mount;
    client_t *client = node->client;
1158

1159 1160 1161 1162 1163
    if (node->shoutcast_mount)
        shoutcast_mount = node->shoutcast_mount;
    else
        shoutcast_mount = config->shoutcast_mount;

1164 1165
    if (node->shoutcast == 1)
    {
1166
        char *source_password, *ptr, *headers;
1167
        mount_proxy *mountinfo = config_find_mount (config, shoutcast_mount);
1168 1169 1170 1171

        if (mountinfo && mountinfo->password)
            source_password = strdup (mountinfo->password);
        else
1172 1173 1174 1175 1176 1177
        {
            if (config->source_password) 
                source_password = strdup (config->source_password);
            else
                source_password = NULL;
        }
1178 1179 1180
        config_release_config();

        /* Get rid of trailing \r\n or \n after password */
1181
        ptr = strstr (client->refbuf->data, "\r\r\n");
1182
        if (ptr)
1183
            headers = ptr+3;
1184 1185
        else
        {
1186
            ptr = strstr (client->refbuf->data, "\r\n");
1187
            if (ptr)
1188 1189 1190 1191 1192 1193 1194
                headers = ptr+2;
            else
            {
                ptr = strstr (client->refbuf->data, "\n");
                if (ptr)
                    headers = ptr+1;
            }
1195
        }
1196 1197 1198 1199 1200

        if (ptr == NULL)
        {
            client_destroy (client);
            free (source_password);
1201
            free (node->shoutcast_mount);
1202 1203 1204 1205 1206
            free (node);
            return;
        }
        *ptr = '\0';

1207
        if (source_password && strcmp (client->refbuf->data, source_password) == 0)
1208 1209 1210 1211
        {
            client->respcode = 200;
            /* send this non-blocking but if there is only a partial write
             * then leave to header timeout */
1212
            sock_write (client->con->sock, "OK2\r\nicy-caps:11\r\n\r\n");
1213 1214
            node->offset -= (headers - client->refbuf->data);
            memmove (client->refbuf->data, headers, node->offset+1);
1215 1216 1217 1218 1219 1220
            node->shoutcast = 2;
            /* we've checked the password, now send it back for reading headers */
            _add_request_queue (node);
            free (source_password);
            return;
        }
1221 1222
        else
            INFO1 ("password does not match \"%s\"", client->refbuf->data);
1223
        client_destroy (client);