slave.c 27.4 KB
Newer Older
1 2 3 4 5
/* Icecast
 *
 * This program is distributed under the GNU General Public License, version 2.
 * A copy of this license is included with this source.
 *
6
 * Copyright 2000-2004, Jack Moffitt <jack@xiph.org,
7 8 9 10 11 12
 *                      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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#ifndef _WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#else
#include <winsock2.h>
#endif

37
#include "compat.h"
38

39
#include <libxml/uri.h>
Marvin Scholz's avatar
Marvin Scholz committed
40 41 42 43
#include "common/thread/thread.h"
#include "common/avl/avl.h"
#include "common/net/sock.h"
#include "common/httpp/httpp.h"
44

45
#include "slave.h"
46
#include "cfgfile.h"
47 48 49 50 51 52 53 54
#include "global.h"
#include "util.h"
#include "connection.h"
#include "refbuf.h"
#include "client.h"
#include "stats.h"
#include "logging.h"
#include "source.h"
Michael Smith's avatar
Michael Smith committed
55
#include "format.h"
56 57 58

#define CATMODULE "slave"

59 60 61 62 63 64 65 66 67 68
struct relay_tag {
    relay_config_t *config;
    source_t *source;
    int running;
    int cleanup;
    time_t start;
    thread_type *thread;
    relay_t *next;
};

69
static void *_slave_thread(void *arg);
70
static thread_type *_slave_thread_id;
71
static int slave_running = 0;
72
static volatile int update_settings = 0;
73
static volatile int update_all_mounts = 0;
74
static volatile unsigned int max_interval = 0;
75
static mutex_t _slave_mutex; // protects update_settings, update_all_mounts, max_interval
76

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
static inline void relay_config_upstream_free (relay_config_upstream_t *upstream)
{
    if (upstream->server)
        xmlFree(upstream->server);
    if (upstream->mount)
        xmlFree(upstream->mount);
    if (upstream->username)
        xmlFree(upstream->username);
    if (upstream->password)
        xmlFree(upstream->password);
}

void relay_config_free (relay_config_t *relay)
{
    size_t i;

    ICECAST_LOG_DEBUG("freeing relay config for %s", relay->localmount);

    for (i = 0; i < relay->upstreams; i++) {
        relay_config_upstream_free(&(relay->upstream[i]));
    }

    relay_config_upstream_free(&(relay->upstream_default));

    xmlFree(relay->localmount);
    free(relay->upstream);
    free(relay);
}

relay_t *relay_free (relay_t *relay)
107
{
108 109 110 111
    relay_t *next = relay->next;

    ICECAST_LOG_DEBUG("freeing relay %s", relay->config->localmount);

112 113
    if (relay->source)
       source_free_source (relay->source);
114 115 116 117

    relay_config_free(relay->config);

    free(relay);
118
    return next;
119 120
}

121

122
static inline void relay_config_upstream_copy(relay_config_upstream_t *dst, const relay_config_upstream_t *src)
123
{
124 125
    dst->server = (char *)xmlCharStrdup(src->server);
    dst->mount = (char *)xmlCharStrdup(src->mount);
Michael Smith's avatar
Michael Smith committed
126

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    if (src->username)
        dst->username = (char *)xmlCharStrdup(src->username);
    if (src->password)
        dst->password = (char *)xmlCharStrdup(src->password);

    dst->port = src->port;

    dst->mp3metadata = src->mp3metadata;
}

static inline relay_config_t *relay_config_copy (relay_config_t *r)
{
    relay_config_t *copy = calloc (1, sizeof (relay_config_t));
    relay_config_upstream_t *u = NULL;
    size_t i;

    if (r->upstreams) {
        u = calloc(r->upstreams, sizeof(relay_config_upstream_t));
        if (!u) {
            free(copy);
            return NULL;
        }
    }

    if (!copy) {
        free(u);
        return NULL;
Michael Smith's avatar
Michael Smith committed
154
    }
155 156 157 158 159 160 161 162 163

    copy->upstream = u;

    copy->localmount = (char *)xmlCharStrdup(r->localmount);
    copy->on_demand = r->on_demand;

    relay_config_upstream_copy(&(copy->upstream_default), &(r->upstream_default));

    for (i = 0; i < r->upstreams; i++)
Philipp Schafft's avatar
Philipp Schafft committed
164
        relay_config_upstream_copy(&(copy->upstream[i]), &(r->upstream[i]));
165 166


167 168
    return copy;
}
169

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
static inline relay_t *relay_new(relay_config_t *config)
{
    relay_t *r = calloc(1, sizeof(*r));

    if (!r)
        return NULL;

    r->config = relay_config_copy(config);
    if (!r->config) {
        free(r);
        return NULL;
    }

    return r;
}
185

186
/* force a recheck of the relays. This will recheck the master server if
187
 * this is a slave and rebuild all mountpoints in the stats tree
188
 */
