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

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

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

36
#include "compat.h"
Jack Moffitt's avatar
Jack Moffitt committed
37

Marvin Scholz's avatar
Marvin Scholz committed
38 39 40 41
#include "common/thread/thread.h"
#include "common/avl/avl.h"
#include "common/net/sock.h"
#include "common/httpp/httpp.h"
Jack Moffitt's avatar
Jack Moffitt committed
42

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

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

#define CATMODULE "connection"

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
/* 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.
*/

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

typedef struct _thread_queue_tag {
91 92
    thread_type *thread_id;
    struct _thread_queue_tag *next;
Jack Moffitt's avatar
Jack Moffitt committed
93 94
} thread_queue_t;

95
static spin_t _connection_lock; // protects _current_id, _con_queue, _con_queue_tail
96
static volatile unsigned long _current_id = 0;
Jack Moffitt's avatar
Jack Moffitt committed
97 98
static int _initialized = 0;

99 100
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;
101
static int tls_ok;
102
static tls_ctx_t *tls_ctx;
103

104
/* filtering client connection based on IP */
105
static matchfile_t *banned_ip, *allowed_ip;
106

107
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
108

109
static void _handle_connection(void);
110
static void get_tls_certificate(ice_config_t *config);
Jack Moffitt's avatar
Jack Moffitt committed
111 112 113

void connection_initialize(void)
{
Marvin Scholz's avatar
Marvin Scholz committed
114 115
    if (_initialized)
        return;
116

117
    thread_spin_create (&_connection_lock);
118
    thread_mutex_create(&move_clients_mutex);
119
    thread_rwlock_create(&_source_shutdown_rwlock);
120
    thread_cond_create(&global.shutdown_cond);
121 122 123 124
    _req_queue = NULL;
    _req_queue_tail = &_req_queue;
    _con_queue = NULL;
    _con_queue_tail = &_con_queue;
Jack Moffitt's avatar
Jack Moffitt committed
125

126
    _initialized = 1;
Jack Moffitt's avatar
Jack Moffitt committed
127 128 129 130
}

