connection.c 29.5 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 20
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
21
#include <time.h>
Jack Moffitt's avatar
Jack Moffitt committed
22
#include <sys/types.h>
23
#include <sys/stat.h>
24 25 26
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
27 28 29

#ifndef _WIN32
#include <sys/time.h>
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 40

#include "os.h"

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"
Michael Smith's avatar
Michael Smith committed
60
#include "format.h"
61
#include "format_mp3.h"
Michael Smith's avatar
Michael Smith committed
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 68

#define CATMODULE "connection"

typedef struct con_queue_tag {
69 70
    connection_t *con;
    struct con_queue_tag *next;
Jack Moffitt's avatar
Jack Moffitt committed
71 72 73
} con_queue_t;

typedef struct _thread_queue_tag {
74 75
    thread_type *thread_id;
    struct _thread_queue_tag *next;
Jack Moffitt's avatar
Jack Moffitt committed
76 77 78
} thread_queue_t;

static mutex_t _connection_mutex;
79
static volatile unsigned long _current_id = 0;
Jack Moffitt's avatar
Jack Moffitt committed
80 81
static int _initialized = 0;

82
static volatile con_queue_t *_queue = NULL;
Jack Moffitt's avatar
Jack Moffitt committed
83 84 85 86
static mutex_t _queue_mutex;

static thread_queue_t *_conhands = NULL;

87
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
88 89 90 91 92

static void *_handle_connection(void *arg);

void connection_initialize(void)
{
93 94 95 96
    if (_initialized) return;
    
    thread_mutex_create(&_connection_mutex);
    thread_mutex_create(&_queue_mutex);
97
    thread_mutex_create(&move_clients_mutex);
98
    thread_rwlock_create(&_source_shutdown_rwlock);
99
    thread_cond_create(&global.shutdown_cond);
Jack Moffitt's avatar
Jack Moffitt committed
100

101
    _initialized = 1;
Jack Moffitt's avatar
Jack Moffitt committed
102 103 104 105
}

void connection_shutdown(void)
{
106 107
    if (!_initialized) return;
    
108
    thread_cond_destroy(&global.shutdown_cond);
109 110 111
    thread_rwlock_destroy(&_source_shutdown_rwlock);
    thread_mutex_destroy(&_queue_mutex);
    thread_mutex_destroy(&_connection_mutex);
112
    thread_mutex_destroy(&move_clients_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
113

114
    _initialized = 0;
Jack Moffitt's avatar
Jack Moffitt committed
115 116 117 118
}

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

121 122 123
    thread_mutex_lock(&_connection_mutex);
    id = _current_id++;
    thread_mutex_unlock(&_connection_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
124

125
    return id;
Jack Moffitt's avatar
Jack Moffitt committed
126 127
}

128
connection_t *create_connection(sock_t sock, sock_t serversock, char *ip) {
129 130 131 132
    connection_t *con;
    con = (connection_t *)malloc(sizeof(connection_t));
    memset(con, 0, sizeof(connection_t));
    con->sock = sock;
133
    con->serversock = serversock;
134 135 136
    con->con_time = time(NULL);
    con->id = _next_connection_id();
    con->ip = ip;
Michael Smith's avatar
Michael Smith committed
137 138 139 140

    con->event_number = EVENT_NO_EVENT;
    con->event = NULL;

141
    return con;
142 143
}

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
static int wait_for_serversock(int timeout)
{
#ifdef HAVE_POLL
    struct pollfd ufds[MAX_LISTEN_SOCKETS];
    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) {
        return -2;
    }
    else if(ret == 0) {
        return -1;
    }
    else {
164
        int dst;
165
        for(i=0; i < global.server_sockets; i++) {
166
            if(ufds[i].revents & POLLIN)
167
                return ufds[i].fd;
168 169 170 171 172 173 174 175 176
            if(ufds[i].revents & (POLLHUP|POLLERR|POLLNVAL))
            {
                if (ufds[i].revents & (POLLHUP|POLLERR))
                {
                    close (global.serversock[i]);
                    WARN0("Had to close a listening socket");
                }
                global.serversock[i] = -1;
            }
177
        }
178 179 180 181 182 183 184 185 186 187 188
        /* remove any closed sockets */
        for(i=0, dst=0; i < global.server_sockets; i++)
        {
            if (global.serversock[i] == -1)
                continue;
            if (i!=dst)
                global.serversock[dst] = global.serversock[i];
            dst++;
        }
        global.server_sockets = dst;
        return -1;
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    }
#else
    fd_set rfds;
    struct timeval tv, *p=NULL;
    int i, ret;
    int max = -1;

    FD_ZERO(&rfds);

    for(i=0; i < global.server_sockets; i++) {
        FD_SET(global.serversock[i], &rfds);
        if(global.serversock[i] > max)
            max = global.serversock[i];
    }

    if(timeout >= 0) {
        tv.tv_sec = timeout/1000;
206
        tv.tv_usec = (timeout % 1000) * 1000;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        p = &tv;
    }

    ret = select(max+1, &rfds, NULL, NULL, p);
    if(ret < 0) {
        return -2;
    }
    else if(ret == 0) {
        return -1;
    }
    else {
        for(i=0; i < global.server_sockets; i++) {
            if(FD_ISSET(global.serversock[i], &rfds))
                return global.serversock[i];
        }
        return -1; /* Should be impossible, stop compiler warnings */
    }
#endif
}