189
void slave_update_all_mounts(void)
190
{
191
    thread_mutex_lock(&_slave_mutex);
192
    max_interval = 0;
193
    update_all_mounts = 1;
194
    update_settings = 1;
195
    thread_mutex_unlock(&_slave_mutex);
196 197
}

198 199 200

/* Request slave thread to check the relay list for changes and to
 * update the stats for the current streams.
201
 */
202
void slave_rebuild_mounts(void)
203
{
204
    thread_mutex_lock(&_slave_mutex);
205
    update_settings = 1;
206
    thread_mutex_unlock(&_slave_mutex);
207 208
}

209 210

void slave_initialize(void)
Michael Smith's avatar
Michael Smith committed
211
{
212 213
    if (slave_running)
        return;
Michael Smith's avatar
Michael Smith committed
214

215
    slave_running = 1;
216
    max_interval = 0;
217
    thread_mutex_create (&_slave_mutex);
218 219
    _slave_thread_id = thread_create("Slave Thread", _slave_thread, NULL, THREAD_ATTACHED);
}
220

Michael Smith's avatar
Michael Smith committed
221

222 223 224
void slave_shutdown(void)
{
    if (!slave_running)
225
        return;
226
    slave_running = 0;
227
    ICECAST_LOG_DEBUG("waiting for slave thread");
228 229 230 231
    thread_join (_slave_thread_id);
}


232 233
/* Actually open the connection and do some http parsing, handle any 302
 * responses within here.
234
 */
