connection.c 34.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
/* Icecast
 *
 * This program is distributed under the GNU General Public License, version 2.
 * A copy of this license is included with this source.
 *
 * Copyright 2000-2004, Jack Moffitt <jack@xiph.org, 
 *                      Michael Smith <msmith@xiph.org>,
 *                      oddsock <oddsock@xiph.org>,
 *                      Karl Heyes <karl@xiph.org>
 *                      and others (see AUTHORS for details).
 */

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

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

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

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

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

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

#include "yp.h"
Jack Moffitt's avatar
Jack Moffitt committed
57
#include "source.h"
Michael Smith's avatar
Michael Smith committed
58
#include "format.h"
59
#include "format_mp3.h"
Michael Smith's avatar
Michael Smith committed
60
#include "event.h"
61
#include "admin.h"
Michael Smith's avatar
Michael Smith committed
62
#include "auth.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
81
82
/* 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

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

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

static mutex_t _connection_mutex;
97
static volatile unsigned long _current_id = 0;
Jack Moffitt's avatar
Jack Moffitt committed
98
static int _initialized = 0;
99
static thread_type *tid;
Jack Moffitt's avatar
Jack Moffitt committed
100

101
102
103
104
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;
static mutex_t _con_queue_mutex;
static mutex_t _req_queue_mutex;
Jack Moffitt's avatar
Jack Moffitt committed
105

106
107
108
109
110
static int ssl_ok;
#ifdef HAVE_OPENSSL
static SSL_CTX *ssl_ctx;
#endif

111
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
112
113
114
115
116

static void *_handle_connection(void *arg);

void connection_initialize(void)
{
117
118
119
    if (_initialized) return;
    
    thread_mutex_create(&_connection_mutex);
120
121
    thread_mutex_create(&_con_queue_mutex);
    thread_mutex_create(&_req_queue_mutex);
122
    thread_mutex_create(&move_clients_mutex);
123
    thread_rwlock_create(&_source_shutdown_rwlock);
124
    thread_cond_create(&global.shutdown_cond);
125
126
127
128
    _req_queue = NULL;
    _req_queue_tail = &_req_queue;
    _con_queue = NULL;
    _con_queue_tail = &_con_queue;
Jack Moffitt's avatar
Jack Moffitt committed
129

130
    _initialized = 1;
Jack Moffitt's avatar
Jack Moffitt committed
131
132
133
134
}

void connection_shutdown(void)
{
135
136
    if (!_initialized) return;
    
137
138
139
140
#ifdef HAVE_OPENSSL
    SSL_CTX_free (ssl_ctx);
#endif

141
    thread_cond_destroy(&global.shutdown_cond);
142
    thread_rwlock_destroy(&_source_shutdown_rwlock);
143
144
    thread_mutex_destroy(&_con_queue_mutex);
    thread_mutex_destroy(&_req_queue_mutex);
145
    thread_mutex_destroy(&_connection_mutex);
146
    thread_mutex_destroy(&move_clients_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
147

148
    _initialized = 0;
Jack Moffitt's avatar
Jack Moffitt committed
149
150
151
152
}

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

155
156
157
    thread_mutex_lock(&_connection_mutex);
    id = _current_id++;
    thread_mutex_unlock(&_connection_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
158

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

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281

#ifdef HAVE_OPENSSL
static void get_ssl_certificate ()
{
    SSL_METHOD *method;
    ice_config_t *config;
    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);

    config = config_get_config ();
    do
    {
        if (config->cert_file == NULL)
            break;
        if (SSL_CTX_use_certificate_file (ssl_ctx, config->cert_file, SSL_FILETYPE_PEM) <= 0)
        {
            WARN1 ("Invalid cert file %s", config->cert_file);
            break;
        }
        if (SSL_CTX_use_PrivateKey_file (ssl_ctx, config->cert_file, SSL_FILETYPE_PEM) <= 0)
        {
            WARN1 ("Invalid private key file %s", config->cert_file);
            break;
        }
        if (!SSL_CTX_check_private_key (ssl_ctx))
        {
            ERROR0 ("Invalid icecast.pem - Private key doesn't"
                    " match cert public key");
            break;
        }
        ssl_ok = 1;
        INFO1 ("SSL certificate found at %s", config->cert_file);
    } while (0);
    config_release_config ();
    if (ssl_ok == 0)
        INFO0 ("No SSL capability on any configured ports");
}


/* 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 */
static void get_ssl_certificate ()
{
    ssl_ok = 0;
    INFO0 ("No SSL capability");
}
#endif /* HAVE_OPENSSL */


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

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


