connection.c 41.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/* Icecast
 *
 * This program is distributed under the GNU General Public License, version 2.
 * A copy of this license is included with this source.
 *
 * Copyright 2000-2004, Jack Moffitt <jack@xiph.org, 
 *                      Michael Smith <msmith@xiph.org>,
 *                      oddsock <oddsock@xiph.org>,
 *                      Karl Heyes <karl@xiph.org>
 *                      and others (see AUTHORS for details).
11
12
 * Copyright 2011,      Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>,
 *                      Dave 'justdave' Miller <justdave@mozilla.com>.
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
28
#include <sys/types.h>
#include <sys/stat.h>
29
30

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

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

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

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

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

#define CATMODULE "connection"

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

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

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

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

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

108
static spin_t _connection_lock; // protects _current_id, _con_queue, _con_queue_tail
109
static volatile unsigned long _current_id = 0;
Jack Moffitt's avatar
Jack Moffitt committed
110
111
static int _initialized = 0;

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

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

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

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

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

    return strcmp (pattern, ip);
}


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


Jack Moffitt's avatar
Jack Moffitt committed
142
143
void connection_initialize(void)
{
144
145
    if (_initialized) return;
    
146
    thread_spin_create (&_connection_lock);
147
    thread_mutex_create(&move_clients_mutex);
148
    thread_rwlock_create(&_source_shutdown_rwlock);
149
    thread_cond_create(&global.shutdown_cond);
150
151
152
153
    _req_queue = NULL;
    _req_queue_tail = &_req_queue;
    _con_queue = NULL;
    _con_queue_tail = &_con_queue;
Jack Moffitt's avatar
Jack Moffitt committed
154

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

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

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

void connection_shutdown(void)
{
166
167
    if (!_initialized) return;
    
168
169
170
#ifdef HAVE_OPENSSL
    SSL_CTX_free (ssl_ctx);
#endif
171
172
173
    if (banned_ip.contents)  avl_tree_free (banned_ip.contents, free_filtered_ip);
    if (allowed_ip.contents) avl_tree_free (allowed_ip.contents, free_filtered_ip);
 
174
    thread_cond_destroy(&global.shutdown_cond);
175
    thread_rwlock_destroy(&_source_shutdown_rwlock);
176
    thread_spin_destroy (&_connection_lock);
177
    thread_mutex_destroy(&move_clients_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
178

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

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

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

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

193
194

#ifdef HAVE_OPENSSL
195
static void get_ssl_certificate (ice_config_t *config)
196
197
{
    SSL_METHOD *method;
198
    long ssl_opts;
199
200
201
202
203
204
205
    ssl_ok = 0;

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

    method = SSLv23_server_method();
    ssl_ctx = SSL_CTX_new (method);
206
207
    ssl_opts = SSL_CTX_get_options (ssl_ctx);
    SSL_CTX_set_options (ssl_ctx, ssl_opts|SSL_OP_NO_SSLv2);
208
209
210
211
212

    do
    {
        if (config->cert_file == NULL)
            break;
213
        if (SSL_CTX_use_certificate_chain_file (ssl_ctx, config->cert_file) <= 0)
214
        {
215
            LOG_WARN("Invalid cert file %s", config->cert_file);
216
217
218
219
            break;
        }
        if (SSL_CTX_use_PrivateKey_file (ssl_ctx, config->cert_file, SSL_FILETYPE_PEM) <= 0)
        {
220
            LOG_WARN("Invalid private key file %s", config->cert_file);
221
222
223
224
            break;
        }
        if (!SSL_CTX_check_private_key (ssl_ctx))
        {
225
            LOG_ERROR("Invalid %s - Private key does not match cert public key", config->cert_file);
226
227
            break;
        }
228
229
        if (SSL_CTX_set_cipher_list(ssl_ctx, config->cipher_list) <= 0) 
        { 
230
            LOG_WARN("Invalid cipher list: %s", config->cipher_list); 
231
        } 
232
        ssl_ok = 1;
233
234
        LOG_INFO("SSL certificate found at %s", config->cert_file);
        LOG_INFO("SSL using ciphers %s", config->cipher_list); 
235
        return;
236
    } while (0);
237
    LOG_INFO("No SSL capability on any configured ports");
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
}


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

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

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

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

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


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

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


317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/* function to handle the re-populating of the avl tree containing IP addresses
 * for deciding whether a connection of an incoming request is to be dropped.
 */