235 236
#define _GET_UPSTREAM_SETTING(n) ((upstream && upstream->n) ? upstream->n : relay->config->upstream_default.n)
static client_t *open_relay_connection (relay_t *relay, relay_config_upstream_t *upstream)
237
{
238
    int redirects = 0;
239 240
    char *server_id = NULL;
    ice_config_t *config;
241 242
    http_parser_t *parser = NULL;
    connection_t *con=NULL;
243 244 245
    char *server = strdup (_GET_UPSTREAM_SETTING(server));
    char *mount = strdup (_GET_UPSTREAM_SETTING(mount));
    int port = _GET_UPSTREAM_SETTING(port);
246
    char *auth_header;
247 248
    char header[4096];

249 250 251 252
    config = config_get_config ();
    server_id = strdup (config->server_id);
    config_release_config ();

253
    /* build any authentication header before connecting */
254
    if (_GET_UPSTREAM_SETTING(username) && _GET_UPSTREAM_SETTING(password))
255
    {
256
        char *esc_authorisation;
257
        unsigned len = strlen(_GET_UPSTREAM_SETTING(username)) + strlen(_GET_UPSTREAM_SETTING(password)) + 2;
258 259

        auth_header = malloc (len);
260
        snprintf (auth_header, len, "%s:%s", _GET_UPSTREAM_SETTING(username), _GET_UPSTREAM_SETTING(password));
261
        esc_authorisation = util_base64_encode(auth_header, len);
262 263 264 265 266 267 268 269 270
        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 ("");
271

272 273 274 275
    while (redirects < 10)
    {
        sock_t streamsock;

276
        ICECAST_LOG_INFO("connecting to %s:%d", server, port);
277

278
        streamsock = sock_connect_wto_bind (server, port, _GET_UPSTREAM_SETTING(bind), 10);
279 280
        if (streamsock == SOCK_ERROR)
        {
281
            ICECAST_LOG_WARN("Failed to connect to %s:%d", server, port);
282
            break;
Michael Smith's avatar
Michael Smith committed
283
        }
284
        con = connection_create(streamsock, NULL, NULL, strdup(server));
285

286 287 288 289 290 291
        /* 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"
292
                "User-Agent: %s\r\n"
Karl Heyes's avatar
Karl Heyes committed
293
                "Host: %s\r\n"
294
                "%s"
295
                "%s"
296
                "\r\n",
297
                mount,
298
                server_id,
Karl Heyes's avatar
Karl Heyes committed
299
                server,
300
                _GET_UPSTREAM_SETTING(mp3metadata) ? "Icy-MetaData: 1\r\n" : "",
301
                auth_header);
302
        memset (header, 0, sizeof(header));
303
        if (util_read_header (con->sock, header, 4096, READ_ENTIRE_HEADER) == 0)
304
        {
305
            ICECAST_LOG_ERROR("Header read failed for %s (%s:%d%s)", relay->config->localmount, server, port, mount);
306 307 308 309
            break;
        }
        parser = httpp_create_parser();
        httpp_initialize (parser, NULL);
310
        if (! httpp_parse_response (parser, header, strlen(header), relay->config->localmount))
311
        {
312
            ICECAST_LOG_ERROR("Error parsing relay request for %s (%s:%d%s)", relay->config->localmount,
313
                    server, port, mount);
314 315
            break;
        }
316
        if (strcmp (httpp_getvar (parser, HTTPP_VAR_ERROR_CODE), "302") == 0)
317
        {
318 319 320
            /* better retry the connection again but with different details */
            const char *uri, *mountpoint;
            int len;
321

322
            uri = httpp_getvar (parser, "location");
323
            ICECAST_LOG_INFO("redirect received %s", uri);
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
            if (strncmp (uri, "http://", 7) != 0)
                break;
            uri += 7;
            mountpoint = strchr (uri, '/');
            free (mount);
            if (mountpoint)
                mount = strdup (mountpoint);
            else
                mount = strdup ("/");

            len = strcspn (uri, ":/");
            port = 80;
            if (uri [len] == ':')
                port = atoi (uri+len+1);
            free (server);
            server = calloc (1, len+1);
            strncpy (server, uri, len);
            connection_close (con);
            httpp_destroy (parser);
343 344 345
            con = NULL;
            parser = NULL;
        }
346 347 348 349 350 351
        else
        {
            client_t *client = NULL;

            if (httpp_getvar (parser, HTTPP_VAR_ERROR_MESSAGE))
            {
352
                ICECAST_LOG_ERROR("Error from relay request: %s (%s)", relay->config->localmount,
353 354 355 356 357 358 359 360 361 362 363 364 365 366
                        httpp_getvar(parser, HTTPP_VAR_ERROR_MESSAGE));
                break;
            }
            global_lock ();
            if (client_create (&client, con, parser) < 0)
            {
                global_unlock ();
                /* make sure only the client_destory frees these */
                con = NULL;
                parser = NULL;
                client_destroy (client);
                break;
            }
            global_unlock ();
367
            sock_set_blocking (streamsock, 0);
368
            client_set_queue (client, NULL);
369
            client_complete(client);
370 371
            free (server);
            free (mount);
372
            free (server_id);
373 374 375 376 377 378 379 380 381
            free (auth_header);

            return client;
        }
        redirects++;
    }
    /* failed, better clean up */
    free (server);
    free (mount);
382
    free (server_id);
383 384 385 386 387 388 389 390 391 392 393 394 395 396
    free (auth_header);
    if (con)
        connection_close (con);
    if (parser)
        httpp_destroy (parser);
    return NULL;
}


/* This does the actual connection for a relay. A thread is
 * started off if a connection can be acquired
 */