282
283
connection_t *connection_create (sock_t sock, sock_t serversock, char *ip)
{
284
    connection_t *con;
285
286
287
288
289
290
291
292
    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;
293
294
        con->read = connection_read;
        con->send = connection_send;
295
    }
Michael Smith's avatar
Michael Smith committed
296

297
    return con;
298
299
}

300
301
302
303
304
305
306
307
308
309
310
311
312
/* 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
}

313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
static int wait_for_serversock(int timeout)
{
#ifdef HAVE_POLL
    struct pollfd ufds[MAX_LISTEN_SOCKETS];
    int i, ret;

    for(i=0; i < global.server_sockets; i++) {
        ufds[i].fd = global.serversock[i];
        ufds[i].events = POLLIN;
        ufds[i].revents = 0;
    }

    ret = poll(ufds, global.server_sockets, timeout);
    if(ret < 0) {
        return -2;
    }
    else if(ret == 0) {
        return -1;
    }
    else {
333
        int dst;
334
        for(i=0; i < global.server_sockets; i++) {
335
            if(ufds[i].revents & POLLIN)
336
                return ufds[i].fd;
337
338
339
340
341
342
343
344
345
            if(ufds[i].revents & (POLLHUP|POLLERR|POLLNVAL))
            {
                if (ufds[i].revents & (POLLHUP|POLLERR))
                {
                    close (global.serversock[i]);
                    WARN0("Had to close a listening socket");
                }
                global.serversock[i] = -1;
            }
346
        }
347
348
349
350
351
352
353
354
355
356
357
        /* remove any closed sockets */
        for(i=0, dst=0; i < global.server_sockets; i++)
        {
            if (global.serversock[i] == -1)
                continue;
            if (i!=dst)
                global.serversock[dst] = global.serversock[i];
            dst++;
        }
        global.server_sockets = dst;
        return -1;
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    }
#else
    fd_set rfds;
    struct timeval tv, *p=NULL;
    int i, ret;
    int max = -1;

    FD_ZERO(&rfds);

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

    if(timeout >= 0) {
        tv.tv_sec = timeout/1000;
375
        tv.tv_usec = (timeout % 1000) * 1000;
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
        p = &tv;
    }

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

