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

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

Jack Moffitt's avatar
Jack Moffitt committed
18
19
20
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
21
#include <time.h>
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
38

#include "os.h"

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
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
107
108
109
110
111

static void *_handle_connection(void *arg);

void connection_initialize(void)
{
112
113
114
    if (_initialized) return;
    
    thread_mutex_create(&_connection_mutex);
115
116
    thread_mutex_create(&_con_queue_mutex);
    thread_mutex_create(&_req_queue_mutex);
117
    thread_mutex_create(&move_clients_mutex);
118
    thread_rwlock_create(&_source_shutdown_rwlock);
119
    thread_cond_create(&global.shutdown_cond);
Jack Moffitt's avatar
Jack Moffitt committed
120

121
    _initialized = 1;
Jack Moffitt's avatar
Jack Moffitt committed
122
123
124
125
}

void connection_shutdown(void)
{
126
127
    if (!_initialized) return;
    
128
    thread_cond_destroy(&global.shutdown_cond);
129
    thread_rwlock_destroy(&_source_shutdown_rwlock);
130
131
    thread_mutex_destroy(&_con_queue_mutex);
    thread_mutex_destroy(&_req_queue_mutex);
132
    thread_mutex_destroy(&_connection_mutex);
133
    thread_mutex_destroy(&move_clients_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
134

135
    _initialized = 0;
Jack Moffitt's avatar
Jack Moffitt committed
136
137
138
139
}

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

142
143
144
    thread_mutex_lock(&_connection_mutex);
    id = _current_id++;
    thread_mutex_unlock(&_connection_mutex);
Jack Moffitt's avatar
Jack Moffitt committed
145

146
    return id;
Jack Moffitt's avatar
Jack Moffitt committed
147
148
}

149
150
connection_t *connection_create (sock_t sock, sock_t serversock, char *ip)
{
151
    connection_t *con;
152
153
154
155
156
157
158
159
160
    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;
    }
Michael Smith's avatar
Michael Smith committed
161

162
    return con;
163
164
}

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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 {
185
        int dst;
186
        for(i=0; i < global.server_sockets; i++) {
187
            if(ufds[i].revents & POLLIN)
188
                return ufds[i].fd;
189
190
191
192
193
194
195
196
197
            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;
            }
198
        }
199
200
201
202
203
204
205
206
207
208
209
        /* 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;
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    }
#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;
227
        tv.tv_usec = (timeout % 1000) * 1000;
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        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
248
249
static connection_t *_accept_connection(void)
{
250
251
252
    int sock;
    connection_t *con;
    char *ip;
253
    int serversock; 
Jack Moffitt's avatar
Jack Moffitt committed
254

255
256
257
    serversock = wait_for_serversock(100);
    if(serversock < 0)
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
258

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

262
    sock = sock_accept(serversock, ip, MAX_ADDR_LEN);
263
264
265
266
267
    if (sock >= 0)
    {
        con = connection_create (sock, serversock, ip);
        if (con == NULL)
            free (ip);
Jack Moffitt's avatar
Jack Moffitt committed
268

269
270
        return con;
    }
Jack Moffitt's avatar
Jack Moffitt committed
271

272
273
274
275
    if (!sock_recoverable(sock_error()))
        WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
    
    free(ip);
Jack Moffitt's avatar
Jack Moffitt committed
276

277
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
278
279
280
}


281
282
283
284
285
/* 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
286
{
287
288
289
290
    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
291
292
293
}


294
295
296
297
298
299
/* 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
300

301
302
303
304
305
306
307
308
309
    /* 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);
310
    }
311
312
    return node;
}
Jack Moffitt's avatar
Jack Moffitt committed
313
314


315
316
317
318
319
320
321
/* run along queue checking for any data that has come in or a timeout */
static void process_request_queue ()
{
    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
322

323
324
325
326
327
328
    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
329

330
331
332
333
334
335
336
        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
337

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
        if (len > 0)
        {
            int pass_it = 1;
            char *ptr;

            node->offset += len;
            client->refbuf->data [node->offset] = '\000';
            do
            {
                if (node->shoutcast == 1)
                {
                    /* password line */
                    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 */
                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
371

372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
            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);
            }
        }
        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;
394
    }
Jack Moffitt's avatar
Jack Moffitt committed
395
396
}

397