Jack Moffitt's avatar
Jack Moffitt committed
227 228
static connection_t *_accept_connection(void)
{
229 230 231
    int sock;
    connection_t *con;
    char *ip;
232
    int serversock; 
Jack Moffitt's avatar
Jack Moffitt committed
233

234 235 236
    serversock = wait_for_serversock(100);
    if(serversock < 0)
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
237

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

241 242
    sock = sock_accept(serversock, ip, MAX_ADDR_LEN);
    if (sock >= 0) {
243
        con = create_connection(sock, serversock, ip);
Jack Moffitt's avatar
Jack Moffitt committed
244

245 246
        return con;
    }
Jack Moffitt's avatar
Jack Moffitt committed
247

248 249 250 251
    if (!sock_recoverable(sock_error()))
        WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
    
    free(ip);
Jack Moffitt's avatar
Jack Moffitt committed
252

253
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
254 255 256 257
}

static void _add_connection(connection_t *con)
{
258
    con_queue_t *node;
Jack Moffitt's avatar
Jack Moffitt committed
259

260 261 262 263
    node = (con_queue_t *)malloc(sizeof(con_queue_t));
    
    thread_mutex_lock(&_queue_mutex);
    node->con = con;
264
    node->next = (con_queue_t *)_queue;
265 266
    _queue = node;
    thread_mutex_unlock(&_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
267 268
}

269
static void _push_thread(thread_queue_t **queue, thread_type *thread_id)
Jack Moffitt's avatar
Jack Moffitt committed
270
{
271 272 273 274 275 276 277 278 279 280 281 282 283 284
    /* create item */
    thread_queue_t *item = (thread_queue_t *)malloc(sizeof(thread_queue_t));
    item->thread_id = thread_id;
    item->next = NULL;


    thread_mutex_lock(&_queue_mutex);
    if (*queue == NULL) {
        *queue = item;
    } else {
        item->next = *queue;
        *queue = item;
    }
    thread_mutex_unlock(&_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
285 286
}

287
static thread_type *_pop_thread(thread_queue_t **queue)
Jack Moffitt's avatar
Jack Moffitt committed
288
{
289 290
    thread_type *id;
    thread_queue_t *item;
Jack Moffitt's avatar
Jack Moffitt committed
291

292
    thread_mutex_lock(&_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
293

294 295 296 297 298
    item = *queue;
    if (item == NULL) {
        thread_mutex_unlock(&_queue_mutex);
        return NULL;
    }
Jack Moffitt's avatar
Jack Moffitt committed
299

300 301 302 303
    *queue = item->next;
    item->next = NULL;
    id = item->thread_id;
    free(item);
Jack Moffitt's avatar
Jack Moffitt committed
304

305
    thread_mutex_unlock(&_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
306

307
    return id;
Jack Moffitt's avatar
Jack Moffitt committed
308 309 310 311
}

static void _build_pool(void)
{
312 313
    ice_config_t *config;
    int i;
314
    thread_type *tid;
315
    char buff[64];
Michael Smith's avatar
Michael Smith committed
316
    int threadpool_size;
Jack Moffitt's avatar
Jack Moffitt committed
317

318
    config = config_get_config();
Michael Smith's avatar
Michael Smith committed
319 320
    threadpool_size = config->threadpool_size;
    config_release_config();
Jack Moffitt's avatar
Jack Moffitt committed
321

322 323 324 325 326
    for (i = 0; i < threadpool_size; i++) {
        snprintf(buff, 64, "Connection Thread #%d", i);
        tid = thread_create(buff, _handle_connection, NULL, THREAD_ATTACHED);
        _push_thread(&_conhands, tid);
    }
Jack Moffitt's avatar
Jack Moffitt committed
327 328 329 330
}

static void _destroy_pool(void)
{
331 332 333 334 335 336 337 338 339 340
    thread_type *id;
    int i;

    i = 0;

    id = _pop_thread(&_conhands);
    while (id != NULL) {
        thread_join(id);
        id = _pop_thread(&_conhands);
    }
341
    INFO0("All connection threads down");
Jack Moffitt's avatar
Jack Moffitt committed
342 343 344 345
}

void connection_accept_loop(void)
{
346
    connection_t *con;
Jack Moffitt's avatar
Jack Moffitt committed
347

348
    _build_pool();
Jack Moffitt's avatar
Jack Moffitt committed
349

350 351
    while (global.running == ICE_RUNNING)
    {
352
        if (global . schedule_config_reread)
353 354 355 356 357
        {
            /* reread config file */
            INFO0("Scheduling config reread ...");

            connection_inject_event(EVENT_CONFIG_READ, NULL);
358
            global . schedule_config_reread = 0;
359 360
        }

361
        con = _accept_connection();
Jack Moffitt's avatar
Jack Moffitt committed
362

363 364 365 366
        if (con) {
            _add_connection(con);
        }
    }
Jack Moffitt's avatar
Jack Moffitt committed
367

368 369 370
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

371
    _destroy_pool();
Jack Moffitt's avatar
Jack Moffitt committed
372

373 374 375
    /* 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
376 377 378 379
}

static connection_t *_get_connection(void)
{
380 381 382 383
    con_queue_t *node = NULL;
    con_queue_t *oldnode = NULL;
    connection_t *con = NULL;

384 385 386 387
    /* common case, no new connections so don't bother taking locks */
    if (_queue == NULL)
        return NULL;

388 389
    thread_mutex_lock(&_queue_mutex);
    if (_queue) {
390
        node = (con_queue_t *)_queue;
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        while (node->next) {
            oldnode = node;
            node = node->next;
        }
        
        /* node is now the last node
        ** and oldnode is the previous one, or NULL
        */
        if (oldnode) oldnode->next = NULL;
        else (_queue) = NULL;
    }
    thread_mutex_unlock(&_queue_mutex);

    if (node) {
        con = node->con;
        free(node);
    }

    return con;
Jack Moffitt's avatar
Jack Moffitt committed
410 411
}

Michael Smith's avatar
Michael Smith committed
412 413 414 415 416 417 418 419 420
void connection_inject_event(int eventnum, void *event_data) {
    connection_t *con = calloc(1, sizeof(connection_t));

    con->event_number = eventnum;
    con->event = event_data;

    _add_connection(con);
}

421 422 423

/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
424
 */
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
int connection_complete_source (source_t *source)
{
    ice_config_t *config = config_get_config();

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

    if (global.sources < config->source_limit)
    {
        char *contenttype;
        mount_proxy *mountproxy = config->mounts;
        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();
                if (source->client)
                    client_send_404 (source->client, "Content-type not supported");
                WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
                return -1;
            }
        }
        else
        {
456
            WARN0("No content-type header, falling back to backwards compatibility mode "
457 458 459 460
                    "for icecast 1.x relays. Assuming content is mp3.");
            format_type = FORMAT_TYPE_MP3;
        }

Karl Heyes's avatar
Karl Heyes committed
461
        if (format_get_plugin (format_type, source) < 0)
462 463 464 465 466 467 468 469 470 471 472 473
        {
            global_unlock();
            config_release_config();
            if (source->client)
                client_send_404 (source->client, "internal format allocation problem");
            WARN1 ("plugin format failed for \"%s\"", source->mount);
            return -1;
        }

        global.sources++;
        global_unlock();

474 475 476
        /* set global settings first */
        source->queue_size_limit = config->queue_size_limit;
        source->timeout = config->source_timeout;
Karl Heyes's avatar
Karl Heyes committed
477
        source->burst_size = config->burst_size;
478

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
        /* for relays, we don't yet have a client, however we do require one
         * to retrieve the stream from.  This is created here, quite late,
         * because we can't use this client to return an error code/message,
         * so we only do this once we know we're going to accept the source.
         */
        if (source->client == NULL)
            source->client = client_create (source->con, source->parser);

        while (mountproxy)
        {
            if (strcmp (mountproxy->mountname, source->mount) == 0)
            {
                source_apply_mount (source, mountproxy);
                break;
            }
            mountproxy = mountproxy->next;
        }
        config_release_config();

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

        return 0;
    }
503
    WARN1("Request to add source when maximum source limit "
504 505 506 507 508 509 510 511 512 513 514 515
            "reached %d", global.sources);

    global_unlock();
    config_release_config();

    if (source->client)
        client_send_404 (source->client, "too many sources connected");

    return -1;
}


516 517
static int _check_pass_http(http_parser_t *parser, 
        char *correctuser, char *correctpass)
518 519 520 521 522 523 524 525 526 527 528 529 530
{
    /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
    char *header = httpp_getvar(parser, "authorization");
    char *userpass, *tmp;
    char *username, *password;

    if(header == NULL)
        return 0;

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

    userpass = util_base64_decode(header+6);
531 532 533
    if(userpass == NULL) {
        WARN1("Base64 decode of Authorization header \"%s\" failed",
                header+6);
534
        return 0;
535
    }
536 537 538 539 540 541 542 543 544 545

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

546
    if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
547 548 549
        free(userpass);
        return 0;
    }
550
    free(userpass);
551 552 553 554

    return 1;
}

555 556 557 558 559 560 561 562
static int _check_pass_icy(http_parser_t *parser, char *correctpass)
{
    char *password;

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

563
    if (strcmp(password, correctpass))
564 565 566 567 568
        return 0;
    else
        return 1;
}

569
static int _check_pass_ice(http_parser_t *parser, char *correctpass)
570
{
571
    char *password;
572 573 574 575 576

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

577
    if (strcmp(password, correctpass))
578 579 580 581 582
        return 0;
    else
        return 1;
}

583
int connection_check_admin_pass(http_parser_t *parser)
584
{
585
    int ret;
Michael Smith's avatar
Michael Smith committed
586 587 588
    ice_config_t *config = config_get_config();
    char *pass = config->admin_password;
    char *user = config->admin_username;
589 590 591 592 593 594 595

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

    ret = _check_pass_http(parser, user, pass);
Michael Smith's avatar
Michael Smith committed
596
    config_release_config();
597 598
    return ret;
}
Michael Smith's avatar
Michael Smith committed
599

600 601 602 603 604 605
int connection_check_relay_pass(http_parser_t *parser)
{
    int ret;
    ice_config_t *config = config_get_config();
    char *pass = config->relay_password;
    char *user = "relay";
Michael Smith's avatar
Michael Smith committed
606

607 608
    if(!pass || !user) {
        config_release_config();
609
        return 0;
610
    }
611

612 613 614
    ret = _check_pass_http(parser, user, pass);
    config_release_config();
    return ret;
615 616
}

617
int connection_check_source_pass(http_parser_t *parser, char *mount)
618
{
Michael Smith's avatar
Michael Smith committed
619 620
    ice_config_t *config = config_get_config();
    char *pass = config->source_password;
621
    char *user = "source";
622
    int ret;
Michael Smith's avatar
Michael Smith committed
623
    int ice_login = config->ice_login;
624
    char *protocol;
Michael Smith's avatar
Michael Smith committed
625 626 627

    mount_proxy *mountinfo = config->mounts;
    thread_mutex_lock(&(config_locks()->mounts_lock));
628

629 630
    while(mountinfo) {
        if(!strcmp(mountinfo->mountname, mount)) {
631 632 633 634
            if(mountinfo->password)
                pass = mountinfo->password;
            if(mountinfo->username)
                user = mountinfo->username;
635 636
            break;
        }
637
        mountinfo = mountinfo->next;
638 639
    }

Michael Smith's avatar
Michael Smith committed
640 641
    thread_mutex_unlock(&(config_locks()->mounts_lock));

642 643
    if(!pass) {
        WARN0("No source password set, rejecting source");
644
        config_release_config();
645 646 647
        return 0;
    }

648
    protocol = httpp_getvar(parser, HTTPP_VAR_PROTOCOL);
649 650 651 652 653 654 655 656 657 658 659
    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");
        }
660
    }