Jack Moffitt's avatar
Jack Moffitt committed
396
397
static connection_t *_accept_connection(void)
{
398
399
400
    int sock;
    connection_t *con;
    char *ip;
401
    int serversock; 
Jack Moffitt's avatar
Jack Moffitt committed
402

403
404
405
    serversock = wait_for_serversock(100);
    if(serversock < 0)
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
406

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

410
    sock = sock_accept(serversock, ip, MAX_ADDR_LEN);
411
412
    if (sock >= 0)
    {
413
414
415
        /* 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
416

417
418
419
420
421
422
423
424
425
426
427
428
        con = connection_create (sock, serversock, ip);
        if (con)
            return con;
        sock_close (sock);
    }
    else
    {
        if (!sock_recoverable(sock_error()))
        {
            WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
            thread_sleep (500000);
        }
429
430
431
    }
    free(ip);
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
432
433
434
}


435
436
437
438
439
/* 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
440
{
441
442
443
444
    thread_mutex_lock (&_con_queue_mutex);
    *_con_queue_tail = node;
    _con_queue_tail = (volatile client_queue_t **)&node->next;
    thread_mutex_unlock (&_con_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
445
446
447
}


448
449
450
451
452
453
/* 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
454

455
456
457
458
459
460
461
462
463
    /* common case, no new connections so don't bother taking locks */
    if (_con_queue)
    {
        thread_mutex_lock (&_con_queue_mutex);
        node = (client_queue_t *)_con_queue;
        _con_queue = node->next;
        if (_con_queue == NULL)
            _con_queue_tail = &_con_queue;
        thread_mutex_unlock (&_con_queue_mutex);
464
        node->next = NULL;
465
    }
466
467
    return node;
}
Jack Moffitt's avatar
Jack Moffitt committed
468
469


470
/* run along queue checking for any data that has come in or a timeout */
471
static void process_request_queue (void)
472
473
474
475
476
{
    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
477

478
479
480
481
482
483
    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
484

485
486
487
488
489
490
491
        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
492

493
494
495
496
497
        if (len > 0)
        {
            int pass_it = 1;
            char *ptr;

498
499
            /* handle \n, \r\n and nsvcap which for some strange reason has
             * EOL as \r\r\n */
500
501
502
503
504
505
506
            node->offset += len;
            client->refbuf->data [node->offset] = '\000';
            do
            {
                if (node->shoutcast == 1)
                {
                    /* password line */
507
508
                    if (strstr (client->refbuf->data, "\r\r\n") != NULL)
                        break;
509
510
511
512
513
514
515
                    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 */
516
517
518
519
520
521
                ptr = strstr (client->refbuf->data, "\r\r\n\r\r\n");
                if (ptr)
                {
                    node->stream_offset = (ptr+6) - client->refbuf->data;
                    break;
                }
522
523
524
525
526
527
528
529
530
531
532
533
534
535
                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
536

537
538
            if (pass_it)
            {
539
                thread_mutex_lock (&_req_queue_mutex);
540
541
542
543
                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;
544
                thread_mutex_unlock (&_req_queue_mutex);
545
                _add_connection (node);
546
                continue;
547
548
549
550
551
552
            }
        }
        else
        {
            if (len == 0 || client->con->error)
            {
553
                thread_mutex_lock (&_req_queue_mutex);
554
555
556
                if ((client_queue_t **)_req_queue_tail == &node->next)
                    _req_queue_tail = (volatile client_queue_t **)node_ref;
                *node_ref = node->next;
557
                thread_mutex_unlock (&_req_queue_mutex);
558
559
560
561
562
563
                client_destroy (client);
                free (node);
                continue;
            }
        }
        node_ref = &node->next;
564
    }
Jack Moffitt's avatar
Jack Moffitt committed
565
566
}

567

568
569
570
571
572
573
574
575
576
/* 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)
{
    thread_mutex_lock (&_req_queue_mutex);
    *_req_queue_tail = node;
    _req_queue_tail = (volatile client_queue_t **)&node->next;
    thread_mutex_unlock (&_req_queue_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
577
578
}

579

Jack Moffitt's avatar
Jack Moffitt committed
580
581
void connection_accept_loop(void)
{
582
    connection_t *con;
Jack Moffitt's avatar
Jack Moffitt committed
583

584
    get_ssl_certificate ();
585
    tid = thread_create ("connection thread", _handle_connection, NULL, THREAD_ATTACHED);
Jack Moffitt's avatar
Jack Moffitt committed
586

587
588
    while (global.running == ICE_RUNNING)
    {
589
590
591
        con = _accept_connection();

        if (con)
592
        {
593
594
595
596
            client_queue_t *node;
            ice_config_t *config;
            int i;
            client_t *client = NULL;
597

598
599
600
601
            global_lock();
            if (client_create (&client, con, NULL) < 0)
            {
                global_unlock();
602
                client_send_403 (client, "Icecast connection limit reached");
603
604
605
                continue;
            }
            global_unlock();
606

607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
            /* setup client for reading incoming http */
            client->refbuf->data [PER_CLIENT_REFBUF_SIZE-1] = '\000';

            node = calloc (1, sizeof (client_queue_t));
            if (node == NULL)
            {
                client_destroy (client);
                continue;
            }
            node->client = client;

            /* Check for special shoutcast compatability processing */
            config = config_get_config();
            for (i = 0; i < global.server_sockets; i++)
            {
                if (global.serversock[i] == con->serversock)
                {
                    if (config->listeners[i].shoutcast_compat)
                        node->shoutcast = 1;
626
627
                    if (config->listeners[i].ssl && ssl_ok)
                        connection_uses_ssl (client->con);
628
629
                }
            }
630
            config_release_config();
631
632
633

            sock_set_blocking (client->con->sock, SOCK_NONBLOCK);
            sock_set_nodelay (client->con->sock);
Jack Moffitt's avatar
Jack Moffitt committed
634

635
636
            _add_request_queue (node);
            stats_event_inc (NULL, "connections");
637
        }
638
        process_request_queue ();
639
    }
