slave.c 18.6 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
18
19
20
/* slave.c
 * by Ciaran Anscomb <ciaran.anscomb@6809.org.uk>
 *
 * Periodically requests a list of streams from a master server
 * and creates source threads for any it doesn't already have.
 * */

21
22
23
24
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>

#ifndef _WIN32
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#include <winsock2.h>
#define snprintf _snprintf
#define strcasecmp stricmp
#define strncasecmp strnicmp
#endif

#include "os.h"

Karl Heyes's avatar
Karl Heyes committed
44
45
46
47
#include "thread/thread.h"
#include "avl/avl.h"
#include "net/sock.h"
#include "httpp/httpp.h"
48

49
#include "cfgfile.h"
50
51
52
53
54
55
56
57
#include "global.h"
#include "util.h"
#include "connection.h"
#include "refbuf.h"
#include "client.h"
#include "stats.h"
#include "logging.h"
#include "source.h"
Michael Smith's avatar
Michael Smith committed
58
#include "format.h"
59
#include "event.h"
60
61
62
63

#define CATMODULE "slave"

static void *_slave_thread(void *arg);
64
static thread_type *_slave_thread_id;
65
static int slave_running = 0;
66
static int update_settings = 0;
67
68
volatile static unsigned int max_interval = 0;
volatile static int rescan_relays = 0;
69

70
relay_server *relay_free (relay_server *relay)
71
{
72
73
74
75
76
77
78
    relay_server *next = relay->next;
    DEBUG1("freeing relay %s", relay->localmount);
    if (relay->source)
       source_free_source (relay->source);
    xmlFree (relay->server);
    xmlFree (relay->mount);
    xmlFree (relay->localmount);
79
80
81
82
    if (relay->username)
        xmlFree (relay->username);
    if (relay->password)
        xmlFree (relay->password);
83
    free (relay);
84
    return next;
85
86
}

87

88
89
90
relay_server *relay_copy (relay_server *r)
{
    relay_server *copy = calloc (1, sizeof (relay_server));
Michael Smith's avatar
Michael Smith committed
91

92
    if (copy)
Michael Smith's avatar
Michael Smith committed
93
    {
94
95
96
        copy->server = xmlStrdup (r->server);
        copy->mount = xmlStrdup (r->mount);
        copy->localmount = xmlStrdup (r->localmount);
97
98
99
100
        if (r->username)
            copy->username = xmlStrdup (r->username);
        if (r->password)
            copy->password = xmlStrdup (r->password);
101
102
        copy->port = r->port;
        copy->mp3metadata = r->mp3metadata;
103
        copy->on_demand = r->on_demand;
Michael Smith's avatar
Michael Smith committed
104
    }
105
106
    return copy;
}
107

108

109
110
111
/* force a recheck of the relays. This will recheck the master server if
 * a this is a slave.
 */
112
void slave_recheck_mounts (void)
113
{
114
    max_interval = 0;
115
    update_settings = 1;
116
117
}

118

119
120
121
122
123
124
125
126
127
/* Request slave thread to rescan the existing relays to see if any need
 * starting up, eg on-demand relays
 */
void slave_rescan (void)
{
    rescan_relays = 1;
}


128
129
/* Request slave thread to check the relay list for changes and to
 * update the stats for the current streams.
130
 */
131
void slave_rebuild_mounts (void)
132
{
133
    update_settings = 1;
134
    rescan_relays = 1;
135
136
}

137
138

void slave_initialize(void)
Michael Smith's avatar
Michael Smith committed
139
{
140
141
    if (slave_running)
        return;
Michael Smith's avatar
Michael Smith committed
142

143
    slave_running = 1;
144
    max_interval = 0;
145
146
    _slave_thread_id = thread_create("Slave Thread", _slave_thread, NULL, THREAD_ATTACHED);
}
147

Michael Smith's avatar
Michael Smith committed
148

149
150
151
void slave_shutdown(void)
{
    if (!slave_running)
152
        return;
153
    slave_running = 0;
154
    DEBUG0 ("waiting for slave thread");
155
156
157
158
159
160
161
    thread_join (_slave_thread_id);
}


/* This does the actual connection for a relay. A thread is
 * started off if a connection can be acquired
 */