static void *start_relay_stream (void *arg)
{
397
    relay_t *relay = arg;
398 399 400
    source_t *src = relay->source;
    client_t *client;

401
    ICECAST_LOG_INFO("Starting relayed source at mountpoint \"%s\"", relay->config->localmount);
402 403
    do
    {
404
        client = open_relay_connection(relay, NULL);
405 406 407 408 409 410 411

        if (client == NULL)
            continue;

        src->client = client;
        src->parser = client->parser;
        src->con = client->con;
412 413

        if (connection_complete_source (src, 0) < 0)
414
        {
415
            ICECAST_LOG_INFO("Failed to complete source initialisation");
416 417 418
            client_destroy (client);
            src->client = NULL;
            continue;
419
        }
420
        stats_event_inc(NULL, "source_relay_connections");
421
        stats_event (relay->config->localmount, "source_ip", client->con->ip);
422

423 424
        source_main (relay->source);

425
        if (relay->config->on_demand == 0)
426 427
        {
            /* only keep refreshing YP entries for inactive on-demand relays */
428
            yp_remove (relay->config->localmount);
429
            relay->source->yp_public = -1;
430
            relay->start = time(NULL) + 10; /* prevent busy looping if failing */
431
            slave_update_all_mounts();
432 433
        }

434
        /* we've finished, now get cleaned up */
435
        relay->cleanup = 1;
436
        slave_rebuild_mounts();
437 438

        return NULL;
439
    } while (0); /* TODO allow looping through multiple servers */
440

441 442 443 444
    if (relay->source->fallback_mount)
    {
        source_t *fallback_source;

445
        ICECAST_LOG_DEBUG("failed relay, fallback to %s", relay->source->fallback_mount);
446
        avl_tree_rlock(global.source_tree);
447
        fallback_source = source_find_mount(relay->source->fallback_mount);
448 449

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

452
        avl_tree_unlock(global.source_tree);
453 454
    }

455
    source_clear_source(relay->source);
456

457
    /* cleanup relay, but prevent this relay from starting up again too soon */
458 459
    thread_mutex_lock(&_slave_mutex);
    thread_mutex_lock(&(config_locks()->relay_lock));
Karl Heyes's avatar
Karl Heyes committed
460
    relay->source->on_demand = 0;
461
    relay->start = time(NULL) + max_interval;
462
    relay->cleanup = 1;
463 464
    thread_mutex_unlock(&(config_locks()->relay_lock));
    thread_mutex_unlock(&_slave_mutex);
465 466

    return NULL;
467 468 469 470
}


/* wrapper for starting the provided relay stream */
471
static void check_relay_stream (relay_t *relay)
472 473 474
{
    if (relay->source == NULL)
    {
475
        if (relay->config->localmount[0] != '/')
476
        {
477
            ICECAST_LOG_WARN("relay mountpoint \"%s\" does not start with /, skipping",
478
                    relay->config->localmount);
479 480
            return;
        }
481
        /* new relay, reserve the name */
482
        relay->source = source_reserve (relay->config->localmount);
483
        if (relay->source)
484
        {
485 486
            ICECAST_LOG_DEBUG("Adding relay source at mountpoint \"%s\"", relay->config->localmount);
            if (relay->config->on_demand)
Karl Heyes's avatar
Karl Heyes committed
487 488
            {
                ice_config_t *config = config_get_config ();
489 490
                mount_proxy *mountinfo = config_find_mount (config, relay->config->localmount, MOUNT_TYPE_NORMAL);
                relay->source->on_demand = relay->config->on_demand;
Karl Heyes's avatar
Karl Heyes committed
491 492 493
                if (mountinfo == NULL)
                    source_update_settings (config, relay->source, mountinfo);
                config_release_config ();
494
                stats_event (relay->config->localmount, "listeners", "0");
495
                slave_update_all_mounts();
Karl Heyes's avatar
Karl Heyes committed
496
            }
497
        }
498
        else
499 500 501
        {
            if (relay->start == 0)
            {
502
                ICECAST_LOG_WARN("new relay but source \"%s\" already exists", relay->config->localmount);
503 504 505 506
                relay->start = 1;
            }
            return;
        }
507
    }
508
    do
509
    {
510
        source_t *source = relay->source;
511 512
        /* skip relay if active, not configured or just not time yet */
        if (relay->source == NULL || relay->running || relay->start > time(NULL))
513
            break;
514
        /* check if an inactive on-demand relay has a fallback that has listeners */
515
        if (relay->config->on_demand && source->on_demand_req == 0)
516
        {
517
            relay->source->on_demand = relay->config->on_demand;
518 519 520 521 522 523 524 525

            if (source->fallback_mount && source->fallback_override)
            {
                source_t *fallback;
                avl_tree_rlock (global.source_tree);
                fallback = source_find_mount (source->fallback_mount);
                if (fallback && fallback->running && fallback->listeners)
                {
526
                   ICECAST_LOG_DEBUG("fallback running %d with %lu listeners", fallback->running, fallback->listeners);
527 528 529 530 531 532 533 534
                   source->on_demand_req = 1;
                }
                avl_tree_unlock (global.source_tree);
            }
            if (source->on_demand_req == 0)
                break;
        }

535
        relay->start = time(NULL) + 5;
536
        relay->running = 1;
537 538 539
        relay->thread = thread_create ("Relay Thread", start_relay_stream,
                relay, THREAD_ATTACHED);
        return;
540

541
    } while (0);
542
    /* the relay thread may of shut down itself */
543
    if (relay->cleanup)
544
    {
545 546
        if (relay->thread)
        {
547
            ICECAST_LOG_DEBUG("waiting for relay thread for \"%s\"", relay->config->localmount);
548 549 550
            thread_join (relay->thread);
            relay->thread = NULL;
        }
551 552
        relay->cleanup = 0;
        relay->running = 0;
553

554
        if (relay->config->on_demand && relay->source)
555 556
        {
            ice_config_t *config = config_get_config ();
557
            mount_proxy *mountinfo = config_find_mount (config, relay->config->localmount, MOUNT_TYPE_NORMAL);
558 559
            source_update_settings (config, relay->source, mountinfo);
            config_release_config ();
560
            stats_event (relay->config->localmount, "listeners", "0");
561
        }
Michael Smith's avatar
Michael Smith committed
562
    }
563 564
}