661
    config_release_config();
662
    return ret;
663 664
}

665

666 667 668
static void _handle_source_request(connection_t *con, 
        http_parser_t *parser, char *uri)
{
669
    client_t *client;
670
    source_t *source;
671

672
    client = client_create(con, parser);
673

674
    INFO1("Source logging in at mountpoint \"%s\"", uri);
675
                
676 677 678 679 680 681 682
    if (uri[0] != '/')
    {
        WARN0 ("source mountpoint not starting with /");
        client_send_401 (client);
        return;
    }

683
    if (!connection_check_source_pass(parser, uri)) {
Michael Smith's avatar
Michael Smith committed
684 685 686 687
        /* 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 */
688
        INFO1("Source (%s) attempted to login with invalid or missing password", uri);
689
        client_send_401(client);
690
        return;
691
    }
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    source = source_reserve (uri);
    if (source)
    {
        source->client = client;
        source->parser = parser;
        source->con = con;
        if (connection_complete_source (source) < 0)
        {
            source->client = NULL;
            source_free_source (source);
        }
        else
            thread_create ("Source Thread", source_client_thread,
                    source, THREAD_DETACHED);
    }
    else
    {
        client_send_404 (client, "Mountpoint in use");
710
        WARN1 ("Mountpoint %s in use", uri);
711
    }
712 713
}