void connection_shutdown(void)
{
Marvin Scholz's avatar
Marvin Scholz committed
131 132
    if (!_initialized)
        return;
133

134
    tls_ctx_unref(tls_ctx);
135 136 137
    matchfile_release(banned_ip);
    matchfile_release(allowed_ip);
 
138
    thread_cond_destroy(&global.shutdown_cond);
139
    thread_rwlock_destroy(&_source_shutdown_rwlock);
140
    thread_spin_destroy (&_connection_lock);
141
    thread_mutex_destroy(&move_clients_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
142

143
    _initialized = 0;
Jack Moffitt's avatar
Jack Moffitt committed
144 145
}

146 147
void connection_reread_config(struct ice_config_tag *config)
{
148
    get_tls_certificate(config);
149 150
}

Jack Moffitt's avatar
Jack Moffitt committed
151 152
static unsigned long _next_connection_id(void)
{
153
    unsigned long id;
Jack Moffitt's avatar
Jack Moffitt committed
154

155
    thread_spin_lock(&_connection_lock);
156
    id = _current_id++;
157
    thread_spin_unlock(&_connection_lock);
Jack Moffitt's avatar
Jack Moffitt committed
158

159
    return id;
Jack Moffitt's avatar
Jack Moffitt committed
160 161
}

162

163
#ifdef ICECAST_CAP_TLS
164
static void get_tls_certificate(ice_config_t *config)
165
{
166 167
    const char *keyfile;

168
    config->tls_ok = tls_ok = 0;
169

170 171 172 173
    keyfile = config->tls_context.key_file;
    if (!keyfile)
        keyfile = config->tls_context.cert_file;

174
    tls_ctx_unref(tls_ctx);
175
    tls_ctx = tls_ctx_new(config->tls_context.cert_file, keyfile, config->tls_context.cipher_list);
176 177
    if (!tls_ctx) {
        ICECAST_LOG_INFO("No TLS capability on any configured ports");
178
        return;
179 180
    }

181
    config->tls_ok = tls_ok = 1;
182 183 184
}


185
/* handlers for reading and writing a connection_t when there is TLS
186 187
 * configured on the listening port
 */
188
static int connection_read_tls(connection_t *con, void *buf, size_t len)
189
{
190
    ssize_t bytes = tls_read(con->tls, buf, len);
191

Marvin Scholz's avatar
Marvin Scholz committed
192
    if (bytes < 0) {
193
        if (tls_want_io(con->tls) > 0)
194
            return -1;
195 196 197 198 199
        con->error = 1;
    }
    return bytes;
}

200
static int connection_send_tls(connection_t *con, const void *buf, size_t len)
201
{
202
    ssize_t bytes = tls_write(con->tls, buf, len);
203

Marvin Scholz's avatar
Marvin Scholz committed
204
    if (bytes < 0) {
205 206
        if (tls_want_io(con->tls) > 0)
            return -1;
207
        con->error = 1;
Marvin Scholz's avatar
Marvin Scholz committed
208
    } else {
209
        con->sent_bytes += bytes;
Marvin Scholz's avatar
Marvin Scholz committed
210
    }
211 212 213 214
    return bytes;
}
#else

215 216
/* TLS not compiled in, so at least log it */
static void get_tls_certificate(ice_config_t *config)
217
{
218
    tls_ok = 0;
219
    ICECAST_LOG_INFO("No TLS capability. "
Philipp Schafft's avatar
Philipp Schafft committed
220
                     "Rebuild Icecast with OpenSSL support to enable this.");
221
}
222
#endif /* ICECAST_CAP_TLS */
223 224 225 226 227


/* handlers (default) for reading and writing a connection_t, no encrpytion
 * used just straight access to the socket
 */
Marvin Scholz's avatar
Marvin Scholz committed
228
static int connection_read(connection_t *con, void *buf, size_t len)
229
{
Marvin Scholz's avatar
Marvin Scholz committed
230
    int bytes = sock_read_bytes(con->sock, buf, len);
231 232
    if (bytes == 0)
        con->error = 1;
Marvin Scholz's avatar
Marvin Scholz committed
233
    if (bytes == -1 && !sock_recoverable(sock_error()))
234 235 236 237
        con->error = 1;
    return bytes;
}

Marvin Scholz's avatar
Marvin Scholz committed
238
static int connection_send(connection_t *con, const void *buf, size_t len)
239
{
Marvin Scholz's avatar
Marvin Scholz committed
240 241 242
    int bytes = sock_write_bytes(con->sock, buf, len);
    if (bytes < 0) {
        if (!sock_recoverable(sock_error()))
243
            con->error = 1;
Marvin Scholz's avatar
Marvin Scholz committed
244
    } else {
245
        con->sent_bytes += bytes;
Marvin Scholz's avatar
Marvin Scholz committed
246
    }
247 248 249
    return bytes;
}

250 251
connection_t *connection_create (sock_t sock, sock_t serversock, char *ip)
{
252
    connection_t *con;
253
    con = (connection_t *)calloc(1, sizeof(connection_t));
Marvin Scholz's avatar
Marvin Scholz committed
254 255
    if (con) {
        con->sock       = sock;
256
        con->serversock = serversock;
Marvin Scholz's avatar
Marvin Scholz committed
257 258 259
        con->con_time   = time(NULL);
        con->id         = _next_connection_id();
        con->ip         = ip;
260
        con->tlsmode    = ICECAST_TLSMODE_AUTO;
Marvin Scholz's avatar
Marvin Scholz committed
261 262
        con->read       = connection_read;
        con->send       = connection_send;
263
    }
Michael Smith's avatar
Michael Smith committed
264

265
    return con;
266 267
}

268
/* prepare connection for interacting over a TLS connection
269
 */
270
void connection_uses_tls(connection_t *con)
271
{
272
#ifdef ICECAST_CAP_TLS
273
    if (con->tls)
274 275
        return;

276
    con->tlsmode = ICECAST_TLSMODE_RFC2818;
277 278
    con->read = connection_read_tls;
    con->send = connection_send_tls;
279 280 281
    con->tls = tls_new(tls_ctx);
    tls_set_incoming(con->tls);
    tls_set_socket(con->tls, con->sock);
282 283 284
#endif
}

285 286 287 288 289
ssize_t connection_read_bytes(connection_t *con, void *buf, size_t len)
{
    return con->read(con, buf, len);
}

290
static sock_t wait_for_serversock(int timeout)
291 292
{
#ifdef HAVE_POLL
293
    struct pollfd ufds [global.server_sockets];
294 295 296 297 298 299 300 301 302 303
    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) {
304
        return SOCK_ERROR;
Marvin Scholz's avatar
Marvin Scholz committed
305
    } else if(ret == 0) {
306
        return SOCK_ERROR;
Marvin Scholz's avatar
Marvin Scholz committed
307
    } else {
308
        int dst;
309
        for(i=0; i < global.server_sockets; i++) {
310
            if(ufds[i].revents & POLLIN)
311
                return ufds[i].fd;
Marvin Scholz's avatar
Marvin Scholz committed
312 313
            if(ufds[i].revents & (POLLHUP|POLLERR|POLLNVAL)) {
                if (ufds[i].revents & (POLLHUP|POLLERR)) {
314
                    sock_close (global.serversock[i]);
315
                    ICECAST_LOG_WARN("Had to close a listening socket");
316
                }
317
                global.serversock[i] = SOCK_ERROR;
318
            }
319
        }
320
        /* remove any closed sockets */
Marvin Scholz's avatar
Marvin Scholz committed
321
        for(i=0, dst=0; i < global.server_sockets; i++) {
322
            if (global.serversock[i] == SOCK_ERROR)
323
            continue;
324
            if (i!=dst)
325
            global.serversock[dst] = global.serversock[i];
326 327 328
            dst++;
        }
        global.server_sockets = dst;
329
        return SOCK_ERROR;
330 331 332 333 334
    }
#else
    fd_set rfds;
    struct timeval tv, *p=NULL;
    int i, ret;
335
    sock_t max = SOCK_ERROR;
336 337 338 339 340

    FD_ZERO(&rfds);

    for(i=0; i < global.server_sockets; i++) {
        FD_SET(global.serversock[i], &rfds);
341
        if (max == SOCK_ERROR || global.serversock[i] > max)
342 343 344 345 346
            max = global.serversock[i];
    }

    if(timeout >= 0) {
        tv.tv_sec = timeout/1000;
347
        tv.tv_usec = (timeout % 1000) * 1000;
348 349 350 351 352
        p = &tv;
    }

    ret = select(max+1, &rfds, NULL, NULL, p);
    if(ret < 0) {
353
        return SOCK_ERROR;
Marvin Scholz's avatar
Marvin Scholz committed
354
    } else if(ret == 0) {
355
        return SOCK_ERROR;
Marvin Scholz's avatar
Marvin Scholz committed
356
    } else {
357 358 359 360
        for(i=0; i < global.server_sockets; i++) {
            if(FD_ISSET(global.serversock[i], &rfds))
                return global.serversock[i];
        }
361
        return SOCK_ERROR; /* Should be impossible, stop compiler warnings */
362 363 364 365
    }
#endif
}