Michael Smith's avatar
Michael Smith committed
565

566 567 568
/* compare the 2 relays to see if there are any changes, return 1 if
 * the relay needs to be restarted, 0 otherwise
 */
569 570 571
#define _EQ_STR(a,b) (((a) == (b)) || ((a) != NULL && (b) != NULL && strcmp((a), (b)) == 0))
#define _EQ_ATTR(x) (_EQ_STR((new->x), (old->x)))
static int relay_has_changed_upstream(const relay_config_upstream_t *new, const relay_config_upstream_t *old)
572
{
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    if (new->mp3metadata != old->mp3metadata)
        return 1;

    if (!_EQ_ATTR(server) || new->port != old->port)
        return 1;

    if (!_EQ_ATTR(mount))
        return 1;

/* NOTE: We currently do not consider this a relevant change. Why?
    if (!_EQ_ATTR(username) || !_EQ_ATTR(password))
        return 1;

    if (!_EQ_ATTR(bind))
        return 1;
*/

    return 0;
}

static int relay_has_changed (const relay_config_t *new, relay_config_t *old)
{
    size_t i;

    /* This is not fully true: If more upstreams has been added there is no reason
     * to restart the relay. However for now we ignore this case. TODO: Change this.
     */
    if (new->upstreams != old->upstreams)
        return 1;

    for (i = 0; i < new->upstreams; i++) {
        if (relay_has_changed_upstream(&(new->upstream[i]), &(old->upstream[i])))
            return 1;
    }

    if (relay_has_changed_upstream(&(new->upstream_default), &(old->upstream_default)))
        return 1;

    /* Why do we do this here? */
    old->on_demand = new->on_demand;

    return 0;
615 616 617
}


618 619 620 621
/* 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
 */