714

715 716
static void _handle_stats_request(connection_t *con, 
        http_parser_t *parser, char *uri)
Jack Moffitt's avatar
Jack Moffitt committed
717
{
718
    stats_connection_t *stats;
719

720 721 722
    stats_event_inc(NULL, "stats_connections");
                
    if (!connection_check_admin_pass(parser)) {
723
        ERROR0("Bad password for stats connection");
724 725
        connection_close(con);
        httpp_destroy(parser);
726
        return;
727 728 729 730 731 732 733 734 735 736
    }
                    
    stats_event_inc(NULL, "stats");
                    
    /* create stats connection and create stats handler thread */
    stats = (stats_connection_t *)malloc(sizeof(stats_connection_t));
    stats->parser = parser;
    stats->con = con;
                    
    thread_create("Stats Connection", stats_connection, (void *)stats, THREAD_DETACHED);
737 738 739
}

static void _handle_get_request(connection_t *con,
740
        http_parser_t *parser, char *passed_uri)
741 742
{
    char *fullpath;
743
    client_t *client;
744
    int bytes;
745 746
    struct stat statbuf;
    source_t *source;
Michael Smith's avatar
Michael Smith committed
747 748 749
    int fileserve;
    char *host;
    int port;
750
    int i;
Karl Heyes's avatar
Karl Heyes committed
751 752
    char *serverhost = NULL;
    int serverport = 0;
753
    aliases *alias;
Michael Smith's avatar
Michael Smith committed
754 755
    ice_config_t *config;
    int client_limit;
756
    int ret;
757
    char *uri = passed_uri;
Michael Smith's avatar
Michael Smith committed
758 759 760 761 762

    config = config_get_config();
    fileserve = config->fileserve;
    host = config->hostname;
    port = config->port;
763 764 765 766 767 768 769 770
    for(i = 0; i < MAX_LISTEN_SOCKETS; i++) {
        if(global.serversock[i] == con->serversock) {
            serverhost = config->listeners[i].bind_address;
            serverport = config->listeners[i].port;
            break;
        }
    }
    alias = config->aliases;
Michael Smith's avatar
Michael Smith committed
771
    client_limit = config->client_limit;
772

773 774 775
    /* 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
776
    ** and directory server authorizers, which are looking for /GUID-xxxxxxxx 
777
    ** (where xxxxxx is the GUID in question) - this isn't implemented yet.
778 779 780 781
    ** we need to handle the latter two before the former, as the latter two
    ** aren't subject to the limits.
    */
    /* TODO: add GUID-xxxxxx */
782

783 784 785
    /* 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))) {
786 787
            uri = strdup (alias->destination);
            DEBUG2 ("alias has made %s into %s", passed_uri, uri);
788 789 790 791
            break;
        }
        alias = alias->next;
    }
792 793 794 795 796
    config_release_config();

    /* make a client */
    client = client_create(con, parser);
    stats_event_inc(NULL, "client_connections");
797

798
    /* Dispatch all admin requests */
799
    if (strncmp(uri, "/admin/", 7) == 0) {
800
        admin_handle_request(client, uri);
801
        if (uri != passed_uri) free (uri);
Michael Smith's avatar
Michael Smith committed
802 803 804
        return;
    }

805 806 807 808
    /* Here we are parsing the URI request to see
    ** if the extension is .xsl, if so, then process
    ** this request as an XSLT request
    */
809 810
    fullpath = util_get_path_from_normalised_uri(uri);
    if (util_check_valid_extension(fullpath) == XSLT_CONTENT) {
811 812
        /* If the file exists, then transform it, otherwise, write a 404 */
        if (stat(fullpath, &statbuf) == 0) {
813
            DEBUG0("Stats request, sending XSL transformed stats");
814
            client->respcode = 200;
815
            bytes = sock_write(client->con->sock, 
816 817 818
                    "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n");
            if(bytes > 0) client->con->sent_bytes = bytes;
            stats_transform_xslt(client, fullpath);
819 820 821
            client_destroy(client);
        }
        else {
822
            client_send_404(client, "The file you requested could not be found");
823
        }
824
        free(fullpath);
825
        if (uri != passed_uri) free (uri);
826
        return;
827
    }
828
    else if(fileserve && stat(fullpath, &statbuf) == 0 && 
Ed "oddsock" Zaleski's avatar
Ed "oddsock" Zaleski committed
829
#ifdef _WIN32
830
            ((statbuf.st_mode) & _S_IFREG))
Ed "oddsock" Zaleski's avatar
Ed "oddsock" Zaleski committed
831
#else
832
            S_ISREG(statbuf.st_mode)) 
