main.c 15.9 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
 *                      Michael Smith <msmith@xiph.org>,
 *                      oddsock <oddsock@xiph.org>,
9
 *                      Karl Heyes <karl@xiph.org>,
10
 *                      and others (see AUTHORS for details).
11
 * Copyright 2011-2018, Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>,
12
 * Copyright 2014,      Thomas B. Ruecker <thomas@ruecker.fi>.
13 14
 */

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

Jack Moffitt's avatar
Jack Moffitt committed
20 21
#include <stdio.h>
#include <string.h>
22 23
#include <errno.h>

24
#ifdef HAVE_CURL
25
#include "curl.h"
26 27
#endif

28
#ifdef WIN32
29
#ifndef _WIN32_WINNT
30
#define _WIN32_WINNT 0x0400
31
#endif
32 33 34 35 36 37
/* For getpid() */
#include <process.h>
#include <windows.h>
#define snprintf _snprintf
#define getpid _getpid
#endif
Jack Moffitt's avatar
Jack Moffitt committed
38

39 40 41 42
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

43 44 45 46
#ifdef HAVE_UNAME
#include <sys/utsname.h>
#endif

Marvin Scholz's avatar
Marvin Scholz committed
47 48 49 50 51
#include "common/thread/thread.h"
#include "common/avl/avl.h"
#include "common/net/sock.h"
#include "common/net/resolver.h"
#include "common/httpp/httpp.h"
Jack Moffitt's avatar
Jack Moffitt committed
52

53
#if HAVE_SYS_TYPES_H
54
#include <sys/types.h>
55 56
#endif
#if HAVE_GRP_H
57
#include <grp.h>
58 59
#endif
#if HAVE_PWD_H
60 61
#include <pwd.h>
#endif
Jack Moffitt's avatar
Jack Moffitt committed
62

63
#include "cfgfile.h"
64
#include "util.h"
Jack Moffitt's avatar
Jack Moffitt committed
65 66 67
#include "sighandler.h"

#include "global.h"
68
#include "compat.h"
Jack Moffitt's avatar
Jack Moffitt committed
69 70 71
#include "connection.h"
#include "refbuf.h"
#include "client.h"
72
#include "slave.h"
Jack Moffitt's avatar
Jack Moffitt committed
73 74
#include "stats.h"
#include "logging.h"
75
#include "xslt.h"
76
#include "fserve.h"
77
#include "yp.h"
78
#include "auth.h"
79
#include "event.h"
Jack Moffitt's avatar
Jack Moffitt committed
80

81 82
#include <libxml/xmlmemory.h>

Jack Moffitt's avatar
Jack Moffitt committed
83 84 85
#undef CATMODULE
#define CATMODULE "main"

86 87 88
static int background;
static char *pidfile = NULL;

89
static void _fatal_error(const char *perr)
90
{
91 92 93
#ifdef WIN32_SERVICE
    MessageBox(NULL, perr, "Error", MB_SERVICE_NOTIFICATION);
#elif defined(WIN32)
94 95 96 97 98 99
    MessageBox(NULL, perr, "Error", MB_OK);
#else
    fprintf(stdout, "%s\n", perr);
#endif
}

100
static void _print_usage(void)
Jack Moffitt's avatar
Jack Moffitt committed
101
{
102
    printf("%s\n\n", ICECAST_VERSION_STRING);
103 104
    printf("usage: icecast [-b] -c <file>\n");
    printf("or   : icecast {-v|--version}\n");
105
    printf("options:\n");
106 107 108
    printf("\t-c <file>       Specify configuration file\n");
    printf("\t-v or --version Display version info\n");
    printf("\t-b              Run icecast in the background\n");
109
    printf("\n");
Jack Moffitt's avatar
Jack Moffitt committed
110 111
}

112 113
static void _stop_logging(void)
{
114 115
    log_close(errorlog);
    log_close(accesslog);
116
    log_close(playlistlog);
117 118
}

119
void initialize_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
120
{
121 122 123 124 125
    log_initialize();
    thread_initialize();
    sock_initialize();
    resolver_initialize();
    config_initialize();
126
    tls_initialize();
127 128 129
    connection_initialize();
    global_initialize();
    refbuf_initialize();
130

131
    xslt_initialize();
132 133
#ifdef HAVE_CURL
    icecast_curl_initialize();
134
#endif
Jack Moffitt's avatar
Jack Moffitt committed
135 136
}

