connection.c 50.1 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
 * Copyright 2011,      Dave 'justdave' Miller <justdave@mozilla.com>,
12
 * Copyright 2011-2018, 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

Marvin Scholz's avatar
Marvin Scholz committed
36 37 38 39
#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
40

41 42
#include "compat.h"
#include "connection.h"
43
#include "cfgfile.h"
Jack Moffitt's avatar
Jack Moffitt committed
44 45
#include "global.h"
#include "util.h"
46
#include "refobject.h"
Jack Moffitt's avatar
Jack Moffitt committed
47 48
#include "refbuf.h"
#include "client.h"
49
#include "errors.h"
Jack Moffitt's avatar
Jack Moffitt committed
50 51
#include "stats.h"
#include "logging.h"
52
#include "fserve.h"
53
#include "slave.h"
54

Jack Moffitt's avatar
Jack Moffitt committed
55
#include "source.h"
56
#include "admin.h"
Michael Smith's avatar
Michael Smith committed
57
#include "auth.h"
58
#include "matchfile.h"
59
#include "tls.h"
60
#include "acl.h"
Jack Moffitt's avatar
Jack Moffitt committed
61 62 63

#define CATMODULE "connection"

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

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

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

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

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

102
/* filtering client connection based on IP */
103
static matchfile_t *banned_ip, *allowed_ip;
104

105
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
106

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

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

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

124
    _initialized = 1;
Jack Moffitt's avatar
Jack Moffitt committed
125 126 127 128
}

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

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

141
    _initialized = 0;
Jack Moffitt's avatar
Jack Moffitt committed
142 143
}

144
void connection_reread_config(ice_config_t *config)
145
{
146
    get_tls_certificate(config);
147 148
}

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

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

157
    return id;
Jack Moffitt's avatar
Jack Moffitt committed
158 159
}

160

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

166
    config->tls_ok = tls_ok = 0;
167

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

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

179
    config->tls_ok = tls_ok = 1;
180 181 182
}


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

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

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

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

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


/* 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
226
static int connection_read(connection_t *con, void *buf, size_t len)
227
{
Marvin Scholz's avatar
Marvin Scholz committed
228
    int bytes = sock_read_bytes(con->sock, buf, len);
229 230
    if (bytes == 0)
        con->error = 1;
Marvin Scholz's avatar
Marvin Scholz committed
231
    if (bytes == -1 && !sock_recoverable(sock_error()))
232 233 234 235
        con->error = 1;
    return bytes;
}

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

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

263
    return con;
264 265
}

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

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

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

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

    FD_ZERO(&rfds);

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

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

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

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

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

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

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

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


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


412 413 414 415 416 417
/* 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
418

Marvin Scholz's avatar
Marvin Scholz committed
419
    thread_spin_lock(&_connection_lock);
420

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

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


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

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

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

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

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

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

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

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

529

530 531 532
/* 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
533
static void _add_request_queue(client_queue_t *node)
534 535 536
{
    *_req_queue_tail = node;
    _req_queue_tail = (volatile client_queue_t **)&node->next;
Jack Moffitt's avatar
Jack Moffitt committed
537 538
}

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
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;
556 557
        client->con->tlsmode = listener->tls;
        if (listener->tls == ICECAST_TLSMODE_RFC2818 && tls_ok)
558
            connection_uses_tls(client->con);
559 560 561 562 563 564 565 566
        if (listener->shoutcast_mount)
            node->shoutcast_mount = strdup(listener->shoutcast_mount);
    }

    config_release_config();

    return node;
}
567

568 569 570 571 572 573 574 575
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();
576
        client_send_error_by_id(client, ICECAST_ERROR_GEN_CLIENT_LIMIT);
577 578 579 580 581 582 583 584 585 586
        /* 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();
587
        ICECAST_LOG_WARN("Failed to set tcp options on client connection, dropping");
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        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
603
void connection_accept_loop(void)
Jack Moffitt's avatar
Jack Moffitt committed
604
{
605
    connection_t *con;
606
    ice_config_t *config;
607
    int duration = 300;
608

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

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

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

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

629 630 631
    /* 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
632 633
}

634 635 636

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

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

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

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

Marvin Scholz's avatar
Marvin Scholz committed
656
            if (format_type == FORMAT_ERROR) {
657
                config_release_config();
658
                global_unlock();
659
                if (response) {
660
                    client_send_error_by_id(source->client, ICECAST_ERROR_CON_CONTENT_TYPE_NOSYS);
661 662
                    source->client = NULL;
                }
663
                ICECAST_LOG_WARN("Content-type \"%s\" not supported, dropping source", contenttype);
664 665
                return -1;
            }
666 667 668 669
        } else if (source->parser->req_type == httpp_req_put) {
            config_release_config();
            global_unlock();
            if (response) {
670
                client_send_error_by_id(source->client, ICECAST_ERROR_CON_NO_CONTENT_TYPE_GIVEN);
671 672 673 674 675 676 677 678
                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!");
679
            format_type = FORMAT_TYPE_GENERIC;
680 681
        }

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

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

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

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

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

    global_unlock();
    config_release_config();

Marvin Scholz's avatar
Marvin Scholz committed
714
    if (response) {
715
        client_send_error_by_id(source->client, ICECAST_ERROR_CON_SOURCE_CLIENT_LIMIT);
716 717
        source->client = NULL;
    }
718 719 720 721

    return -1;
}

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

Marvin Scholz's avatar
Marvin Scholz committed
727
    if (source) {
728
        source->client = client;
729 730
        source->parser = client->parser;
        source->con = client->con;
Marvin Scholz's avatar
Marvin Scholz committed
731 732 733
        if (connection_complete_source(source, 1) < 0) {
            source_clear_source(source);
            source_free_source(source);
734 735 736
            return;
        }
        client->respcode = 200;
Philipp Schafft's avatar
Philipp Schafft committed
737 738 739 740
        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 */