Ed "oddsock" Zaleski's avatar
Ed "oddsock" Zaleski committed
833
#endif
Michael Smith's avatar
Michael Smith committed
834
    {
835
        fserve_client_create(client, fullpath);
836
        free(fullpath);
837
        if (uri != passed_uri) free (uri);
838 839
        return;
    }
840 841 842 843 844 845
    free(fullpath);

    if(strcmp(util_get_extension(uri), "m3u") == 0) {
        char *sourceuri = strdup(uri);
        char *dot = strrchr(sourceuri, '.');
        *dot = 0;
846 847
        client->respcode = 200;
        bytes = sock_write(client->con->sock,
848 849
                    "HTTP/1.0 200 OK\r\n"
                    "Content-Type: audio/x-mpegurl\r\n\r\n"
850
                    "http://%s:%d%s\r\n", 
Michael Smith's avatar
Michael Smith committed
851 852
                    host, 
                    port,
853 854
                    sourceuri
                    );
855 856
        if(bytes > 0) client->con->sent_bytes = bytes;
        client_destroy(client);
857
        free(sourceuri);
858
        if (uri != passed_uri) free (uri);
859 860 861
        return;
    }

862 863 864
    global_lock();
    if (global.clients >= client_limit) {
        global_unlock();
865 866
        client_send_404(client,
                "The server is already full. Try again later.");
867
        if (uri != passed_uri) free (uri);
868
        return;
869 870 871 872 873 874
    }
    global_unlock();
                    
    avl_tree_rlock(global.source_tree);
    source = source_find_mount(uri);
    if (source) {
875
        DEBUG0("Source found for client");
Michael Smith's avatar
Michael Smith committed
876 877 878 879 880 881 882

        /* The source may not be the requested source - it might have gone
         * via one or more fallbacks. We only reject it for no-mount if it's
         * the originally requested source
         */
        if(strcmp(uri, source->mount) == 0 && source->no_mount) {
            avl_tree_unlock(global.source_tree);
883
            client_send_404(client, "This mount is unavailable.");
884
            if (uri != passed_uri) free (uri);
Michael Smith's avatar
Michael Smith committed
885
            return;
886 887 888 889 890 891
        }
        if (source->running == 0)
        {
            avl_tree_unlock(global.source_tree);
            DEBUG0("inactive source, client dropped");
            client_send_404(client, "This mount is unavailable.");
892
            if (uri != passed_uri) free (uri);
893
            return;
Michael Smith's avatar
Michael Smith committed
894 895 896 897
        }

        /* Check for any required authentication first */
        if(source->authenticator != NULL) {
898 899
            ret = auth_check_client(source, client);
            if(ret != AUTH_OK) {
900
                avl_tree_unlock(global.source_tree);
901 902 903 904 905 906 907 908
                if (ret == AUTH_FORBIDDEN) {
                    INFO1("Client attempted to log multiple times to source "
                        "(\"%s\")", uri);
                    client_send_403(client);
                }
                else {
                /* If not FORBIDDEN, default to 401 */
                    INFO1("Client attempted to log in to source (\"%s\")with "
Michael Smith's avatar
Michael Smith committed
909
                        "incorrect or missing password", uri);
910 911
                    client_send_401(client);
                }
912
                if (uri != passed_uri) free (uri);
Michael Smith's avatar
Michael Smith committed
913 914 915 916 917
                return;
            }
        }

        /* And then check that there's actually room in the server... */
918 919 920
        global_lock();
        if (global.clients >= client_limit) {
            global_unlock();
921
            avl_tree_unlock(global.source_tree);
922 923
            client_send_404(client, 
                    "The server is already full. Try again later.");
924
            if (uri != passed_uri) free (uri);
925
            return;
926
        }
Michael Smith's avatar
Michael Smith committed
927 928 929 930
        /* Early-out for per-source max listeners. This gets checked again
         * by the source itself, later. This route gives a useful message to
         * the client, also.
         */
Michael Smith's avatar
Michael Smith committed
931 932 933
        else if(source->max_listeners != -1 && 
                source->listeners >= source->max_listeners) 
        {
934
            global_unlock();
Michael Smith's avatar
Michael Smith committed
935
            avl_tree_unlock(global.source_tree);
936 937
            client_send_404(client, 
                    "Too many clients on this mountpoint. Try again later.");
938
            if (uri != passed_uri) free (uri);
Michael Smith's avatar
Michael Smith committed
939 940
            return;
        }
941 942 943
        global.clients++;
        global_unlock();
                        
Karl Heyes's avatar
Karl Heyes committed
944
        source->format->create_client_data (source, client);
Michael Smith's avatar
Michael Smith committed
945 946

        source->format->client_send_headers(source->format, source, client);
947 948
                        
        bytes = sock_write(client->con->sock, "\r\n");
949
        if(bytes > 0) client->con->sent_bytes += bytes;
950 951
                            
        sock_set_blocking(client->con->sock, SOCK_NONBLOCK);
952
        sock_set_nodelay(client->con->sock);
953 954 955 956 957 958 959 960 961
                        
        avl_tree_wlock(source->pending_tree);
        avl_insert(source->pending_tree, (void *)client);
        avl_tree_unlock(source->pending_tree);
    }
                    
    avl_tree_unlock(global.source_tree);
                    
    if (!source) {
962 963
        DEBUG0("Source not found for client");
        client_send_404(client, "The source you requested could not be found.");
964
    }