398
399
400
401
402
403
404
405
406
/* 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
407
408
}

409

Jack Moffitt's avatar
Jack Moffitt committed
410
411
void connection_accept_loop(void)
{
412
    connection_t *con;
Jack Moffitt's avatar
Jack Moffitt committed
413

414
    tid = thread_create ("connection thread", _handle_connection, NULL, THREAD_ATTACHED);
Jack Moffitt's avatar
Jack Moffitt committed
415

416
417
    while (global.running == ICE_RUNNING)
    {
418
419
420
        con = _accept_connection();

        if (con)
421
        {
422
423
424
425
            client_queue_t *node;
            ice_config_t *config;
            int i;
            client_t *client = NULL;
426

427
428
429
430
431
432
433
434
            global_lock();
            if (client_create (&client, con, NULL) < 0)
            {
                global_unlock();
                client_send_404 (client, "Icecast connection limit reached");
                continue;
            }
            global_unlock();
435

436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
            /* 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;
                }
            }
            config_release_config(); 

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

462
463
            _add_request_queue (node);
            stats_event_inc (NULL, "connections");
464
        }
465
        process_request_queue ();
466
    }
Jack Moffitt's avatar
Jack Moffitt committed
467

468
469
470
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

471
472
    if (tid)
        thread_join (tid);
Jack Moffitt's avatar
Jack Moffitt committed
473

474
475
476
    /* 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
477
478
}

479
480
481

/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
482
 */
483
int connection_complete_source (source_t *source, int response)
484
485
486
487
488
489
490
491
492
{
    ice_config_t *config = config_get_config();

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

    if (global.sources < config->source_limit)
    {
        char *contenttype;
493
        mount_proxy *mountinfo;
494
495
496
497
498
499
500
501
502
503
504
505
        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();
506
507
                if (response)
                {
508
                    client_send_404 (source->client, "Content-type not supported");
509
510
                    source->client = NULL;
                }
511
512
513
514
515
516
                WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
                return -1;
            }
        }
        else
        {
517
            WARN0("No content-type header, falling back to backwards compatibility mode "
518
                    "for icecast 1.x relays. Assuming content is mp3.");
519
            format_type = FORMAT_TYPE_GENERIC;
520
521
        }

Karl Heyes's avatar
Karl Heyes committed
522
        if (format_get_plugin (format_type, source) < 0)
523
524
525
        {
            global_unlock();
            config_release_config();
526
527
            if (response)
            {
528
                client_send_404 (source->client, "internal format allocation problem");
529
530
                source->client = NULL;
            }
531
532
533
534
            WARN1 ("plugin format failed for \"%s\"", source->mount);
            return -1;
        }

535
536
537
        global.sources++;
        stats_event_args (NULL, "sources", "%d", global.sources);
        global_unlock();
538

539
540
541
542
543
        source->running = 1;
        mountinfo = config_find_mount (config, source->mount);
        if (mountinfo == NULL)
            source_update_settings (config, source, mountinfo);
        source_recheck_mounts ();
544
545
546
547
548
549
550
        config_release_config();

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

        return 0;
    }
551
    WARN1("Request to add source when maximum source limit "
552
553
554
555
556
            "reached %d", global.sources);

    global_unlock();
    config_release_config();

557
558
    if (response)
    {
559
        client_send_404 (source->client, "too many sources connected");
560
561
        source->client = NULL;
    }
562
563
564
565
566

    return -1;
}


567
568
static int _check_pass_http(http_parser_t *parser, 
        char *correctuser, char *correctpass)
569
570
571
572
573
574
575
576
577
578
579
580
581
{
    /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
    char *header = httpp_getvar(parser, "authorization");
    char *userpass, *tmp;
    char *username, *password;

    if(header == NULL)
        return 0;

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

    userpass = util_base64_decode(header+6);
582
583
584
    if(userpass == NULL) {
        WARN1("Base64 decode of Authorization header \"%s\" failed",
                header+6);
585
        return 0;
586
    }
587
588
589
590
591
592
593
594
595
596

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

597
    if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
598
599
600
        free(userpass);
        return 0;
    }
601
    free(userpass);
602
603
604
605

    return 1;
}

606
607
608
609
610
611
612
613
static int _check_pass_icy(http_parser_t *parser, char *correctpass)
{
    char *password;

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

614
    if (strcmp(password, correctpass))
615
616
617
618
619
        return 0;
    else
        return 1;
}