137
void shutdown_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
138
{
139
    event_shutdown();
140
    fserve_shutdown();
141 142
    refbuf_shutdown();
    slave_shutdown();
143
    auth_shutdown();
144
    yp_shutdown();
145
    stats_shutdown();
146

147 148
    global_shutdown();
    connection_shutdown();
149
    tls_shutdown();
150 151 152 153
    config_shutdown();
    resolver_shutdown();
    sock_shutdown();
    thread_shutdown();
154

155
#ifdef HAVE_CURL
156
    icecast_curl_shutdown();
157 158
#endif

159 160
    /* Now that these are done, we can stop the loggers. */
    _stop_logging();
161
    log_shutdown();
162
    xslt_shutdown();
Jack Moffitt's avatar
Jack Moffitt committed
163 164
}

165
static int _parse_config_opts(int argc, char **argv, char *filename, int size)
Jack Moffitt's avatar
Jack Moffitt committed
166
{
167
    int i = 1;
168 169
    int config_ok = 0;

170
    background = 0;
171
    if (argc < 2) return -1;
Jack Moffitt's avatar
Jack Moffitt committed
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    while (i < argc) {
        if (strcmp(argv[i], "-b") == 0) {
#ifndef WIN32
            pid_t pid;
            fprintf(stdout, "Starting icecast2\nDetaching from the console\n");

            pid = fork();

            if (pid > 0) {
                /* exit the parent */
                exit(0);
            }
            else if(pid < 0) {
                fprintf(stderr, "FATAL: Unable to fork child!");
                exit(1);
            }
            background = 1;
#endif
        }
192
        if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
193
            fprintf(stdout, "%s\n", ICECAST_VERSION_STRING);
194 195 196
            exit(0);
        }

197 198 199
        if (strcmp(argv[i], "-c") == 0) {
            if (i + 1 < argc) {
                strncpy(filename, argv[i + 1], size-1);
200
                filename[size-1] = 0;
201
                config_ok = 1;
202 203 204 205
            } else {
                return -1;
            }
        }
206
        i++;
207 208
    }

209 210 211 212
    if(config_ok)
        return 1;
    else
        return -1;
Jack Moffitt's avatar
Jack Moffitt committed
213 214
}

215 216 217 218 219
static int _start_logging_stdout(void) {
    errorlog = log_open_file(stderr);
    if ( errorlog < 0 )
        return 0;

220
    log_set_level(errorlog, ICECAST_LOGLEVEL_WARN);
221 222 223 224

    return 1;
}

225
static int _start_logging(void)
Jack Moffitt's avatar
Jack Moffitt committed
226
{
227 228
    char fn_error[FILENAME_MAX];
    char fn_access[FILENAME_MAX];
229
    char fn_playlist[FILENAME_MAX];
230
    char buf[1024];
231
    int log_to_stderr;
232

233
    ice_config_t *config = config_get_config_unlocked();
Jack Moffitt's avatar
Jack Moffitt committed
234

235 236 237
    if(strcmp(config->error_log, "-") == 0) {
        /* this is already in place because of _start_logging_stdout() */
    } else {
238
        snprintf(fn_error, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->error_log);
239
        errorlog = log_open(fn_error);
240
        log_to_stderr = 0;
241 242 243
        if (config->logsize)
            log_set_trigger (errorlog, config->logsize);
        log_set_archive_timestamp(errorlog, config->logarchive);
244
    }
245 246 247

    if (errorlog < 0) {
        buf[sizeof(buf)-1] = 0;
248
        snprintf(buf, sizeof(buf)-1,
249 250
                "FATAL: could not open error logging (%s): %s",
                log_to_stderr?"standard error":fn_error,
251 252 253 254 255
                strerror(errno));
        _fatal_error(buf);
    }
    log_set_level(errorlog, config->loglevel);

256 257 258 259
    if(strcmp(config->access_log, "-") == 0) {
        accesslog = log_open_file(stderr);
        log_to_stderr = 1;
    } else {
260
        snprintf(fn_access, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->access_log);
261
        accesslog = log_open(fn_access);
262
        log_to_stderr = 0;
263 264 265
        if (config->logsize)
            log_set_trigger (accesslog, config->logsize);
        log_set_archive_timestamp(accesslog, config->logarchive);
266
    }
267 268 269

    if (accesslog < 0) {
        buf[sizeof(buf)-1] = 0;
270 271 272 273
        snprintf(buf, sizeof(buf) - 1,
            "FATAL: could not open access logging (%s): %s",
            log_to_stderr ? "standard error" : fn_access,
            strerror(errno));
274 275
        _fatal_error(buf);
    }
276 277 278 279 280 281

    if(config->playlist_log) {
        snprintf(fn_playlist, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->playlist_log);
        playlistlog = log_open(fn_playlist);
        if (playlistlog < 0) {
            buf[sizeof(buf)-1] = 0;
282
            snprintf(buf, sizeof(buf)-1,
283 284 285 286 287 288
                "FATAL: could not open playlist logging (%s): %s",
                log_to_stderr?"standard error":fn_playlist,
                strerror(errno));
            _fatal_error(buf);
        }
        log_to_stderr = 0;
289 290 291
        if (config->logsize)
            log_set_trigger (playlistlog, config->logsize);
        log_set_archive_timestamp(playlistlog, config->logarchive);
292 293 294
    } else {
        playlistlog = -1;
    }
295

296 297
    log_set_level(errorlog, config->loglevel);
    log_set_level(accesslog, 4);
298
    log_set_level(playlistlog, 4);
299 300

    if (errorlog >= 0 && accesslog >= 0) return 1;
301

302
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
303 304 305
}