162
static void *start_relay_stream (void *arg)
163
{
164
    relay_server *relay = arg;
165
166
167
168
169
170
    sock_t streamsock = SOCK_ERROR;
    source_t *src = relay->source;
    http_parser_t *parser = NULL;
    connection_t *con=NULL;
    char header[4096];

171
    relay->running = 1;
172
173
174
    INFO1("Starting relayed source at mountpoint \"%s\"", relay->localmount);
    do
    {
175
176
        char *auth_header;

177
178
179
180
181
182
        streamsock = sock_connect_wto (relay->server, relay->port, 30);
        if (streamsock == SOCK_ERROR)
        {
            WARN3("Failed to relay stream from master server, couldn't connect to http://%s:%d%s",
                    relay->server, relay->port, relay->mount);
            break;
Michael Smith's avatar
Michael Smith committed
183
        }
184
        con = connection_create (streamsock, -1, NULL);
185

186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
        if (relay->username && relay->password)
        {
            char *esc_authorisation;
            unsigned len = strlen(relay->username) + strlen(relay->password) + 2;

            auth_header = malloc (len);
            snprintf (auth_header, len, "%s:%s", relay->username, relay->password);
            esc_authorisation = util_base64_encode(auth_header);
            free(auth_header);
            len = strlen (esc_authorisation) + 24;
            auth_header = malloc (len);
            snprintf (auth_header, len,
                    "Authorization: Basic %s\r\n", esc_authorisation);
            free(esc_authorisation);
        }
        else
        {
            auth_header = strdup ("");
        }

206
207
208
209
210
211
212
213
        /* At this point we may not know if we are relaying an mp3 or vorbis
         * stream, but only send the icy-metadata header if the relay details
         * state so (the typical case).  It's harmless in the vorbis case. If
         * we don't send in this header then relay will not have mp3 metadata.
         */
        sock_write(streamsock, "GET %s HTTP/1.0\r\n"
                "User-Agent: " ICECAST_VERSION_STRING "\r\n"
                "%s"
214
                "%s"
215
                "\r\n",
216
217
218
219
                relay->mount,
                relay->mp3metadata?"Icy-MetaData: 1\r\n":"",
                auth_header);
        free (auth_header);
220
        memset (header, 0, sizeof(header));
221
        if (util_read_header (con->sock, header, 4096, READ_ENTIRE_HEADER) == 0)
222
223
224
225
226
227
228
229
        {
            WARN0("Header read failed");
            break;
        }
        parser = httpp_create_parser();
        httpp_initialize (parser, NULL);
        if (! httpp_parse_response (parser, header, strlen(header), relay->localmount))
        {
Michael Smith's avatar
Michael Smith committed
230
            ERROR0("Error parsing relay request");
231
232
233
234
235
236
237
238
239
240
241
242
243
244
            break;
        }
        if (httpp_getvar (parser, HTTPP_VAR_ERROR_MESSAGE))
        {
            ERROR1("Error from relay request: %s", httpp_getvar(parser, HTTPP_VAR_ERROR_MESSAGE));
            break;
        }
        src->parser = parser;
        src->con = con;
        if (connection_complete_source (src) < 0)
        {
            DEBUG0("Failed to complete source initialisation");
            break;
        }
245
        stats_event_inc(NULL, "source_relay_connections");
246
        stats_event (relay->localmount, "source_ip", relay->server);
247

248
249
        source_main (relay->source);

250
251
252
253
254
255
256
        if (relay->on_demand == 0)
        {
            /* only keep refreshing YP entries for inactive on-demand relays */
            yp_remove (relay->localmount);
            relay->source->yp_public = -1;
        }

257
258
        /* initiate an immediate relay cleanup run */
        relay->cleanup = 1;
259
        rescan_relays = 1;
260
261

        return NULL;
262
263
    } while (0);

264
265
266
267
    if (relay->source->fallback_mount)
    {
        source_t *fallback_source;

268
        DEBUG1 ("failed relay, fallback to %s", relay->source->fallback_mount);
269
270
271
272
273
274
275
276
277
        avl_tree_rlock(global.source_tree);
        fallback_source = source_find_mount (relay->source->fallback_mount);

        if (fallback_source != NULL)
            source_move_clients (relay->source, fallback_source);

        avl_tree_unlock (global.source_tree);
    }

278
279
280
281
282
283
284
285
    if (con == NULL && streamsock != SOCK_ERROR)
        sock_close (streamsock);
    if (con)
        connection_close (con);
    src->con = NULL;
    if (parser)
        httpp_destroy (parser);
    src->parser = NULL;
286
    source_clear_source (relay->source);
287
288
289

    /* initiate an immediate relay cleanup run */
    relay->cleanup = 1;
290
    rescan_relays = 1;
291
292

    return NULL;
293
294
295
296
297
298
299
300
}