620
static int _check_pass_ice(http_parser_t *parser, char *correctpass)
621
{
622
    char *password;
623
624
625
626
627

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

628
    if (strcmp(password, correctpass))
629
630
631
632
633
        return 0;
    else
        return 1;
}

634
int connection_check_admin_pass(http_parser_t *parser)
635
{
636
    int ret;
Michael Smith's avatar
Michael Smith committed
637
638
639
    ice_config_t *config = config_get_config();
    char *pass = config->admin_password;
    char *user = config->admin_username;
640
    char *protocol;
641
642
643
644
645
646

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

647
648
649
650
651
    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
652
    config_release_config();
653
654
    return ret;
}
Michael Smith's avatar
Michael Smith committed
655

656
657
658
659
660
int connection_check_relay_pass(http_parser_t *parser)
{
    int ret;
    ice_config_t *config = config_get_config();
    char *pass = config->relay_password;
661
    char *user = config->relay_username;
Michael Smith's avatar
Michael Smith committed
662

663
664
    if(!pass || !user) {
        config_release_config();
665
        return 0;
666
    }
667

668
669
670
    ret = _check_pass_http(parser, user, pass);
    config_release_config();
    return ret;
671
672
}

673
int connection_check_source_pass(http_parser_t *parser, const char *mount)
674
{
Michael Smith's avatar
Michael Smith committed
675
676
    ice_config_t *config = config_get_config();
    char *pass = config->source_password;
677
    char *user = "source";
678
    int ret;
Michael Smith's avatar
Michael Smith committed
679
    int ice_login = config->ice_login;
680
    char *protocol;
Michael Smith's avatar
Michael Smith committed
681

682
    mount_proxy *mountinfo = config_find_mount (config, mount);
683

684
685
686
687
688
689
    if (mountinfo)
    {
        if (mountinfo->password)
            pass = mountinfo->password;
        if (mountinfo->username)
            user = mountinfo->username;
690
691
692
693
    }

    if(!pass) {
        WARN0("No source password set, rejecting source");
694
        config_release_config();
695
696
697
        return 0;
    }

698
    protocol = httpp_getvar(parser, HTTPP_VAR_PROTOCOL);
699
700
701
702
703
704
705
706
707
708
709
    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");
        }
710
    }
711
    config_release_config();
712
    return ret;
713
714
}

715

716
static void _handle_source_request (client_t *client, char *uri, int auth_style)
717
{
718
    source_t *source;
719

720
    INFO1("Source logging in at mountpoint \"%s\"", uri);
721

722
723
724
725
726
727
    if (uri[0] != '/')
    {
        WARN0 ("source mountpoint not starting with /");
        client_send_401 (client);
        return;
    }
728
    if (auth_style == ICECAST_SOURCE_AUTH) {
729
730
        if (connection_check_source_pass (client->parser, uri) == 0)
        {
731
732
733
734
            /* 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 */
735
            INFO1("Source (%s) attempted to login with invalid or missing password", uri);
736
737
738
            client_send_401(client);
            return;
        }
739
    }
740
741
742
    source = source_reserve (uri);
    if (source)
    {
743
744
745
        if (auth_style == SHOUTCAST_SOURCE_AUTH) {
            source->shoutcast_compat = 1;
        }
746
        source->client = client;
747
748
        source->parser = client->parser;
        source->con = client->con;
749
        if (connection_complete_source (source, 1) < 0)
750
        {
751
            source_clear_source (source);
752
753
754
            source_free_source (source);
        }
        else
755
        {
756
            refbuf_t *ok = refbuf_new (PER_CLIENT_REFBUF_SIZE);
757
            client->respcode = 200;
758
            snprintf (ok->data, PER_CLIENT_REFBUF_SIZE,
759
                    "HTTP/1.0 200 OK\r\n\r\n");
760
761
762
763
            ok->len = strlen (ok->data);
            /* we may have unprocessed data read in, so don't overwrite it */
            ok->associated = client->refbuf;
            client->refbuf = ok;
764
765
            fserve_add_client_callback (client, source_client_callback, source);
        }
766
767
768
769
    }
    else
    {
        client_send_404 (client, "Mountpoint in use");
770
        WARN1 ("Mountpoint %s in use", uri);
771
    }
772
773
}

774

775
static void _handle_stats_request (client_t *client, char *uri)
Jack Moffitt's avatar
Jack Moffitt committed
776
{
777
    stats_event_inc(NULL, "stats_connections");
778
779
780
781

    if (connection_check_admin_pass (client->parser) == 0)
    {
        client_send_401 (client);
782
783
        ERROR0("Bad password for stats connection");
        return;
784
    }
785

786
    client->respcode = 200;
787
788
789
790
    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);