Jack Moffitt's avatar
Jack Moffitt committed
640

641
642
643
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

644
645
    if (tid)
        thread_join (tid);
Jack Moffitt's avatar
Jack Moffitt committed
646

647
648
649
    /* 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
650
651
}

652
653
654

/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
655
 */
656
int connection_complete_source (source_t *source, int response)
657
658
659
660
661
662
663
664
{
    ice_config_t *config = config_get_config();

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

    if (global.sources < config->source_limit)
    {
665
        const char *contenttype;
666
        mount_proxy *mountinfo;
667
668
669
670
671
672
673
674
675
676
677
678
        format_type_t format_type;

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

            if (format_type == FORMAT_ERROR)
            {
                global_unlock();
                config_release_config();
679
680
                if (response)
                {
681
                    client_send_403 (source->client, "Content-type not supported");
682
683
                    source->client = NULL;
                }
684
685
686
687
688
689
                WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
                return -1;
            }
        }
        else
        {
690
            WARN0("No content-type header, falling back to backwards compatibility mode "
691
                    "for icecast 1.x relays. Assuming content is mp3.");
692
            format_type = FORMAT_TYPE_GENERIC;
693
694
        }

Karl Heyes's avatar
Karl Heyes committed
695
        if (format_get_plugin (format_type, source) < 0)
696
697
698
        {
            global_unlock();
            config_release_config();
699
700
            if (response)
            {
701
                client_send_403 (source->client, "internal format allocation problem");
702
703
                source->client = NULL;
            }
704
705
706
707
            WARN1 ("plugin format failed for \"%s\"", source->mount);
            return -1;
        }

708
709
710
        global.sources++;
        stats_event_args (NULL, "sources", "%d", global.sources);
        global_unlock();
711

712
713
        source->running = 1;
        mountinfo = config_find_mount (config, source->mount);
714
        source_update_settings (config, source, mountinfo);
715
        config_release_config();
716
        slave_rebuild_mounts();
717
718
719
720
721
722

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

        return 0;
    }
723
    WARN1("Request to add source when maximum source limit "
724
725
726
727
728
            "reached %d", global.sources);

    global_unlock();
    config_release_config();

729
730
    if (response)
    {
731
        client_send_403 (source->client, "too many sources connected");
732
733
        source->client = NULL;
    }
734
735
736
737
738

    return -1;
}


739
static int _check_pass_http(http_parser_t *parser, 
740
        const char *correctuser, const char *correctpass)
741
742
{
    /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
743
    const char *header = httpp_getvar(parser, "authorization");
744
745
746
747
748
749
750
751
752
753
    char *userpass, *tmp;
    char *username, *password;

    if(header == NULL)
        return 0;

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

    userpass = util_base64_decode(header+6);
754
755
756
    if(userpass == NULL) {
        WARN1("Base64 decode of Authorization header \"%s\" failed",
                header+6);
757
        return 0;
758
    }
759
760
761
762
763
764
765
766
767
768

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

769
    if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
770
771
772
        free(userpass);
        return 0;
    }
773
    free(userpass);
774
775
776
777

    return 1;
}

778
static int _check_pass_icy(http_parser_t *parser, const char *correctpass)
779
{
780
    const char *password;
781
782
783
784
785

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

786
    if (strcmp(password, correctpass))
787
788
789
790
791
        return 0;
    else
        return 1;
}

792
static int _check_pass_ice(http_parser_t *parser, const char *correctpass)
793
{
794
    const char *password;
795
796
797
798
799

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

800
    if (strcmp(password, correctpass))
801
802
803
804
805
        return 0;
    else
        return 1;
}