306
static int _start_listening(void)
Jack Moffitt's avatar
Jack Moffitt committed
307
{
308 309
    int i;
    for(i=0; i < global.server_sockets; i++) {
310
        if (sock_listen(global.serversock[i], ICECAST_LISTEN_QUEUE) == SOCK_ERROR)
311
            return 0;
Jack Moffitt's avatar
Jack Moffitt committed
312

313
        sock_set_blocking(global.serversock[i], 0);
314
    }
Jack Moffitt's avatar
Jack Moffitt committed
315

316
    return 1;
Jack Moffitt's avatar
Jack Moffitt committed
317 318
}

319
/* bind the socket and start listening */
320
static int _server_proc_init(void)
Jack Moffitt's avatar
Jack Moffitt committed
321
{
322
    ice_config_t *config = config_get_config_unlocked();
323

324
    if (connection_setup_sockets (config) < 1)
325
        return 0;
Jack Moffitt's avatar
Jack Moffitt committed
326

327
    if (!_start_listening()) {
328
        _fatal_error("Failed trying to listen on server socket");
329 330
        return 0;
    }
331

332 333 334 335 336 337 338 339 340 341 342 343
    /* recreate the pid file */
    if (config->pidfile)
    {
        FILE *f;
        pidfile = strdup (config->pidfile);
        if (pidfile && (f = fopen (config->pidfile, "w")) != NULL)
        {
            fprintf (f, "%d\n", (int)getpid());
            fclose (f);
        }
    }

344
    return 1;
345
}
Jack Moffitt's avatar
Jack Moffitt committed
346

347 348 349
/* this is the heart of the beast */
static void _server_proc(void)
{
350 351 352 353 354 355
    if (background)
    {
        fclose (stdin);
        fclose (stdout);
        fclose (stderr);
    }
356
    connection_accept_loop();
Jack Moffitt's avatar
Jack Moffitt committed
357

358
    connection_setup_sockets (NULL);
Jack Moffitt's avatar
Jack Moffitt committed
359 360
}

361
/* chroot the process. Watch out - we need to do this before starting other
362
 * threads. Change uid as well, after figuring out uid _first_ */