791
792
}

793
static void _handle_get_request (client_t *client, char *passed_uri)
794
{
Michael Smith's avatar
Michael Smith committed
795
796
    int fileserve;
    int port;
797
    int i;
Karl Heyes's avatar
Karl Heyes committed
798
799
    char *serverhost = NULL;
    int serverport = 0;
800
    aliases *alias;
Michael Smith's avatar
Michael Smith committed
801
    ice_config_t *config;
802
    char *uri = passed_uri;
Michael Smith's avatar
Michael Smith committed
803
804
805
806

    config = config_get_config();
    fileserve = config->fileserve;
    port = config->port;
807
    for(i = 0; i < global.server_sockets; i++) {
808
        if(global.serversock[i] == client->con->serversock) {
809
810
811
812
813
814
            serverhost = config->listeners[i].bind_address;
            serverport = config->listeners[i].port;
            break;
        }
    }
    alias = config->aliases;
815

816
817
818
    /* 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
819
    ** and directory server authorizers, which are looking for /GUID-xxxxxxxx 
820
    ** (where xxxxxx is the GUID in question) - this isn't implemented yet.
821
822
823
824
    ** we need to handle the latter two before the former, as the latter two
    ** aren't subject to the limits.
    */
    /* TODO: add GUID-xxxxxx */
825

826
827
828
    /* 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))) {
829
830
            uri = strdup (alias->destination);
            DEBUG2 ("alias has made %s into %s", passed_uri, uri);
831
832
833
834
            break;
        }
        alias = alias->next;
    }
835
836
837
    config_release_config();

    stats_event_inc(NULL, "client_connections");
838

839
    /* Dispatch all admin requests */
840
841
    if ((strcmp(uri, "/admin.cgi") == 0) ||
        (strncmp(uri, "/admin/", 7) == 0)) {
842
        admin_handle_request(client, uri);
843
        if (uri != passed_uri) free (uri);
Michael Smith's avatar
Michael Smith committed
844
845
846
        return;
    }

847
848
849
850
    /* Here we are parsing the URI request to see
    ** if the extension is .xsl, if so, then process
    ** this request as an XSLT request
    */
851
852
    if (util_check_valid_extension (uri) == XSLT_CONTENT)
    {
853
        /* If the file exists, then transform it, otherwise, write a 404 */
854
855
        DEBUG0("Stats request, sending XSL transformed stats");
        stats_transform_xslt (client, uri);
856
        if (uri != passed_uri) free (uri);
857
        return;
858
    }
859

860
    add_client (uri, client);
861
    if (uri != passed_uri) free (uri);
862
863
}

864
865
static void _handle_shoutcast_compatible (client_queue_t *node)
{
866
867
868
    char *http_compliant;
    int http_compliant_len = 0;
    http_parser_t *parser;
869
870
871
    ice_config_t *config = config_get_config ();
    char *shoutcast_mount;
    client_t *client = node->client;
872

873
874
    if (node->shoutcast == 1)
    {
875
        char *source_password, *ptr, *headers;
876
877
878
879
880
881
882
883
884
885
        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 */
        ptr = strstr (client->refbuf->data, "\r\n");
886
887
888
889
        if (ptr)
            headers = ptr+2;
        else
        {
890
            ptr = strstr (client->refbuf->data, "\n");
891
892
893
            if (ptr)
                headers = ptr+1;
        }
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909

        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 */
            sock_write (client->con->sock, "OK2\r\n");
910
911
            node->offset -= (headers - client->refbuf->data);
            memmove (client->refbuf->data, headers, node->offset+1);
912
913
914
915
916
917
918
919
            node->shoutcast = 2;
            /* we've checked the password, now send it back for reading headers */
            _add_request_queue (node);
            free (source_password);
            return;
        }
        client_destroy (client);
        free (node);
920
921
        return;
    }
922
923
    shoutcast_mount = strdup (config->shoutcast_mount);
    config_release_config();
924
925
926
    /* 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 */
927
    http_compliant_len = 20 + strlen (shoutcast_mount) + node->offset;
928
    http_compliant = (char *)calloc(1, http_compliant_len);
929
    snprintf (http_compliant, http_compliant_len,
930
            "SOURCE %s HTTP/1.0\r\n%s", shoutcast_mount, client->refbuf->data);