static void recheck_ip_file (cache_file_contents *cache)
{
    time_t now = time(NULL);
    if (now >= cache->file_recheck)
    {
        struct stat file_stat;
        FILE *file = NULL;
        int count = 0;
        avl_tree *new_ips;
        char line [MAX_LINE_LEN];

        cache->file_recheck = now + 10;
        if (cache->filename == NULL)
        {
            if (cache->contents)
            {
                avl_tree_free (cache->contents, free_filtered_ip);
                cache->contents = NULL;
            }
            return;
        }
        if (stat (cache->filename, &file_stat) < 0)
        {
343
            LOG_WARN("failed to check status of \"%s\": %s", cache->filename, strerror(errno));
344
345
346
347
348
349
350
351
352
353
            return;
        }
        if (file_stat.st_mtime == cache->file_mtime)
            return; /* common case, no update to file */

        cache->file_mtime = file_stat.st_mtime;

        file = fopen (cache->filename, "r");
        if (file == NULL)
        {
354
            LOG_WARN("Failed to open file \"%s\": %s", cache->filename, strerror (errno));
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
            return;
        }

        new_ips = avl_tree_new (compare_ip, NULL);

        while (get_line (file, line, MAX_LINE_LEN))
        {
            char *str;
            if(!line[0] || line[0] == '#')
                continue;
            count++;
            str = strdup (line);
            if (str)
                avl_insert (new_ips, str);
        }
        fclose (file);
371
        LOG_INFO("%d entries read from file \"%s\"", count, cache->filename);
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

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


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

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

    if (banned_ip.contents)
    {
        if (avl_get_by_key (banned_ip.contents, ip, &result) == 0)
        {
391
            LOG_DEBUG("%s is banned", ip);
392
393
394
395
396
397
398
            return 0;
        }
    }
    if (allowed_ip.contents)
    {
        if (avl_get_by_key (allowed_ip.contents, ip, &result) == 0)
        {
399
            LOG_DEBUG("%s is allowed", ip);
400
401
402
403
            return 1;
        }
        else
        {
404
            LOG_DEBUG("%s is not allowed", ip);
405
406
407
408
409
410
411
            return 0;
        }
    }
    return 1;
}


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

427
    return con;
428
429
}

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

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

    FD_ZERO(&rfds);

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

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

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