/* wrapper for starting the provided relay stream */
static void check_relay_stream (relay_server *relay)
{
    if (relay->source == NULL)
    {
301
302
303
304
305
306
        if (relay->localmount[0] != '/')
        {
            WARN1 ("relay mountpoint \"%s\" does not start with /, skipping",
                    relay->localmount);
            return;
        }
307
308
        /* new relay, reserve the name */
        relay->source = source_reserve (relay->localmount);
309
310
311
312
        if (relay->source)
            DEBUG1("Adding relay source at mountpoint \"%s\"", relay->localmount);
        else
            WARN1 ("new relay but source \"%s\" already exists", relay->localmount);
313
    }
314
    do
315
    {
316
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
343
344
345
346
347
        source_t *source = relay->source;
        if (relay->source == NULL || relay->running)
            break;
        if (relay->on_demand)
        {
            ice_config_t *config = config_get_config ();
            mount_proxy *mountinfo = config_find_mount (config, relay->localmount);

            if (mountinfo == NULL)
                source_update_settings (config, relay->source, mountinfo);
            config_release_config ();
            slave_rebuild_mounts();
            stats_event (relay->localmount, "listeners", "0");
            relay->source->on_demand = relay->on_demand;

            if (source->fallback_mount && source->fallback_override)
            {
                source_t *fallback;
                DEBUG1 ("checking %s for fallback override", source->fallback_mount);
                avl_tree_rlock (global.source_tree);
                fallback = source_find_mount (source->fallback_mount);
                if (fallback && fallback->running && fallback->listeners)
                {
                   DEBUG2 ("fallback running %d with %lu listeners", fallback->running, fallback->listeners);
                   source->on_demand_req = 1;
                }
                avl_tree_unlock (global.source_tree);
            }
            if (source->on_demand_req == 0)
                break;
        }

348
349
350
        relay->thread = thread_create ("Relay Thread", start_relay_stream,
                relay, THREAD_ATTACHED);
        return;
351
352
353

    } while(0);
    /* the relay thread may of shut down itself */
354
355
356
357
358
359
360
    if (relay->cleanup && relay->thread)
    {
        DEBUG1 ("waiting for relay thread for \"%s\"", relay->localmount);
        thread_join (relay->thread);
        relay->thread = NULL;
        relay->cleanup = 0;
        relay->running = 0;
361
362
363
364
365
366
367
368
369

        if (relay->on_demand)
        {
            ice_config_t *config = config_get_config ();
            mount_proxy *mountinfo = config_find_mount (config, relay->localmount);
            source_update_settings (config, relay->source, mountinfo);
            config_release_config ();
            stats_event (relay->localmount, "listeners", "0");
        }
Michael Smith's avatar
Michael Smith committed
370
    }
371
372
}

Michael Smith's avatar
Michael Smith committed
373

374
375
376
377
378
379
380
381
382
383
384
385
386
/* compare the 2 relays to see if there are any changes, return 1 if
 * the relay needs to be restarted, 0 otherwise
 */
static int relay_has_changed (relay_server *new, relay_server *old)
{
    do
    {
        if (strcmp (new->mount, old->mount) != 0)
            break;
        if (strcmp (new->server, old->server) != 0)
            break;
        if (new->port != old->port)
            break;
387
388
        if (new->mp3metadata != old->mp3metadata)
            break;
389
390
        if (new->on_demand != old->on_demand)
            old->on_demand = new->on_demand;
391
392
393
394
395
396
        return 0;
    } while (0);
    return 1;
}