806
int connection_check_admin_pass(http_parser_t *parser)
807
{
808
    int ret;
Michael Smith's avatar
Michael Smith committed
809
810
811
    ice_config_t *config = config_get_config();
    char *pass = config->admin_password;
    char *user = config->admin_username;
812
    const char *protocol;
813
814
815
816
817
818

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

819
820
821
822
823
    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
824
    config_release_config();
825
826
    return ret;
}
Michael Smith's avatar
Michael Smith committed
827

828
829
830
831
832
int connection_check_relay_pass(http_parser_t *parser)
{
    int ret;
    ice_config_t *config = config_get_config();
    char *pass = config->relay_password;
833
    char *user = config->relay_username;
Michael Smith's avatar
Michael Smith committed
834

835
836
    if(!pass || !user) {
        config_release_config();
837
        return 0;
838
    }
839

840
841
842
    ret = _check_pass_http(parser, user, pass);
    config_release_config();
    return ret;
843
844
}

845
int connection_check_source_pass(http_parser_t *parser, const char *mount)
846
{
Michael Smith's avatar
Michael Smith committed
847
848
    ice_config_t *config = config_get_config();
    char *pass = config->source_password;
849
    char *user = "source";
850
    int ret;
Michael Smith's avatar
Michael Smith committed
851
    int ice_login = config->ice_login;
852
    const char *protocol;
Michael Smith's avatar
Michael Smith committed
853

854
    mount_proxy *mountinfo = config_find_mount (config, mount);
855

856
857
858
859
860
861
    if (mountinfo)
    {
        if (mountinfo->password)
            pass = mountinfo->password;
        if (mountinfo->username)
            user = mountinfo->username;
862
863
864
865
    }

    if(!pass) {
        WARN0("No source password set, rejecting source");
866
        config_release_config();
867
868
869
        return 0;
    }

870
    protocol = httpp_getvar(parser, HTTPP_VAR_PROTOCOL);
871
872
873
874
875
876
877
878
879
880
881
    if(protocol != NULL && !strcmp(protocol, "ICY")) {
        ret = _check_pass_icy(parser, pass);
    }
    else {
        ret = _check_pass_http(parser, user, pass);
        if(!ret && ice_login)
        {
            ret = _check_pass_ice(parser, pass);
            if(ret)
                WARN0("Source is using deprecated icecast login");
        }
882
    }
883
    config_release_config();
884
    return ret;
885
886
}

887

888
static void _handle_source_request (client_t *client, char *uri, int auth_style)
889
{
890
    source_t *source;
891

892
    INFO1("Source logging in at mountpoint \"%s\"", uri);
893

894
895
896
897
898
899
    if (uri[0] != '/')
    {
        WARN0 ("source mountpoint not starting with /");
        client_send_401 (client);
        return;
    }
900
    if (auth_style == ICECAST_SOURCE_AUTH) {
901
902
        if (connection_check_source_pass (client->parser, uri) == 0)
        {
903
904
905
906
            /* We commonly get this if the source client is using the wrong
             * protocol: attempt to diagnose this and return an error
             */
            /* TODO: Do what the above comment says */
907
            INFO1("Source (%s) attempted to login with invalid or missing password", uri);
908
909
910
            client_send_401(client);
            return;
        }
911
    }
912
913
914
    source = source_reserve (uri);
    if (source)
    {
915
916
917
        if (auth_style == SHOUTCAST_SOURCE_AUTH) {
            source->shoutcast_compat = 1;
        }
918
        source->client = client;
919
920
        source->parser = client->parser;
        source->con = client->con;
921
        if (connection_complete_source (source, 1) < 0)
922
        {
923
            source_clear_source (source);
924
925
926
            source_free_source (source);
        }
        else
927
        {
928
            refbuf_t *ok = refbuf_new (PER_CLIENT_REFBUF_SIZE);
929
            client->respcode = 200;
930
            snprintf (ok->data, PER_CLIENT_REFBUF_SIZE,
931
                    "HTTP/1.0 200 OK\r\n\r\n");
932
933
934
935
            ok->len = strlen (ok->data);
            /* we may have unprocessed data read in, so don't overwrite it */
            ok->associated = client->refbuf;
            client->refbuf = ok;
936
937
            fserve_add_client_callback (client, source_client_callback, source);
        }
938
939
940
    }
    else
    {
941
        client_send_403 (client, "Mountpoint in use");
942
        WARN1 ("Mountpoint %s in use", uri);
943
    }
944
945
}