366
static connection_t *_accept_connection(int duration)
Jack Moffitt's avatar
Jack Moffitt committed
367
{
368
    sock_t sock, serversock;
369
    char *ip;
Jack Moffitt's avatar
Jack Moffitt committed
370

371
    serversock = wait_for_serversock (duration);
372
    if (serversock == SOCK_ERROR)
373
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
374

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

378
    sock = sock_accept(serversock, ip, MAX_ADDR_LEN);
Marvin Scholz's avatar
Marvin Scholz committed
379
    if (sock != SOCK_ERROR) {
380
        connection_t *con = NULL;
381
        /* Make any IPv4 mapped IPv6 address look like a normal IPv4 address */
Marvin Scholz's avatar
Marvin Scholz committed
382 383
        if (strncmp(ip, "::ffff:", 7) == 0)
            memmove(ip, ip+7, strlen (ip+7)+1);
Jack Moffitt's avatar
Jack Moffitt committed
384

385 386
        if (matchfile_match_allow_deny(allowed_ip, banned_ip, ip))
            con = connection_create (sock, serversock, ip);
387 388
        if (con)
            return con;
Marvin Scholz's avatar
Marvin Scholz committed
389 390 391
        sock_close(sock);
    } else {
        if (!sock_recoverable(sock_error())) {
392
            ICECAST_LOG_WARN("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
Marvin Scholz's avatar
Marvin Scholz committed
393
            thread_sleep(500000);
394
        }
395 396 397
    }
    free(ip);
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
398 399 400
}


401 402 403 404
/* 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
 */
405
static void _add_connection(client_queue_t *node)
Jack Moffitt's avatar
Jack Moffitt committed
406
{
407
    thread_spin_lock(&_connection_lock);
408
    *_con_queue_tail = node;
409 410
    _con_queue_tail = (volatile client_queue_t **) &node->next;
    thread_spin_unlock(&_connection_lock);
Jack Moffitt's avatar
Jack Moffitt committed
411 412 413
}


414 415 416 417 418 419
/* 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
420

Marvin Scholz's avatar
Marvin Scholz committed
421
    thread_spin_lock(&_connection_lock);
422

Marvin Scholz's avatar
Marvin Scholz committed
423
    if (_con_queue){
424 425 426 427
        node = (client_queue_t *)_con_queue;
        _con_queue = node->next;
        if (_con_queue == NULL)
            _con_queue_tail = &_con_queue;
428
        node->next = NULL;
429
    }
430

Marvin Scholz's avatar
Marvin Scholz committed
431
    thread_spin_unlock(&_connection_lock);
432 433
    return node;
}
Jack Moffitt's avatar
Jack Moffitt committed
434 435


436
/* run along queue checking for any data that has come in or a timeout */
437
static void process_request_queue (void)
438 439
{
    client_queue_t **node_ref = (client_queue_t **)&_req_queue;
440 441 442 443 444 445
    ice_config_t *config;
    int timeout;
    char peak;

    config = config_get_config();
    timeout = config->header_timeout;
446
    config_release_config();
Jack Moffitt's avatar
Jack Moffitt committed
447

Marvin Scholz's avatar
Marvin Scholz committed
448
    while (*node_ref) {
449 450 451 452
        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
453

454
        if (client->con->tlsmode == ICECAST_TLSMODE_AUTO || client->con->tlsmode == ICECAST_TLSMODE_AUTO_NO_PLAIN) {
455 456
            if (recv(client->con->sock, &peak, 1, MSG_PEEK) == 1) {
                if (peak == 0x16) { /* TLS Record Protocol Content type 0x16 == Handshake */
457
                    connection_uses_tls(client->con);
458 459 460 461
                }
            }
        }

Marvin Scholz's avatar
Marvin Scholz committed
462 463
        if (len > 0) {
            if (client->con->con_time + timeout <= time(NULL)) {
464
                len = 0;
Marvin Scholz's avatar
Marvin Scholz committed
465 466 467
            } else {
                len = client_read_bytes(client, buf, len);
            }
468
        }
Jack Moffitt's avatar
Jack Moffitt committed
469

Marvin Scholz's avatar
Marvin Scholz committed
470
        if (len > 0) {
471 472 473
            int pass_it = 1;
            char *ptr;

474 475
            /* handle \n, \r\n and nsvcap which for some strange reason has
             * EOL as \r\r\n */
476
            node->offset += len;
Marvin Scholz's avatar
Marvin Scholz committed
477 478 479
            client->refbuf->data[node->offset] = '\000';
            do {
                if (node->shoutcast == 1) {
480
                    /* password line */
481 482
                    if (strstr (client->refbuf->data, "\r\r\n") != NULL)
                        break;
483 484 485 486 487 488 489
                    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 */
Marvin Scholz's avatar
Marvin Scholz committed
490 491
                ptr = strstr(client->refbuf->data, "\r\r\n\r\r\n");
                if (ptr) {
492 493 494
                    node->stream_offset = (ptr+6) - client->refbuf->data;
                    break;
                }
Marvin Scholz's avatar
Marvin Scholz committed
495 496
                ptr = strstr(client->refbuf->data, "\r\n\r\n");
                if (ptr) {
497 498 499
                    node->stream_offset = (ptr+4) - client->refbuf->data;
                    break;
                }
Marvin Scholz's avatar
Marvin Scholz committed
500 501
                ptr = strstr(client->refbuf->data, "\n\n");
                if (ptr) {
502 503 504 505 506
                    node->stream_offset = (ptr+2) - client->refbuf->data;
                    break;
                }
                pass_it = 0;
            } while (0);
Jack Moffitt's avatar
Jack Moffitt committed
507

Marvin Scholz's avatar
Marvin Scholz committed
508
            if (pass_it) {
509 510 511 512
                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;
Marvin Scholz's avatar
Marvin Scholz committed
513
                _add_connection(node);
514
                continue;
515
            }
Marvin Scholz's avatar
Marvin Scholz committed
516 517
        } else {
            if (len == 0 || client->con->error) {
518 519 520
                if ((client_queue_t **)_req_queue_tail == &node->next)
                    _req_queue_tail = (volatile client_queue_t **)node_ref;
                *node_ref = node->next;
Marvin Scholz's avatar
Marvin Scholz committed
521 522
                client_destroy(client);
                free(node);
523 524 525 526
                continue;
            }
        }
        node_ref = &node->next;
527
    }
528
    _handle_connection();
Jack Moffitt's avatar
Jack Moffitt committed
529 530
}

531

532 533 534
/* add node to the queue of requests. This is where the clients are when
 * initial http details are read.
 */
Marvin Scholz's avatar
Marvin Scholz committed
535
static void _add_request_queue(client_queue_t *node)
536 537 538
{
    *_req_queue_tail = node;
    _req_queue_tail = (volatile client_queue_t **)&node->next;
Jack Moffitt's avatar
Jack Moffitt committed
539 540
}

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
static client_queue_t *create_client_node(client_t *client)
{
    client_queue_t *node = calloc (1, sizeof (client_queue_t));
    ice_config_t *config;
    listener_t *listener;

    if (!node)
        return NULL;

    node->client = client;

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

    if (listener) {
        if (listener->shoutcast_compat)
            node->shoutcast = 1;
558 559
        client->con->tlsmode = listener->tls;
        if (listener->tls == ICECAST_TLSMODE_RFC2818 && tls_ok)
560
            connection_uses_tls(client->con);
561 562 563 564 565 566 567 568
        if (listener->shoutcast_mount)
            node->shoutcast_mount = strdup(listener->shoutcast_mount);
    }

    config_release_config();

    return node;
}
569

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
void connection_queue(connection_t *con)
{
    client_queue_t *node;
    client_t *client = NULL;

    global_lock();
    if (client_create(&client, con, NULL) < 0) {
        global_unlock();
        client_send_error(client, 403, 1, "Icecast connection limit reached");
        /* don't be too eager as this is an imposed hard limit */
        thread_sleep(400000);
        return;
    }

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

    if (sock_set_blocking(client->con->sock, 0) || sock_set_nodelay(client->con->sock)) {
        global_unlock();
589
        ICECAST_LOG_WARN("Failed to set tcp options on client connection, dropping");
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
        client_destroy(client);
        return;
    }
    node = create_client_node(client);
    global_unlock();

    if (node == NULL) {
        client_destroy(client);
        return;
    }

    _add_request_queue(node);
    stats_event_inc(NULL, "connections");
}

Marvin Scholz's avatar
Marvin Scholz committed
605
void connection_accept_loop(void)
Jack Moffitt's avatar
Jack Moffitt committed
606
{
607
    connection_t *con;
608
    ice_config_t *config;
609
    int duration = 300;
610

Marvin Scholz's avatar
Marvin Scholz committed
611
    config = config_get_config();
612
    get_tls_certificate(config);
Marvin Scholz's avatar
Marvin Scholz committed
613
    config_release_config();
Jack Moffitt's avatar
Jack Moffitt committed
614

Marvin Scholz's avatar
Marvin Scholz committed
615
    while (global.running == ICECAST_RUNNING) {
616
        con = _accept_connection (duration);
617

Marvin Scholz's avatar
Marvin Scholz committed
618
        if (con) {
619
            connection_queue(con);
620
            duration = 5;
Marvin Scholz's avatar
Marvin Scholz committed
621
        } else {
622 623
            if (_req_queue == NULL)
                duration = 300; /* use longer timeouts when nothing waiting */
624
        }
Marvin Scholz's avatar
Marvin Scholz committed
625
        process_request_queue();
626
    }
Jack Moffitt's avatar
Jack Moffitt committed
627

628 629 630
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

631 632 633
    /* 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
634 635
}

636 637 638

/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
639
 */
Marvin Scholz's avatar
Marvin Scholz committed
640
int connection_complete_source(source_t *source, int response)
641
{
642
    ice_config_t *config;
643

Marvin Scholz's avatar
Marvin Scholz committed
644
    global_lock();
645
    ICECAST_LOG_DEBUG("sources count is %d", global.sources);
646

647
    config = config_get_config();
Marvin Scholz's avatar
Marvin Scholz committed
648
    if (global.sources < config->source_limit) {
649
        const char *contenttype;
650
        mount_proxy *mountinfo;
651 652 653 654
        format_type_t format_type;

        /* setup format handler */
        contenttype = httpp_getvar (source->parser, "content-type");
Marvin Scholz's avatar
Marvin Scholz committed
655 656
        if (contenttype != NULL) {
            format_type = format_get_type(contenttype);
657

Marvin Scholz's avatar
Marvin Scholz committed
658
            if (format_type == FORMAT_ERROR) {
659
                config_release_config();
660
                global_unlock();
661
                if (response) {
662
                    client_send_error(source->client, 403, 1, "Content-type not supported");
663 664
                    source->client = NULL;
                }
665
                ICECAST_LOG_WARN("Content-type \"%s\" not supported, dropping source", contenttype);
666 667
                return -1;
            }
668 669 670 671
        } else if (source->parser->req_type == httpp_req_put) {
            config_release_config();
            global_unlock();
            if (response) {
672
                client_send_error(source->client, 403, 1, "No Content-type given");
673 674 675 676 677 678 679 680
                source->client = NULL;
            }
            ICECAST_LOG_ERROR("Content-type not given in PUT request, dropping source");
            return -1;
        } else {
            ICECAST_LOG_ERROR("No content-type header, falling back to backwards compatibility mode "
                    "for icecast 1.x relays. Assuming content is mp3. This behaviour is deprecated "
                    "and the source client will NOT work with future Icecast versions!");
681
            format_type = FORMAT_TYPE_GENERIC;
682 683
        }

Marvin Scholz's avatar
Marvin Scholz committed
684
        if (format_get_plugin (format_type, source) < 0) {
685 686
            global_unlock();
            config_release_config();
Marvin Scholz's avatar
Marvin Scholz committed
687
            if (response) {
688
                client_send_error(source->client, 403, 1, "internal format allocation problem");
689 690
                source->client = NULL;
            }
691
            ICECAST_LOG_WARN("plugin format failed for \"%s\"", source->mount);
692 693 694
            return -1;
        }

695
        global.sources++;
Marvin Scholz's avatar
Marvin Scholz committed
696
        stats_event_args(NULL, "sources", "%d", global.sources);
697
        global_unlock();
698

699
        source->running = 1;
Marvin Scholz's avatar
Marvin Scholz committed
700 701
        mountinfo = config_find_mount(config, source->mount, MOUNT_TYPE_NORMAL);
        source_update_settings(config, source, mountinfo);
702
        config_release_config();
703
        slave_rebuild_mounts();
704 705

        source->shutdown_rwlock = &_source_shutdown_rwlock;
706
        ICECAST_LOG_DEBUG("source is ready to start");
707 708 709

        return 0;
    }
710
    ICECAST_LOG_WARN("Request to add source when maximum source limit "
Marvin Scholz's avatar
Marvin Scholz committed
711
        "reached %d", global.sources);
712 713 714 715

    global_unlock();
    config_release_config();

Marvin Scholz's avatar
Marvin Scholz committed
716
    if (response) {
717
        client_send_error(source->client, 403, 1, "too many sources connected");
718 719
        source->client = NULL;
    }
720 721 722 723

    return -1;
}

Marvin Scholz's avatar
Marvin Scholz committed
724
static inline void source_startup(client_t *client, const char *uri)
725 726
{
    source_t *source;
Marvin Scholz's avatar
Marvin Scholz committed
727
    source = source_reserve(uri);
728

Marvin Scholz's avatar
Marvin Scholz committed
729
    if (source) {
730
        source->client = client;
731 732
        source->parser = client->parser;
        source->con = client->con;
Marvin Scholz's avatar
Marvin Scholz committed
733 734 735
        if (connection_complete_source(source, 1) < 0) {
            source_clear_source(source);
            source_free_source(source);
736 737 738
            return;
        }
        client->respcode = 200;
Philipp Schafft's avatar
Philipp Schafft committed
739 740 741 742 743
        if (client->protocol == ICECAST_PROTOCOL_SHOUTCAST) {
            client->respcode = 200;
            /* send this non-blocking but if there is only a partial write
             * then leave to header timeout */
            sock_write (client->con->sock, "OK2\r\nicy-caps:11\r\n\r\n");
744
            source->shoutcast_compat = 1;
Marvin Scholz's avatar
Marvin Scholz committed
745
            source_client_callback(client, source);
Philipp Schafft's avatar
Philipp Schafft committed
746
        } else {
Marvin Scholz's avatar
Marvin Scholz committed
747
            refbuf_t *ok = refbuf_new(PER_CLIENT_REFBUF_SIZE);
748
            const char *expectcontinue;
749
            const char *transfer_encoding;
750
            int status_to_send = 200;
751
            ssize_t ret;
752

753 754 755 756 757 758 759 760 761
            transfer_encoding = httpp_getvar(source->parser, "transfer-encoding");
            if (transfer_encoding && strcasecmp(transfer_encoding, HTTPP_ENCODING_IDENTITY) != 0) {
                client->encoding = httpp_encoding_new(transfer_encoding);
                if (!client->encoding) {
                    client_send_error(client, 501, 1, "Unimplemented");
                    return;
                }
            }

762 763 764 765 766 767 768
            /* For PUT support we check for 100-continue and send back a 100 to stay in spec */
            expectcontinue = httpp_getvar (source->parser, "expect");

            if (expectcontinue != NULL) {
#ifdef HAVE_STRCASESTR
                if (strcasestr (expectcontinue, "100-continue") != NULL)
#else
769
                ICECAST_LOG_WARN("OS doesn't support case insensitive substring checks...");
770 771 772 773 774 775 776
                if (strstr (expectcontinue, "100-continue") != NULL)
#endif
                {
                    status_to_send = 100;
                }
            }

777
            client->respcode = 200;
778 779
            ret = util_http_build_header(ok->data, PER_CLIENT_REFBUF_SIZE, 0, 0, status_to_send, NULL, NULL, NULL, NULL, NULL, client);
            snprintf(ok->data + ret, PER_CLIENT_REFBUF_SIZE - ret, "Content-Length: 0\r\n\r\n");
Marvin Scholz's avatar
Marvin Scholz committed
780
            ok->len = strlen(ok->data);
781 782 783
            /* we may have unprocessed data read in, so don't overwrite it */
            ok->associated = client->refbuf;
            client->refbuf = ok;
Marvin Scholz's avatar
Marvin Scholz committed
784
            fserve_add_client_callback(client, source_client_callback, source);
785
        }
Marvin Scholz's avatar
Marvin Scholz committed
786
    } else {
787
        client_send_error(client, 403, 1, "Mountpoint in use");
788
        ICECAST_LOG_WARN("Mountpoint %s in use", uri);
789
    }
790 791
}

Philipp Schafft's avatar
Philipp Schafft committed
792
/* only called for native icecast source clients */
Marvin Scholz's avatar
Marvin Scholz committed
793
static void _handle_source_request(client_t *client, const char *uri)
Jack Moffitt's avatar
Jack Moffitt committed
794
{
795 796
    ICECAST_LOG_INFO("Source logging in at mountpoint \"%s\" from %s as role %s",
        uri, client->con->ip, client->role);
797

Marvin Scholz's avatar
Marvin Scholz committed
798
    if (uri[0] != '/') {
Philipp Schafft's avatar
Philipp Schafft committed
799 800
        ICECAST_LOG_WARN("source mountpoint not starting with /");
        client_send_error(client, 400, 1, "source mountpoint not starting with /");
801
        return;
802
    }
803

Philipp Schafft's avatar
Philipp Schafft committed
804 805 806 807
    source_startup(client, uri);
}


Marvin Scholz's avatar
Marvin Scholz committed
808
static void _handle_stats_request(client_t *client, char *uri)
Philipp Schafft's avatar
Philipp Schafft committed
809 810 811
{
    stats_event_inc(NULL, "stats_connections");

812
    client->respcode = 200;
813
    snprintf (client->refbuf->data, PER_CLIENT_REFBUF_SIZE,
Marvin Scholz's avatar
Marvin Scholz committed
814 815 816
        "HTTP/1.0 200 OK\r\n\r\n");
    client->refbuf->len = strlen(client->refbuf->data);
    fserve_add_client_callback(client, stats_callback, NULL);
817 818
}

Philipp Schafft's avatar
Philipp Schafft committed
819 820 821
/* if 0 is returned then the client should not be touched, however if -1
 * is returned then the caller is responsible for handling the client
 */
Marvin Scholz's avatar
Marvin Scholz committed
822
static int __add_listener_to_source(source_t *source, client_t *client)
823
{
Philipp Schafft's avatar
Philipp Schafft committed
824
    size_t loop = 10;
Michael Smith's avatar
Michael Smith committed
825

Marvin Scholz's avatar
Marvin Scholz committed
826
    do {
Philipp Schafft's avatar
Philipp Schafft committed
827
        ICECAST_LOG_DEBUG("max on %s is %ld (cur %lu)", source->mount,
Marvin Scholz's avatar
Marvin Scholz committed
828
            source->max_listeners, source->listeners);
Philipp Schafft's avatar
Philipp Schafft committed
829 830 831 832
        if (source->max_listeners == -1)
            break;
        if (source->listeners < (unsigned long)source->max_listeners)
            break;
833

Marvin Scholz's avatar
Marvin Scholz committed
834
        if (loop && source->fallback_when_full && source->fallback_mount) {
Philipp Schafft's avatar
Philipp Schafft committed
835 836 837
            source_t *next = source_find_mount (source->fallback_mount);
            if (!next) {
                ICECAST_LOG_ERROR("Fallback '%s' for full source '%s' not found",
Marvin Scholz's avatar
Marvin Scholz committed
838
                    source->mount, source->fallback_mount);
Philipp Schafft's avatar
Philipp Schafft committed
839