965
    if (uri != passed_uri) free (uri);
966 967 968 969
}

static void *_handle_connection(void *arg)
{
970 971 972
    char header[4096];
    connection_t *con;
    http_parser_t *parser;
973
    char *rawuri, *uri;
974
    client_t *client;
Jack Moffitt's avatar
Jack Moffitt committed
975

976
    while (global.running == ICE_RUNNING) {
Jack Moffitt's avatar
Jack Moffitt committed
977

978 979
        /* grab a connection and set the socket to blocking */
        while ((con = _get_connection())) {
Michael Smith's avatar
Michael Smith committed
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994

            /* Handle meta-connections */
            if(con->event_number > 0) {
                switch(con->event_number) {
                    case EVENT_CONFIG_READ:
                        event_config_read(con->event);
                        break;
                    default:
                        ERROR1("Unknown event number: %d", con->event_number);
                        break;
                }
                free(con);
                continue;
            }

995
            stats_event_inc(NULL, "connections");
Jack Moffitt's avatar
Jack Moffitt committed
996

997
            sock_set_blocking(con->sock, SOCK_BLOCK);
Jack Moffitt's avatar
Jack Moffitt committed
998

999
            /* fill header with the http header */
1000 1001
            memset(header, 0, sizeof (header));
            if (util_read_header(con->sock, header, sizeof (header)) == 0) {
1002 1003 1004 1005
                /* either we didn't get a complete header, or we timed out */
                connection_close(con);
                continue;
            }
Jack Moffitt's avatar
Jack Moffitt committed
1006

1007 1008 1009 1010 1011 1012
            parser = httpp_create_parser();
            httpp_initialize(parser, NULL);
            if (httpp_parse(parser, header, strlen(header))) {
                /* handle the connection or something */
                
                if (strcmp("ICE",  httpp_getvar(parser, HTTPP_VAR_PROTOCOL)) &&
1013
                    strcmp("HTTP", httpp_getvar(parser, HTTPP_VAR_PROTOCOL))) {
1014
                    ERROR0("Bad HTTP protocol detected");
1015 1016 1017 1018
                    connection_close(con);
                    httpp_destroy(parser);
                    continue;
                }
Jack Moffitt's avatar
Jack Moffitt committed
1019

1020 1021 1022 1023
                rawuri = httpp_getvar(parser, HTTPP_VAR_URI);
                uri = util_normalise_uri(rawuri);

                if(!uri) {
1024
                    client = client_create(con, parser);
1025
                    client_send_404(client, "The path you requested was invalid");
1026 1027
                    continue;
                }
1028

1029
                if (parser->req_type == httpp_req_source) {
1030 1031 1032 1033 1034 1035 1036 1037 1038
                    _handle_source_request(con, parser, uri);
                }
                else if (parser->req_type == httpp_req_stats) {
                    _handle_stats_request(con, parser, uri);
                }
                else if (parser->req_type == httpp_req_get) {
                    _handle_get_request(con, parser, uri);
                }
                else {
1039
                    ERROR0("Wrong request type from client");
1040 1041
                    connection_close(con);
                    httpp_destroy(parser);
1042 1043 1044
                }

                free(uri);
1045
                continue;
1046
            } 
1047