946

947
static void _handle_stats_request (client_t *client, char *uri)
Jack Moffitt's avatar
Jack Moffitt committed
948
{
949
    stats_event_inc(NULL, "stats_connections");
950
951
952
953

    if (connection_check_admin_pass (client->parser) == 0)
    {
        client_send_401 (client);
954
955
        ERROR0("Bad password for stats connection");
        return;
956
    }
957

958
    client->respcode = 200;
959
960
961
962
    snprintf (client->refbuf->data, PER_CLIENT_REFBUF_SIZE,
            "HTTP/1.0 200 OK\r\n\r\n");
    client->refbuf->len = strlen (client->refbuf->data);
    fserve_add_client_callback (client, stats_callback, NULL);
963
964
}

965
static void _handle_get_request (client_t *client, char *passed_uri)
966
{
Michael Smith's avatar
Michael Smith committed
967
968
    int fileserve;
    int port;
969
    int i;
Karl Heyes's avatar
Karl Heyes committed
970
971
    char *serverhost = NULL;
    int serverport = 0;
972
    aliases *alias;
Michael Smith's avatar
Michael Smith committed
973
    ice_config_t *config;
974
    char *uri = passed_uri;
Michael Smith's avatar
Michael Smith committed
975
976
977
978

    config = config_get_config();
    fileserve = config->fileserve;
    port = config->port;
979
    for(i = 0; i < global.server_sockets; i++) {
980
        if(global.serversock[i] == client->con->serversock) {
981
982
983
984
985
986
            serverhost = config->listeners[i].bind_address;
            serverport = config->listeners[i].port;
            break;
        }
    }
    alias = config->aliases;
987

988
989
990
    /* there are several types of HTTP GET clients
    ** media clients, which are looking for a source (eg, URI = /stream.ogg)
    ** stats clients, which are looking for /admin/stats.xml
991
    ** and directory server authorizers, which are looking for /GUID-xxxxxxxx 
992
    ** (where xxxxxx is the GUID in question) - this isn't implemented yet.
993
994
995
996
    ** we need to handle the latter two before the former, as the latter two
    ** aren't subject to the limits.
    */
    /* TODO: add GUID-xxxxxx */
997

998
999
1000
    /* Handle aliases */
    while(alias) {
        if(strcmp(uri, alias->source) == 0 && (alias->port == -1 || alias->port == serverport) && (alias->bind_address == NULL || (serverhost != NULL && strcmp(alias->bind_address, serverhost) == 0))) {
1001
1002
            uri = strdup (alias->destination);
            DEBUG2 ("alias has made %s into %s", passed_uri, uri);
1003
1004
1005
1006
            break;
        }
        alias = alias->next;
    }
1007
1008
1009
    config_release_config();

    stats_event_inc(NULL, "client_connections");
1010

1011
    /* Dispatch all admin requests */
1012
1013
    if ((strcmp(uri, "/admin.cgi") == 0) ||
        (strncmp(uri, "/admin/", 7) == 0)) {
1014
        admin_handle_request(client, uri);
1015
        if (uri != passed_uri) free (uri);
Michael Smith's avatar
Michael Smith committed
1016
1017
        return;
    }
1018
    auth_add_listener (uri, client);
1019
    if (uri != passed_uri) free (uri);
1020
1021
}