741
            client_send_bytes(client, "OK2\r\nicy-caps:11\r\n\r\n", 20); /* TODO: Replace Magic Number! */
742
            source->shoutcast_compat = 1;
Marvin Scholz's avatar
Marvin Scholz committed
743
            source_client_callback(client, source);
Philipp Schafft's avatar
Philipp Schafft committed
744
        } else {
Marvin Scholz's avatar
Marvin Scholz committed
745
            refbuf_t *ok = refbuf_new(PER_CLIENT_REFBUF_SIZE);
746
            const char *expectcontinue;
747
            const char *transfer_encoding;
748
            int status_to_send = 200;
749
            ssize_t ret;
750

751 752 753 754
            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) {
755
                    client_send_error_by_id(client, ICECAST_ERROR_CON_UNIMPLEMENTED);
756 757 758 759
                    return;
                }
            }

760 761 762 763 764 765 766
            /* 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
767
                ICECAST_LOG_WARN("OS doesn't support case insensitive substring checks...");
768 769 770 771 772 773 774
                if (strstr (expectcontinue, "100-continue") != NULL)
#endif
                {
                    status_to_send = 100;
                }
            }

775
            client->respcode = 200;
776 777
            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
778
            ok->len = strlen(ok->data);
779 780 781
            /* 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
782
            fserve_add_client_callback(client, source_client_callback, source);
783
        }
Marvin Scholz's avatar
Marvin Scholz committed
784
    } else {
785
        client_send_error_by_id(client, ICECAST_ERROR_CON_MOUNT_IN_USE);
786
        ICECAST_LOG_WARN("Mountpoint %s in use", uri);
787
    }
788 789
}

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

Marvin Scholz's avatar
Marvin Scholz committed
796
    if (uri[0] != '/') {
Philipp Schafft's avatar
Philipp Schafft committed
797
        ICECAST_LOG_WARN("source mountpoint not starting with /");
798
        client_send_error_by_id(client, ICECAST_ERROR_CON_MOUNTPOINT_NOT_STARTING_WITH_SLASH);
799
        return;
800
    }
801

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


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

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

Philipp Schafft's avatar
Philipp Schafft committed
817 818 819
/* 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
820
static int __add_listener_to_source(source_t *source, client_t *client)
821
{
Philipp Schafft's avatar
Philipp Schafft committed
822
    size_t loop = 10;
Michael Smith's avatar
Michael Smith committed
823

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