363
#if defined(HAVE_SETUID) || defined(HAVE_CHROOT) || defined(HAVE_SETUID)
Michael Smith's avatar
Michael Smith committed
364
static void _ch_root_uid_setup(void)
365
{
Michael Smith's avatar
Michael Smith committed
366
   ice_config_t *conf = config_get_config_unlocked();
367
#ifdef HAVE_SETUID
368 369 370 371 372 373 374
   struct passwd *user;
   struct group *group;
   uid_t uid=-1;
   gid_t gid=-1;

   if(conf->chuid)
   {
375 376 377 378 379 380 381 382 383
       if(conf->user) {
           user = getpwnam(conf->user);
           if(user)
               uid = user->pw_uid;
           else
               fprintf(stderr, "Couldn't find user \"%s\" in password file\n", conf->user);
       }
       if(conf->group) {
           group = getgrnam(conf->group);
384

385 386 387 388 389
           if(group)
               gid = group->gr_gid;
           else
               fprintf(stderr, "Couldn't find group \"%s\" in groups file\n", conf->group);
       }
390 391 392
   }
#endif

393
#if HAVE_CHROOT
394 395 396 397 398 399
   if (conf->chroot)
   {
       if(getuid()) /* root check */
       {
           fprintf(stderr, "WARNING: Cannot change server root unless running as root.\n");
       }
400
       if(chroot(conf->base_dir) == -1 || chdir("/") == -1)
401 402 403 404 405 406 407
       {
           fprintf(stderr,"WARNING: Couldn't change server root: %s\n", strerror(errno));
           return;
       }
       else
           fprintf(stdout, "Changed root successfully to \"%s\".\n", conf->base_dir);

408
   }
409
#endif
410

411
#if HAVE_SETUID
412 413 414 415 416 417 418 419
   if(conf->chuid)
   {
       if(getuid()) /* root check */
       {
           fprintf(stderr, "WARNING: Can't change user id unless you are root.\n");
           return;
       }

420
       if(uid != (uid_t)-1 && gid != (gid_t)-1) {
421 422 423 424 425
#ifdef HAVE_SETRESGID
           if(!setresgid(gid, gid, gid)) {
#else
           if(!setgid(gid)) {
#endif
426
               fprintf(stdout, "Changed groupid to %i.\n", (int)gid);
427
           } else {
428
               fprintf(stdout, "Error changing groupid: %s.\n", strerror(errno));
429
           }
430 431
           if(!initgroups(conf->user, gid))
               fprintf(stdout, "Changed supplementary groups based on user: %s.\n", conf->user);
432
           else
433
               fprintf(stdout, "Error changing supplementary groups: %s.\n", strerror(errno));
434 435 436 437 438
#ifdef HAVE_SETRESUID
           if(!setresuid(uid, uid, uid)) {
#else
           if(!setuid(uid)) {
#endif
439
               fprintf(stdout, "Changed userid to %i.\n", (int)uid);
440
           } else {
441
               fprintf(stdout, "Error changing userid: %s.\n", strerror(errno));
442
           }
443
       }
444 445
   }
#endif
446
}
447
#endif
Philipp Schafft's avatar
Philipp Schafft committed
448

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
static inline void __log_system_name(void) {
    char hostname[80] = "(unknown)";
    char system[128] = "(unknown)";
    int have_hostname = 0;
#ifdef HAVE_UNAME
    struct utsname utsname;
#endif
    ice_config_t *config;

#ifdef HAVE_GETHOSTNAME
    if (gethostname(hostname, sizeof(hostname)) != 0) {
        strncpy(hostname, "(unknown)", sizeof(hostname));
    } else {
        have_hostname = 1;
    }
#endif
#ifdef HAVE_UNAME
    if(uname(&utsname) == 0) {
        snprintf(system, sizeof(system), "%s %s, %s, %s, %s",
                 utsname.sysname, utsname.release, utsname.nodename, utsname.version, utsname.machine);
        if (!have_hostname) {
            strncpy(hostname, utsname.nodename, sizeof(hostname));
            have_hostname = 1;
        }
    }
#elif defined(WIN32)
    strncpy(system, "MS Windows", sizeof(system));
#endif

   ICECAST_LOG_INFO("Running on %s; OS: %s; Address Bits: %i", hostname, system, sizeof(void*)*8);

   if (have_hostname) {
       config = config_get_config();
       if (!config->sane_hostname && util_hostcheck(hostname) == HOSTCHECK_SANE) {
           ICECAST_LOG_WARN("Hostname is not set to anything useful in <hostname>, Consider setting it to the system's name \"%s\".", hostname);
       }
       config_release_config();
   }
}

489
#ifdef WIN32_SERVICE
Philipp Schafft's avatar
Philipp Schafft committed
490 491 492 493
int mainService(int argc, char **argv)
#else
int main(int argc, char **argv)
#endif
Jack Moffitt's avatar
Jack Moffitt committed
494
{
495 496
    int res, ret;
    char filename[512];
497
    char pbuf[1024];
498 499 500 501

    /* parse the '-c icecast.xml' option
    ** only, so that we can read a configfile
    */
502
    res = _parse_config_opts(argc, argv, filename, sizeof(filename));
503
    if (res == 1) {
504
#if !defined(_WIN32) || defined(_CONSOLE) || defined(__MINGW32__) || defined(__MINGW64__)
505
        /* startup all the modules */
506
        initialize_subsystems();
507 508 509 510 511
        if (!_start_logging_stdout()) {
            _fatal_error("FATAL: Could not start logging on stderr.");
            shutdown_subsystems();
            return 1;
        }
512
#endif
513
        /* parse the config file */
Michael Smith's avatar
Michael Smith committed
514
        config_get_config();
515
        ret = config_initial_parse_file(filename);
Michael Smith's avatar
Michael Smith committed
516
        config_release_config();
517
        if (ret < 0) {
518
            memset(pbuf, '\000', sizeof(pbuf));
519
            snprintf(pbuf, sizeof(pbuf)-1,
520 521
                "FATAL: error parsing config file (%s)", filename);
            _fatal_error(pbuf);
522 523
            switch (ret) {
            case CONFIG_EINSANE:
524
                _fatal_error("filename was null or blank");
525 526
                break;
            case CONFIG_ENOROOT:
527
                _fatal_error("no root element found");
528 529
                break;
            case CONFIG_EBADROOT:
530
                _fatal_error("root element is not <icecast>");
531 532
                break;
            default:
533
                _fatal_error("XML config parsing error");
534 535
                break;
            }
536
#if !defined(_WIN32) || defined(_CONSOLE) || defined(__MINGW32__) || defined(__MINGW64__)
537 538
            shutdown_subsystems();
#endif
539
            return 1;
540 541 542 543 544
        }
    } else if (res == -1) {
        _print_usage();
        return 1;
    }
545

546 547
    /* override config file options with commandline options */
    config_parse_cmdline(argc, argv);
Jack Moffitt's avatar
Jack Moffitt committed
548

549 550
    /* Bind socket, before we change userid */
    if(!_server_proc_init()) {
551
        _fatal_error("Server startup failed. Exiting");
552
        shutdown_subsystems();
553 554
        return 1;
    }
555

556
#if defined(HAVE_SETUID) || defined(HAVE_CHROOT) || defined(HAVE_SETUID)
Michael Smith's avatar
Michael Smith committed
557
    _ch_root_uid_setup(); /* Change user id and root if requested/possible */
558
#endif
559 560

    stats_initialize(); /* We have to do this later on because of threading */
561
    fserve_initialize(); /* This too */
562

563
#ifdef HAVE_SETUID
564 565
    /* We'll only have getuid() if we also have setuid(), it's reasonable to
     * assume */
566
    if(!getuid() && getpid() != 1) /* Running as root! Don't allow this */
567
    {
568
        fprintf(stderr, "ERROR: You should not run icecast2 as root\n");
569
        fprintf(stderr, "Use the changeowner directive in the config file\n");
570
        shutdown_subsystems();
571 572 573 574 575 576 577
        return 1;
    }
#endif

    /* setup default signal handlers */
    sighandler_initialize();

578
    if (!_start_logging()) {
579
        _fatal_error("FATAL: Could not start logging");
580
        shutdown_subsystems();
581 582
        return 1;
    }
Jack Moffitt's avatar
Jack Moffitt committed
583

584
    ICECAST_LOG_INFO("%s server started", ICECAST_VERSION_STRING);
585
    ICECAST_LOG_INFO("Server's PID is %lli", (long long int)getpid());
586
    __log_system_name();
Jack Moffitt's avatar
Jack Moffitt committed
587

588
    /* REM 3D Graphics */
Jack Moffitt's avatar
Jack Moffitt committed
589

590
    /* let her rip */
591
    global.running = ICECAST_RUNNING;
592 593 594 595

    /* Startup yp thread */
    yp_initialize();

596 597
    /* Do this after logging init */
    slave_initialize();
598
    auth_initialise ();
599
    event_initialise();
600

601
    event_emit_global("icecast-start");
602
    _server_proc();
603
    event_emit_global("icecast-stop");
Jack Moffitt's avatar
Jack Moffitt committed
604

605
    ICECAST_LOG_INFO("Shutting down");
606
#if !defined(_WIN32) || defined(_CONSOLE) || defined(__MINGW32__) || defined(__MINGW64__)
607 608
    shutdown_subsystems();
#endif
609 610 611 612 613 614
    if (pidfile)
    {
        remove (pidfile);
        free (pidfile);
    }

615
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
616 617 618
}