1022
1023
static void _handle_shoutcast_compatible (client_queue_t *node)
{
1024
1025
1026
    char *http_compliant;
    int http_compliant_len = 0;
    http_parser_t *parser;
1027
1028
1029
    ice_config_t *config = config_get_config ();
    char *shoutcast_mount;
    client_t *client = node->client;
1030

1031
1032
    if (node->shoutcast == 1)
    {
1033
        char *source_password, *ptr, *headers;
1034
1035
1036
1037
1038
1039
1040
1041
1042
        mount_proxy *mountinfo = config_find_mount (config, config->shoutcast_mount);

        if (mountinfo && mountinfo->password)
            source_password = strdup (mountinfo->password);
        else
            source_password = strdup (config->source_password);
        config_release_config();

        /* Get rid of trailing \r\n or \n after password */
1043
        ptr = strstr (client->refbuf->data, "\r\r\n");
1044
        if (ptr)
1045
            headers = ptr+3;
1046
1047
        else
        {
1048
            ptr = strstr (client->refbuf->data, "\r\n");
1049
            if (ptr)
1050
1051
1052
1053
1054
1055
1056
                headers = ptr+2;
            else
            {
                ptr = strstr (client->refbuf->data, "\n");
                if (ptr)
                    headers = ptr+1;
            }
1057
        }
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072

        if (ptr == NULL)
        {
            client_destroy (client);
            free (source_password);
            free (node);
            return;
        }
        *ptr = '\0';

        if (strcmp (client->refbuf->data, source_password) == 0)
        {
            client->respcode = 200;
            /* send this non-blocking but if there is only a partial write
             * then leave to header timeout */
1073
            sock_write (client->con->sock, "OK2\r\nicy-caps:11\r\n\r\n");
1074
1075
            node->offset -= (headers - client->refbuf->data);
            memmove (client->refbuf->data, headers, node->offset+1);
1076
1077
1078
1079
1080
1081
            node->shoutcast = 2;
            /* we've checked the password, now send it back for reading headers */
            _add_request_queue (node);
            free (source_password);
            return;
        }
1082
1083
        else
            INFO1 ("password does not match \"%s\"", client->refbuf->data);
1084
1085
        client_destroy (client);
        free (node);
1086
1087
        return;
    }
1088
1089
    shoutcast_mount = strdup (config->shoutcast_mount);
    config_release_config();
1090
1091
1092
    /* Here we create a valid HTTP request based of the information
       that was passed in via the non-HTTP style protocol above. This
       means we can use some of our existing code to handle this case */
1093
    http_compliant_len = 20 + strlen (shoutcast_mount) + node->offset;
1094
    http_compliant = (char *)calloc(1, http_compliant_len);
1095
    snprintf (http_compliant, http_compliant_len,
1096
            "SOURCE %s HTTP/1.0\r\n%s", shoutcast_mount, client->refbuf->data);
1097
1098
    parser = httpp_create_parser();
    httpp_initialize(parser, NULL);
1099
1100
    if (httpp_parse (parser, http_compliant, strlen(http_compliant)))
    {
1101
1102
1103
1104
        /* we may have more than just headers, so prepare for it */
        if (node->stream_offset == node->offset)
            client->refbuf->len = 0;
        else
1105
        {
1106
1107
1108
            char *ptr = client->refbuf->data;
            client->refbuf->len = node->offset - node->stream_offset;
            memmove (ptr, ptr + node->stream_offset, client->refbuf->len);
1109
        }
1110
1111
        client->parser = parser;
        _handle_source_request (client, shoutcast_mount, SHOUTCAST_SOURCE_AUTH);
1112
    }
1113
1114
    else {
        httpp_destroy (parser);
1115
        client_destroy (client);
1116
    }
1117
    free (http_compliant);
1118
1119
1120
    free (shoutcast_mount);
    free (node);
    return;
1121
1122
}

1123
1124
1125
1126
1127

/* Connection thread. Here we take clients off the connection queue and check
 * the contents provided. We set up the parser then hand off to the specific
 * request handler.
 */
1128
1129
static void *_handle_connection(void *arg)
{
1130
    http_parser_t *parser;
1131
    const char *rawuri;
Jack Moffitt's avatar
Jack Moffitt committed
1132

1133
    while (global.running == ICE_RUNNING) {
Jack Moffitt's avatar
Jack Moffitt committed
1134

1135
        client_queue_t *node = _get_connection();