622 623
static relay_t *
update_relay_set(relay_t **current, relay_config_t **updated, size_t updated_length)
624
{
625 626 627 628 629 630 631
    relay_config_t *relay;
    relay_t *existing_relay, **existing_p;
    relay_t *new_list = NULL;
    size_t i;

    for (i = 0; i < updated_length; i++) {
        relay = updated[i];
632

633 634 635 636 637 638
        existing_relay = *current;
        existing_p = current;

        while (existing_relay)
        {
            /* break out if keeping relay */
639 640
            if (strcmp(relay->localmount, existing_relay->config->localmount) == 0)
                if (relay_has_changed(relay, existing_relay->config) == 0)
641
                    break;
642
            existing_p = &existing_relay->next;
643

644 645
            existing_relay = existing_relay->next;
        }
646 647


648 649 650
        if (existing_relay == NULL)
        {
            /* new one, copy and insert */
651
            existing_relay = relay_new(relay);
652 653 654 655 656 657 658
        }
        else
        {
            *existing_p = existing_relay->next;
        }
        existing_relay->next = new_list;
        new_list = existing_relay;
659
    }
660

661 662 663 664 665 666
    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
667
 * are separated and returned in a separate list
668
 */
669 670
static relay_t *
update_relays (relay_t **relay_list, relay_config_t **new_relay_list, size_t new_relay_list_length)
671
{
672
    relay_t *active_relays, *cleanup_relays;
673

674
    active_relays = update_relay_set(relay_list, new_relay_list, new_relay_list_length);
675

676 677 678 679 680 681 682 683
    cleanup_relays = *relay_list;
    /* re-assign new set */
    *relay_list = active_relays;

    return cleanup_relays;
}


684 685
static void relay_check_streams (relay_t *to_start,
        relay_t *to_free, int skip_timer)
686
{
687
    relay_t *relay;
688 689

    while (to_free)
690
    {
691
        if (to_free->source)
692
        {
693 694 695
            if (to_free->running)
            {
                /* relay has been removed from xml, shut down active relay */
696
                ICECAST_LOG_DEBUG("source shutdown request on \"%s\"", to_free->config->localmount);
697
                to_free->running = 0;
698 699 700 701
                to_free->source->running = 0;
                thread_join (to_free->thread);
            }
            else
702
                stats_event (to_free->config->localmount, NULL, NULL);
703
        }
704 705 706 707 708 709
        to_free = relay_free (to_free);
    }

    relay = to_start;
    while (relay)
    {
710 711
        if (skip_timer)
            relay->start = 0;
712 713
        check_relay_stream (relay);
        relay = relay->next;
714
    }
Michael Smith's avatar
Michael Smith committed
715 716
}

717 718 719 720 721

static int update_from_master(ice_config_t *config)
{
    char *master = NULL, *password = NULL, *username= NULL;
    int port;
722
    sock_t mastersock;
723
    int ret = 0;
724
    char buf[256];
725 726 727
    do
    {
        char *authheader, *data;
728 729 730
        relay_t *cleanup_relays;
        relay_config_t **new_relays = NULL;
        size_t new_relays_length = 0;
731
        int len, count = 1;
732
        int on_demand;
733
        size_t i;
734

735
        username = strdup(config->master_username);
736
        if (config->master_password)
737
            password = strdup(config->master_password);
Michael Smith's avatar
Michael Smith committed
738

739
        if (config->master_server)
740
            master = strdup(config->master_server);
Michael Smith's avatar
Michael Smith committed
741

742
        port = config->master_server_port;
Michael Smith's avatar
Michael Smith committed
743

744 745
        if (password == NULL || master == NULL || port == 0)
            break;
746
        on_demand = config->on_demand;
747 748
        ret = 1;
        config_release_config();
749
        mastersock = sock_connect_wto(master, port, 10);
750

751 752
        if (mastersock == SOCK_ERROR)
        {
753
            ICECAST_LOG_WARN("Relay slave failed to contact master server to fetch stream list");
754 755
            break;
        }
Michael Smith's avatar
Michael Smith committed
756

757 758 759
        len = strlen(username) + strlen(password) + 2;
        authheader = malloc(len);
        snprintf (authheader, len, "%s:%s", username, password);
760
        data = util_base64_encode(authheader, len);
761 762 763 764 765 766 767
        sock_write (mastersock,
                "GET /admin/streamlist.txt HTTP/1.0\r\n"
                "Authorization: Basic %s\r\n"
                "\r\n", data);
        free(authheader);
        free(data);

768
        if (sock_read_line(mastersock, buf, sizeof(buf)) == 0 ||
769
                ((strncmp (buf, "HTTP/1.0 200", 12) != 0) && (strncmp (buf, "HTTP/1.1 200", 12) != 0)))
770 771
        {
            sock_close (mastersock);
772
            ICECAST_LOG_WARN("Master rejected streamlist request");
773
            break;
774 775
        } else {
            ICECAST_LOG_INFO("Master accepted streamlist request");
776 777
        }

778 779 780 781 782 783 784
        while (sock_read_line(mastersock, buf, sizeof(buf)))
        {
            if (!strlen(buf))
                break;
        }
        while (sock_read_line(mastersock, buf, sizeof(buf)))
        {
785 786 787
            relay_config_t *c = NULL;
            relay_config_t **n;

788 789
            if (!strlen(buf))
                continue;
790
            ICECAST_LOG_DEBUG("read %d from master \"%s\"", count++, buf);
791 792
            xmlURIPtr parsed_uri = xmlParseURI(buf);
            if (parsed_uri == NULL) {
793
                ICECAST_LOG_DEBUG("Error while parsing line from master. Ignoring line.");
794 795
                continue;
            }
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

            n = realloc(new_relays, sizeof(*new_relays)*(new_relays_length + 1));
            if (n) {
                new_relays = n;

                c = calloc(1, sizeof(*c));
                new_relays[new_relays_length++] = c;
            }

            if (c) {
                if (parsed_uri->server != NULL) {
                    c->upstream_default.server = strdup(parsed_uri->server);
                    if (parsed_uri->port == 0) {
                        c->upstream_default.port = 80;
                    } else {
                        c->upstream_default.port = parsed_uri->port;
                    }
                } else {
                    c->upstream_default.server = (char *)xmlCharStrdup (master);
                    c->upstream_default.port = port;
816 817
                }

818 819 820 821 822
                c->upstream_default.mount = strdup(parsed_uri->path);
                c->localmount = strdup(parsed_uri->path);
                c->upstream_default.mp3metadata = 1;
                c->on_demand = on_demand;
                ICECAST_LOG_DEBUG("Added relay host=\"%s\", port=%d, mount=\"%s\"", c->upstream_default.server, c->upstream_default.port, c->upstream_default.mount);
823
            }
824
            xmlFreeURI(parsed_uri);
Michael Smith's avatar
Michael Smith committed
825
        }
826 827
        sock_close (mastersock);

828
        thread_mutex_lock (&(config_locks()->relay_lock));
829
        cleanup_relays = update_relays (&global.master_relays, new_relays, new_relays_length);
830

831
        relay_check_streams (global.master_relays, cleanup_relays, 0);
832 833 834 835 836

        for (i = 0; i < new_relays_length; i++) {
            relay_config_free(new_relays[i]);
        }
        free(new_relays);
837 838 839

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

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    } 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;
856
    unsigned int interval = 0;
Michael Smith's avatar
Michael Smith committed
857

858 859
    (void)arg;

860
    thread_mutex_lock(&_slave_mutex);
861
    update_settings = 0;
862
    update_all_mounts = 0;
863
    thread_mutex_unlock(&_slave_mutex);
864

Karl Heyes's avatar
Karl Heyes committed
865
    config = config_get_config();
866
    stats_global(config);
Karl Heyes's avatar
Karl Heyes committed
867
    config_release_config();
868
    source_recheck_mounts(1);
869

870
    while (1)
871
    {
872
        relay_t *cleanup_relays = NULL;
873
        int skip_timer = 0;
874

875
        /* re-read xml file if requested */
876
        global_lock();
877 878
        if (global.schedule_config_reread) {
            config_reread_config();
879
            global.schedule_config_reread = 0;
880
        }
881
        global_unlock();
882

883
        thread_sleep(1000000);
884 885
        if (slave_running == 0)
            break;
886 887

        ++interval;
888

889
        /* only update relays lists when required */
890
        thread_mutex_lock(&_slave_mutex);
891 892
        if (max_interval <= interval)
        {
893
            ICECAST_LOG_DEBUG("checking master stream list");
894
            config = config_get_config();
Michael Smith's avatar
Michael Smith committed
895

896 897
            if (max_interval == 0)
                skip_timer = 1;
898 899
            interval = 0;
            max_interval = config->master_update_interval;
900
            thread_mutex_unlock(&_slave_mutex);
Michael Smith's avatar
Michael Smith committed
901

902 903 904
            /* the connection could take some time, so the lock can drop */
            if (update_from_master (config))
                config = config_get_config();
905

906
            thread_mutex_lock (&(config_locks()->relay_lock));
907

908
            cleanup_relays = update_relays(&global.relays, config->relay, config->relay_length);
909

910 911 912
            config_release_config();
        }
        else
913 914
        {
            thread_mutex_unlock(&_slave_mutex);
915
            thread_mutex_lock (&(config_locks()->relay_lock));
916
        }
917 918 919 920 921

        relay_check_streams (global.relays, cleanup_relays, skip_timer);
        relay_check_streams (global.master_relays, NULL, skip_timer);
        thread_mutex_unlock (&(config_locks()->relay_lock));

922
        thread_mutex_lock(&_slave_mutex);
923 924
        if (update_settings)
        {
925
            source_recheck_mounts (update_all_mounts);
926
            update_settings = 0;
927
            update_all_mounts = 0;
928
        }
929
        thread_mutex_unlock(&_slave_mutex);
930
    }
931
    ICECAST_LOG_INFO("shutting down current relays");
932 933
    relay_check_streams (NULL, global.relays, 0);
    relay_check_streams (NULL, global.master_relays, 0);
934

935
    ICECAST_LOG_INFO("Slave thread shutdown complete");
936

937
    return NULL;
938
}
Michael Smith's avatar
Michael Smith committed
939