397
398
399
400
401
402
403
404
405
406
407
408
409
/* go through updated looking for relays that are different configured. The
 * returned list contains relays that should be kept running, current contains
 * the list of relays to shutdown
 */
static relay_server *
update_relay_set (relay_server **current, relay_server *updated)
{
    relay_server *relay = updated;
    relay_server *existing_relay, **existing_p;
    relay_server *new_list = NULL;

    while (relay)
    {
410
411
412
413
414
415
416
        existing_relay = *current;
        existing_p = current;

        while (existing_relay)
        {
            /* break out if keeping relay */
            if (strcmp (relay->localmount, existing_relay->localmount) == 0)
417
418
                if (relay_has_changed (relay, existing_relay) == 0)
                    break;
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
            existing_p = &existing_relay->next;
            existing_relay = existing_relay->next;
        }
        if (existing_relay == NULL)
        {
            /* new one, copy and insert */
            existing_relay = relay_copy (relay);
        }
        else
        {
            *existing_p = existing_relay->next;
        }
        existing_relay->next = new_list;
        new_list = existing_relay;
        relay = relay->next;
434
    }
435
436
437
438
439
440
    return new_list;
}


/* update the relay_list with entries from new_relay_list. Any new relays
 * are added to the list, and any not listed in the provided new_relay_list
441
 * are separated and returned in a separate list
442
 */
443
static relay_server *
444
445
update_relays (relay_server **relay_list, relay_server *new_relay_list)
{
446
    relay_server *active_relays, *cleanup_relays;
447

448
    active_relays = update_relay_set (relay_list, new_relay_list);
449

450
451
452
453
454
455
456
457
458
459
460
461
462
    cleanup_relays = *relay_list;
    /* re-assign new set */
    *relay_list = active_relays;

    return cleanup_relays;
}


static void relay_check_streams (relay_server *to_start, relay_server *to_free)
{
    relay_server *relay;

    while (to_free)
463
    {
464
        if (to_free->source)
465
        {
466
467
468
469
470
471
472
473
474
475
            if (to_free->running)
            {
                /* relay has been removed from xml, shut down active relay */
                DEBUG1 ("source shutdown request on \"%s\"", to_free->localmount);
                to_free->source->running = 0;
                thread_join (to_free->thread);
                slave_rebuild_mounts();
            }
            else
                stats_event (to_free->localmount, NULL, NULL);
476
        }
477
478
479
480
481
482
483
484
        to_free = relay_free (to_free);
    }

    relay = to_start;
    while (relay)
    {
        check_relay_stream (relay);
        relay = relay->next;
485
    }
Michael Smith's avatar
Michael Smith committed
486
487
}

488
489
490
491
492