931
932
    parser = httpp_create_parser();
    httpp_initialize(parser, NULL);
933
934
    if (httpp_parse (parser, http_compliant, strlen(http_compliant)))
    {
935
936
937
938
        /* we may have more than just headers, so prepare for it */
        if (node->stream_offset == node->offset)
            client->refbuf->len = 0;
        else
939
        {
940
941
942
            char *ptr = client->refbuf->data;
            client->refbuf->len = node->offset - node->stream_offset;
            memmove (ptr, ptr + node->stream_offset, client->refbuf->len);
943
        }
944
945
        client->parser = parser;
        _handle_source_request (client, shoutcast_mount, SHOUTCAST_SOURCE_AUTH);
946
    }
947
948
    else
        client_destroy (client);
949
    free (http_compliant);
950
951
952
    free (shoutcast_mount);
    free (node);
    return;
953
954
}

955
956
957
958
959

/* 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.
 */
960
961
static void *_handle_connection(void *arg)
{
962
    http_parser_t *parser;
963
    char *rawuri, *uri;
Jack Moffitt's avatar
Jack Moffitt committed
964

965
    while (global.running == ICE_RUNNING) {
Jack Moffitt's avatar
Jack Moffitt committed
966

967
        client_queue_t *node = _get_connection();
Michael Smith's avatar
Michael Smith committed
968

969
970
971
        if (node)
        {
            client_t *client = node->client;
Jack Moffitt's avatar
Jack Moffitt committed
972

973
            /* Check for special shoutcast compatability processing */
974
975
976
            if (node->shoutcast) 
            {
                _handle_shoutcast_compatible (node);
977
978
                continue;
            }
Jack Moffitt's avatar
Jack Moffitt committed
979

980
            /* process normal HTTP headers */
981
982
            parser = httpp_create_parser();
            httpp_initialize(parser, NULL);
983
984
985
986
987
988
989
990
991
992
993
994
995
            client->parser = parser;
            if (httpp_parse (parser, client->refbuf->data, node->offset))
            {
                /* we may have more than just headers, so prepare for it */
                if (node->stream_offset == node->offset)
                    client->refbuf->len = 0;
                else
                {
                    char *ptr = client->refbuf->data;
                    client->refbuf->len = node->offset - node->stream_offset;
                    memmove (ptr, ptr + node->stream_offset, client->refbuf->len);
                }
                free (node);
996
997
                
                if (strcmp("ICE",  httpp_getvar(parser, HTTPP_VAR_PROTOCOL)) &&
998
                    strcmp("HTTP", httpp_getvar(parser, HTTPP_VAR_PROTOCOL))) {
999
                    ERROR0("Bad HTTP protocol detected");
1000
                    client_destroy (client);
1001
1002
                    continue;
                }
Jack Moffitt's avatar
Jack Moffitt committed
1003

1004
1005
1006
                rawuri = httpp_getvar(parser, HTTPP_VAR_URI);
                uri = util_normalise_uri(rawuri);

1007
1008
                if (uri == NULL)
                {
1009
                    client_destroy (client);
1010
1011
                    continue;
                }
1012

1013
                if (parser->req_type == httpp_req_source) {
1014
                    _handle_source_request (client, uri, ICECAST_SOURCE_AUTH);
1015
1016
                }
                else if (parser->req_type == httpp_req_stats) {
1017
                    _handle_stats_request (client, uri);
1018
1019
                }
                else if (parser->req_type == httpp_req_get) {
1020
                    _handle_get_request (client, uri);
1021
1022
                }
                else {
1023
                    ERROR0("Wrong request type from client");
1024
                    client_send_400 (client, "unknown request");
1025
1026
1027
                }

                free(uri);
1028
            } 
1029
1030
1031
            else
            {
                free (node);
1032
                ERROR0("HTTP request parsing failed");
1033
                client_destroy (client);
1034
            }
1035
            continue;
1036
        }
1037
        thread_sleep (50000);
1038
    }
1039
    DEBUG0 ("Connection thread done");
Jack Moffitt's avatar
Jack Moffitt committed
1040

1041
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
1042
1043
1044
1045
}

void connection_close(connection_t *con)
{
1046
1047
1048
1049
    sock_close(con->sock);
    if (con->ip) free(con->ip);
    if (con->host) free(con->host);
    free(con);
Jack Moffitt's avatar
Jack Moffitt committed
1050
}