526
static connection_t *_accept_connection(int duration)
Jack Moffitt's avatar
Jack Moffitt committed
527
{
528
    sock_t sock, serversock;
529
    char *ip;
Jack Moffitt's avatar
Jack Moffitt committed
530

531
    serversock = wait_for_serversock (duration);
532
    if (serversock == SOCK_ERROR)
533
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
534

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

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

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


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


578
579
580
581
582
583
/* 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
584

585
586
    thread_spin_lock (&_connection_lock);

587
588
589
590
591
592
    if (_con_queue)
    {
        node = (client_queue_t *)_con_queue;
        _con_queue = node->next;
        if (_con_queue == NULL)
            _con_queue_tail = &_con_queue;
593
        node->next = NULL;
594
    }
595
596

    thread_spin_unlock (&_connection_lock);
597
598
    return node;
}
Jack Moffitt's avatar
Jack Moffitt committed
599
600


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

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

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

624
625
626
627
628
        if (len > 0)
        {
            int pass_it = 1;
            char *ptr;

629
630
            /* handle \n, \r\n and nsvcap which for some strange reason has
             * EOL as \r\r\n */
631
632
633
634
635
636
637
            node->offset += len;
            client->refbuf->data [node->offset] = '\000';
            do
            {
                if (node->shoutcast == 1)
                {
                    /* password line */
638
639
                    if (strstr (client->refbuf->data, "\r\r\n") != NULL)
                        break;
640
641
642
643
644
645
646
                    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 */
647
648
649
650
651
652
                ptr = strstr (client->refbuf->data, "\r\r\n\r\r\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+6) - client->refbuf->data;
                    break;
                }
653
654
655
656
657
658
659
660
661
662
663
664
665
666
                ptr = strstr (client->refbuf->data, "\r\n\r\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+4) - client->refbuf->data;
                    break;
                }
                ptr = strstr (client->refbuf->data, "\n\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+2) - client->refbuf->data;
                    break;
                }
                pass_it = 0;
            } while (0);
Jack Moffitt's avatar
Jack Moffitt committed
667

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

695

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

705

706
void connection_accept_loop (void)
Jack Moffitt's avatar
Jack Moffitt committed
707
{
708
    connection_t *con;
709
    ice_config_t *config;
710
    int duration = 300;
711
712
713
714

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

716
717
    while (global.running == ICE_RUNNING)
    {
718
        con = _accept_connection (duration);
719
720

        if (con)
721
        {
722
723
724
            client_queue_t *node;
            ice_config_t *config;
            client_t *client = NULL;
725
            listener_t *listener;
726

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

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

740
741
            if (sock_set_blocking (client->con->sock, 0) || sock_set_nodelay (client->con->sock))
            {
742
                global_unlock();
743
                LOG_WARN("failed to set tcp options on client connection, dropping");
744
745
746
747
                client_destroy (client);
                continue;
            }

748
749
750
            node = calloc (1, sizeof (client_queue_t));
            if (node == NULL)
            {
751
                global_unlock();
752
753
754
755
756
757
                client_destroy (client);
                continue;
            }
            node->client = client;

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

            if (listener)
761
            {
762
763
764
765
                if (listener->shoutcast_compat)
                    node->shoutcast = 1;
                if (listener->ssl && ssl_ok)
                    connection_uses_ssl (client->con);
766
767
                if (listener->shoutcast_mount)
                    node->shoutcast_mount = strdup (listener->shoutcast_mount);
768
            }
769
            global_unlock();
770
            config_release_config();
771
772
773

            _add_request_queue (node);
            stats_event_inc (NULL, "connections");
774
775
776
777
778
779
            duration = 5;
        }
        else
        {
            if (_req_queue == NULL)
                duration = 300; /* use longer timeouts when nothing waiting */
780
        }
781
        process_request_queue ();
782
    }
Jack Moffitt's avatar
Jack Moffitt committed
783

784
785
786
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

787
788
789
    /* 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
790
791
}

792
793
794

/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
795
 */
796
int connection_complete_source (source_t *source, int response)
797
{
798
    ice_config_t *config;
799
800

    global_lock ();
801
    LOG_DEBUG("sources count is %d", global.sources);
802

803
    config = config_get_config();
804
805
    if (global.sources < config->source_limit)
    {
806
        const char *contenttype;
807
        const char *expectcontinue;
808
        mount_proxy *mountinfo;
809
810
811
812
813
814
815
816
817
818
819
        format_type_t format_type;

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

            if (format_type == FORMAT_ERROR)
            {
                config_release_config();
820
                global_unlock();
821
822
                if (response)
                {
823
                    client_send_403 (source->client, "Content-type not supported");
824
825
                    source->client = NULL;
                }
826
                LOG_WARN("Content-type \"%s\" not supported, dropping source", contenttype);
827
828
829
830
831
                return -1;
            }
        }
        else
        {
832
            LOG_WARN("No content-type header, falling back to backwards compatibility mode "
833
                    "for icecast 1.x relays. Assuming content is mp3.");
834
            format_type = FORMAT_TYPE_GENERIC;
835
836
        }

Karl Heyes's avatar
Karl Heyes committed
837
        if (format_get_plugin (format_type, source) < 0)
838
839
840
        {
            global_unlock();
            config_release_config();
841
842
            if (response)
            {
843
                client_send_403 (source->client, "internal format allocation problem");
844
845
                source->client = NULL;
            }
846
            LOG_WARN("plugin format failed for \"%s\"", source->mount);
847
848
849
            return -1;
        }

850
851
852
853
854
855
856
	/* 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
857
	    LOG_WARN("OS doesn't support case insenestive substring checks...");
858
859
860
861
862
863
864
	    if (strstr (expectcontinue, "100-continue") != NULL)
#endif
	    {
		client_send_100 (source->client);
	    }
	}

865
866
867
        global.sources++;
        stats_event_args (NULL, "sources", "%d", global.sources);
        global_unlock();
868

869
        source->running = 1;
870
        mountinfo = config_find_mount (config, source->mount, MOUNT_TYPE_NORMAL);
871
        source_update_settings (config, source, mountinfo);
872
        config_release_config();
873
        slave_rebuild_mounts();
874
875

        source->shutdown_rwlock = &_source_shutdown_rwlock;
876
        LOG_DEBUG("source is ready to start");
877
878
879

        return 0;
    }
880
    LOG_WARN("Request to add source when maximum source limit "
881
882
883
884
885
            "reached %d", global.sources);

    global_unlock();
    config_release_config();

886
887
    if (response)
    {
888
        client_send_403 (source->client, "too many sources connected");
889
890
        source->client = NULL;
    }
891
892
893
894
895

    return -1;
}


896
static int _check_pass_http(http_parser_t *parser, 
897
        const char *correctuser, const char *correctpass)
898
899
{
    /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
900
    const char *header = httpp_getvar(parser, "authorization");
901
902
903
904
905
906
907
908
909
910
    char *userpass, *tmp;
    char *username, *password;

    if(header == NULL)
        return 0;

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

    userpass = util_base64_decode(header+6);
911
    if(userpass == NULL) {
912
        LOG_WARN("Base64 decode of Authorization header \"%s\" failed",
913
                header+6);
914
        return 0;
915
    }
916
917
918
919
920
921
922
923
924
925

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

926
    if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
927
928
929
        free(userpass);
        return 0;
    }
930
    free(userpass);
931
932
933
934

    return 1;
}

935
static int _check_pass_icy(http_parser_t *parser, const char *correctpass)
936
{
937
    const char *password;
938
939
940
941
942

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

943
    if (strcmp(password, correctpass))
944
945
946
947
948
        return 0;
    else
        return 1;
}

949
static int _check_pass_ice(http_parser_t *parser, const char *correctpass)
950
{
951
    const char *password;
952
953
954
955
956

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

957
    if (strcmp(password, correctpass))
958
959
960
961
962
        return 0;
    else
        return 1;
}

963
int connection_check_admin_pass(http_parser_t *parser)
964
{
965
    int ret;
Michael Smith's avatar
Michael Smith committed
966
967
968
    ice_config_t *config = config_get_config();
    char *pass = config->admin_password;
    char *user = config->admin_username;
969
    const char *protocol;
970
971
972
973
974
975

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

976
977
978
979
980
    protocol = httpp_getvar (parser, HTTPP_VAR_PROTOCOL);
    if (protocol && strcmp (protocol, "ICY") == 0)
        ret = _check_pass_icy (parser, pass);
    else 
        ret = _check_pass_http (parser, user, pass);
Michael Smith's avatar
Michael Smith committed
981
    config_release_config();
982
983
    return ret;
}
Michael Smith's avatar
Michael Smith committed
984

985
986
987
988
989
int connection_check_relay_pass(http_parser_t *parser)
{
    int ret;
    ice_config_t *config = config_get_config();
    char *pass = config->relay_password;
990
    char *user = config->relay_username;
Michael Smith's avatar
Michael Smith committed
991

992
993
    if(!pass || !user) {
        config_release_config();
994
        return 0;
995
    }
996

997
998
999
    ret = _check_pass_http(parser, user, pass);
    config_release_config();
    return ret;
1000
1001
}

1002
1003
1004
1005

/* return 0 for failed, 1 for ok
 */
int connection_check_pass (http_parser_t *parser, const char *user, const char *pass)
1006
{
1007
    int ret;
1008
    const char *protocol;
Michael Smith's avatar
Michael Smith committed
1009

1010
    if(!pass) {
1011
        LOG_WARN("No source password set, rejecting source");
1012
        return -1;
1013
1014
    }

1015
    protocol = httpp_getvar(parser, HTTPP_VAR_PROTOCOL);
1016
1017
1018
1019
1020
    if(protocol != NULL && !strcmp(protocol, "ICY")) {
        ret = _check_pass_icy(parser, pass);
    }
    else {
        ret = _check_pass_http(parser, user, pass);
1021
        if (!ret)
1022
        {
1023
1024
1025
1026
1027
            ice_config_t *config = config_get_config_unlocked();
            if (config->ice_login)
            {
                ret = _check_pass_ice(parser, pass);
                if(ret)
1028
                    LOG_WARN("Source is using deprecated icecast login");
1029
            }
1030
        }
1031
1032
    }
    return ret;
1033
1034
}

1035

1036
1037
/* only called for native icecast source clients */
static void _handle_source_request (client_t *client, const char *uri)
1038
{
ePirat's avatar
ePirat committed
1039
1040
    LOG_INFO("Source logging in at mountpoint \"%s\" from %s",
        uri, client->con->ip);
1041

1042
1043
    if (uri[0] != '/')
    {
1044
        LOG_WARN("source mountpoint not starting with /");
1045
1046
1047
        client_send_401 (client);
        return;
    }
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
    switch (client_check_source_auth (client, uri))
    {
        case 0: /* authenticated from config file */
            source_startup (client, uri, ICECAST_SOURCE_AUTH);
            break;

        case 1: /* auth pending */
            break;

        default: /* failed */
1058
            LOG_INFO("Source (%s) attempted to login with invalid or missing password", uri);
1059
            client_send_401(client);
1060
            break;
1061
    }
1062
1063
1064
1065
1066
1067
}


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

1070
1071
1072
    if (source)
    {
        source->client = client;
1073
1074
        source->parser = client->parser;
        source->con = client->con;
1075
        if (connection_complete_source (source, 1) < 0)
1076
        {
1077
            source_clear_source (source);
1078
            source_free_source (source);
1079
1080
1081
1082
1083
1084
1085
            return;
        }
        client->respcode = 200;
        if (auth_style == SHOUTCAST_SOURCE_AUTH)
        {
            source->shoutcast_compat = 1;
            source_client_callback (client, source);
1086
1087
        }
        else
1088
        {
1089
            refbuf_t *ok = refbuf_new (PER_CLIENT_REFBUF_SIZE);
1090
            client->respcode = 200;
1091
            snprintf (ok->data, PER_CLIENT_REFBUF_SIZE,