static int update_from_master(ice_config_t *config)
{
    char *master = NULL, *password = NULL, *username= NULL;
    int port;
493
    sock_t mastersock;
494
    int ret = 0;
495
    char buf[256];
496
497
498
    do
    {
        char *authheader, *data;
499
        relay_server *new_relays = NULL, *cleanup_relays;
500
        int len, count = 1;
501
        int on_demand;
502

503
        username = strdup (config->master_username);
504
505
        if (config->master_password)
            password = strdup (config->master_password);
Michael Smith's avatar
Michael Smith committed
506

507
508
        if (config->master_server)
            master = strdup (config->master_server);
Michael Smith's avatar
Michael Smith committed
509

510
        port = config->master_server_port;
Michael Smith's avatar
Michael Smith committed
511

512
513
        if (password == NULL || master == NULL || port == 0)
            break;
514
        on_demand = config->on_demand;
515
516
517
        ret = 1;
        config_release_config();
        mastersock = sock_connect_wto (master, port, 0);
518

519
520
521
522
523
        if (mastersock == SOCK_ERROR)
        {
            WARN0("Relay slave failed to contact master server to fetch stream list");
            break;
        }
Michael Smith's avatar
Michael Smith committed
524

525
526
527
        len = strlen(username) + strlen(password) + 2;
        authheader = malloc(len);
        snprintf (authheader, len, "%s:%s", username, password);
528
529
530
531
532
533
534
535
        data = util_base64_encode(authheader);
        sock_write (mastersock,
                "GET /admin/streamlist.txt HTTP/1.0\r\n"
                "Authorization: Basic %s\r\n"
                "\r\n", data);
        free(authheader);
        free(data);

536
537
538
539
540
541
542
543
        if (sock_read_line(mastersock, buf, sizeof(buf)) == 0 ||
                strncmp (buf, "HTTP/1.0 200", 12) != 0)
        {
            sock_close (mastersock);
            WARN0 ("Master rejected streamlist request");
            break;
        }

544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        while (sock_read_line(mastersock, buf, sizeof(buf)))
        {
            if (!strlen(buf))
                break;
        }
        while (sock_read_line(mastersock, buf, sizeof(buf)))
        {
            relay_server *r;
            if (!strlen(buf))
                continue;
            DEBUG2 ("read %d from master \"%s\"", count++, buf);
            r = calloc (1, sizeof (relay_server));
            if (r)
            {
                r->server = xmlStrdup (master);
                r->port = port;
                r->mount = xmlStrdup (buf);
                r->localmount = xmlStrdup (buf);
                r->mp3metadata = 1;
563
                r->on_demand = on_demand;
564
565
                r->next = new_relays;
                new_relays = r;
566
            }
Michael Smith's avatar
Michael Smith committed
567
        }
568
569
        sock_close (mastersock);

570
571
572
573
574
575
576
577
        thread_mutex_lock (&(config_locks()->relay_lock));
        cleanup_relays = update_relays (&global.master_relays, new_relays);
        
        relay_check_streams (global.master_relays, cleanup_relays);
        relay_check_streams (NULL, new_relays);

        thread_mutex_unlock (&(config_locks()->relay_lock));

578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
    } while(0);

    if (master)
        free (master);
    if (username)
        free (username);
    if (password)
        free (password);

    return ret;
}


static void *_slave_thread(void *arg)
{
    ice_config_t *config;
594
    unsigned int interval = 0;
Michael Smith's avatar
Michael Smith committed
595

596
597
    source_recheck_mounts();

598
    while (1)
599
    {
600
601
        relay_server *cleanup_relays;

602
603
604
605
606
607
608
        /* re-read xml file if requested */
        if (global . schedule_config_reread)
        {
            event_config_read (NULL);
            global . schedule_config_reread = 0;
        }

609
        thread_sleep (1000000);
610
611
        if (slave_running == 0)
            break;
612
        if (rescan_relays == 0 && max_interval > ++interval)
613
614
            continue;

615
616
617
618
619
        /* only update relays lists when required */
        if (max_interval <= interval)
        {
            DEBUG0 ("checking master stream list");
            config = config_get_config();
Michael Smith's avatar
Michael Smith committed
620

621
622
            interval = 0;
            max_interval = config->master_update_interval;
Michael Smith's avatar
Michael Smith committed
623

624
625
626
            /* the connection could take some time, so the lock can drop */
            if (update_from_master (config))
                config = config_get_config();
627

628
            thread_mutex_lock (&(config_locks()->relay_lock));
629

630
            cleanup_relays = update_relays (&global.relays, config->relay);
631

632
            config_release_config();
633

634
635
636
637
            relay_check_streams (global.relays, cleanup_relays);
            thread_mutex_unlock (&(config_locks()->relay_lock));
        }
        else
638
        {
639
640
641
642
643
            DEBUG0 ("rescanning relay lists");
            thread_mutex_lock (&(config_locks()->relay_lock));
            relay_check_streams (global.master_relays, NULL);
            relay_check_streams (global.relays, NULL);
            thread_mutex_unlock (&(config_locks()->relay_lock));
Michael Smith's avatar
Michael Smith committed
644
        }
645
        rescan_relays = 0;
646
647
648
649
650
        if (update_settings)
        {
            update_settings = 0;
            source_recheck_mounts();
        }
651
    }
652
653
654
655
    DEBUG0 ("shutting down current relays");
    relay_check_streams (NULL, global.relays);
    relay_check_streams (NULL, global.master_relays);

656
657
    INFO0 ("Slave thread shutdown complete");

658
    return NULL;
659
}
Michael Smith's avatar
Michael Smith committed
660