main.c 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* 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).
Philipp Schafft's avatar
Philipp Schafft committed
11
 * Copyright 2011-2012, Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>,
12 13
 */

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

Jack Moffitt's avatar
Jack Moffitt committed
19 20
#include <stdio.h>
#include <string.h>
21 22 23 24 25 26 27 28 29 30
#include <errno.h>

#ifdef WIN32
#define _WIN32_WINNT 0x0400
/* For getpid() */
#include <process.h>
#include <windows.h>
#define snprintf _snprintf
#define getpid _getpid
#endif
Jack Moffitt's avatar
Jack Moffitt committed
31

32 33 34
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
35 36 37
#ifdef HAVE_CURL
#include <curl/curl.h>
#endif
38

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

45
#if HAVE_SYS_TYPES_H
46
#include <sys/types.h>
47 48
#endif
#if HAVE_GRP_H
49
#include <grp.h>
50 51
#endif
#if HAVE_PWD_H
52 53
#include <pwd.h>
#endif
Jack Moffitt's avatar
Jack Moffitt committed
54

55
#include "cfgfile.h"
Jack Moffitt's avatar
Jack Moffitt committed
56 57 58
#include "sighandler.h"

#include "global.h"
59
#include "compat.h"
Jack Moffitt's avatar
Jack Moffitt committed
60 61 62
#include "connection.h"
#include "refbuf.h"
#include "client.h"
63
#include "slave.h"
Jack Moffitt's avatar
Jack Moffitt committed
64 65
#include "stats.h"
#include "logging.h"
66
#include "xslt.h"
67
#include "fserve.h"
68
#include "yp.h"
69
#include "auth.h"
Jack Moffitt's avatar
Jack Moffitt committed
70

71 72
#include <libxml/xmlmemory.h>

Jack Moffitt's avatar
Jack Moffitt committed
73 74 75
#undef CATMODULE
#define CATMODULE "main"

76 77 78
static int background;
static char *pidfile = NULL;

79 80
static void _fatal_error(char *perr)
{
81 82 83
#ifdef WIN32_SERVICE
    MessageBox(NULL, perr, "Error", MB_SERVICE_NOTIFICATION);
#elif defined(WIN32)
84 85 86 87 88 89
    MessageBox(NULL, perr, "Error", MB_OK);
#else
    fprintf(stdout, "%s\n", perr);
#endif
}

90
static void _print_usage(void)
Jack Moffitt's avatar
Jack Moffitt committed
91
{
92
    printf("%s\n\n", ICECAST_VERSION_STRING);
93 94
    printf("usage: icecast [-b] -c <file>\n");
    printf("or   : icecast {-v|--version}\n");
95
    printf("options:\n");
96 97 98
    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");
99
    printf("\n");
Jack Moffitt's avatar
Jack Moffitt committed
100 101
}

102 103
static void _stop_logging(void)
{
104 105
    log_close(errorlog);
    log_close(accesslog);
106
    log_close(playlistlog);
107 108
}

109
void initialize_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
110
{
111 112 113 114 115 116 117 118
    log_initialize();
    thread_initialize();
    sock_initialize();
    resolver_initialize();
    config_initialize();
    connection_initialize();
    global_initialize();
    refbuf_initialize();
119

120
    xslt_initialize();
121
#ifdef HAVE_CURL_GLOBAL_INIT
122 123
    curl_global_init (CURL_GLOBAL_ALL);
#endif
Jack Moffitt's avatar
Jack Moffitt committed
124 125
}

126
void shutdown_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
127
{
128
    fserve_shutdown();
129 130
    refbuf_shutdown();
    slave_shutdown();
131
    auth_shutdown();
132
    yp_shutdown();
133
    stats_shutdown();
134

135 136 137 138 139 140
    global_shutdown();
    connection_shutdown();
    config_shutdown();
    resolver_shutdown();
    sock_shutdown();
    thread_shutdown();
141

142 143 144 145
#ifdef HAVE_CURL
    curl_global_cleanup();
#endif

146 147
    /* Now that these are done, we can stop the loggers. */
    _stop_logging();
148
    log_shutdown();
149
    xslt_shutdown();
Jack Moffitt's avatar
Jack Moffitt committed
150 151
}

152
static int _parse_config_opts(int argc, char **argv, char *filename, int size)
Jack Moffitt's avatar
Jack Moffitt committed
153
{
154
    int i = 1;
155 156
    int config_ok = 0;

157
    background = 0;
158
    if (argc < 2) return -1;
Jack Moffitt's avatar
Jack Moffitt committed
159

160 161
    while (i < argc) {
        if (strcmp(argv[i], "-b") == 0) {
162
#ifndef WIN32
Michael Smith's avatar
Michael Smith committed
163
            pid_t pid;
164
            fprintf(stdout, "Starting icecast2\nDetaching from the console\n");
Michael Smith's avatar
Michael Smith committed
165 166 167 168

            pid = fork();

            if (pid > 0) {
169
                /* exit the parent */
170 171
                exit(0);
            }
Michael Smith's avatar
Michael Smith committed
172
            else if(pid < 0) {
173 174
                fprintf(stderr, "FATAL: Unable to fork child!");
                exit(1);
175
            }
176
            background = 1;
177
#endif
178
        }
179
        if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
180
            fprintf(stdout, "%s\n", ICECAST_VERSION_STRING);
181 182 183
            exit(0);
        }

184 185 186
        if (strcmp(argv[i], "-c") == 0) {
            if (i + 1 < argc) {
                strncpy(filename, argv[i + 1], size-1);
187
                filename[size-1] = 0;
188
                config_ok = 1;
189 190 191 192 193 194 195
            } else {
                return -1;
            }
        }
        i++;
    }

196 197 198 199
    if(config_ok)
        return 1;
    else
        return -1;
Jack Moffitt's avatar
Jack Moffitt committed
200 201
}

202
static int _start_logging(void)
Jack Moffitt's avatar
Jack Moffitt committed
203
{
204 205
    char fn_error[FILENAME_MAX];
    char fn_access[FILENAME_MAX];
206
    char fn_playlist[FILENAME_MAX];
207
    char buf[1024];
208
    int log_to_stderr;
209

210
    ice_config_t *config = config_get_config_unlocked();
Jack Moffitt's avatar
Jack Moffitt committed
211

212
    if(strcmp(config->error_log, "-")) {
213
        snprintf(fn_error, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->error_log);
214
        errorlog = log_open(fn_error);
215
        log_to_stderr = 0;
216 217 218
        if (config->logsize)
            log_set_trigger (errorlog, config->logsize);
        log_set_archive_timestamp(errorlog, config->logarchive);
219 220
    } else {
        errorlog = log_open_file(stderr);
221
        log_to_stderr = 1;
222
    }
223 224 225

    if (errorlog < 0) {
        buf[sizeof(buf)-1] = 0;
226 227 228
        snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open error logging (%s): %s",
                log_to_stderr?"standard error":fn_error,
229 230 231 232 233
                strerror(errno));
        _fatal_error(buf);
    }
    log_set_level(errorlog, config->loglevel);

234
    if(strcmp(config->access_log, "-")) {
235
        snprintf(fn_access, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->access_log);
236
        accesslog = log_open(fn_access);
237
        log_to_stderr = 0;
238 239 240
        if (config->logsize)
            log_set_trigger (accesslog, config->logsize);
        log_set_archive_timestamp(accesslog, config->logarchive);
241 242
    } else {
        accesslog = log_open_file(stderr);
243
        log_to_stderr = 1;
244
    }
245 246 247

    if (accesslog < 0) {
        buf[sizeof(buf)-1] = 0;
248 249 250
        snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open access logging (%s): %s",
                log_to_stderr?"standard error":fn_access,
251 252 253
                strerror(errno));
        _fatal_error(buf);
    }
254 255 256 257 258 259 260 261 262 263 264 265 266

    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;
            snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open playlist logging (%s): %s",
                log_to_stderr?"standard error":fn_playlist,
                strerror(errno));
            _fatal_error(buf);
        }
        log_to_stderr = 0;
267 268 269
        if (config->logsize)
            log_set_trigger (playlistlog, config->logsize);
        log_set_archive_timestamp(playlistlog, config->logarchive);
270 271 272
    } else {
        playlistlog = -1;
    }
273

274 275
    log_set_level(errorlog, config->loglevel);
    log_set_level(accesslog, 4);
276
    log_set_level(playlistlog, 4);
277 278 279 280

    if (errorlog >= 0 && accesslog >= 0) return 1;
    
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
281 282 283
}


284
static int _start_listening(void)
Jack Moffitt's avatar
Jack Moffitt committed
285
{
286 287
    int i;
    for(i=0; i < global.server_sockets; i++) {
288 289
        if (sock_listen(global.serversock[i], ICE_LISTEN_QUEUE) == SOCK_ERROR)
            return 0;
Jack Moffitt's avatar
Jack Moffitt committed
290

291
        sock_set_blocking(global.serversock[i], 0);
292
    }
Jack Moffitt's avatar
Jack Moffitt committed
293

294
    return 1;
Jack Moffitt's avatar
Jack Moffitt committed
295 296
}

297
/* bind the socket and start listening */
298
static int _server_proc_init(void)
Jack Moffitt's avatar
Jack Moffitt committed
299
{
300
    ice_config_t *config = config_get_config_unlocked();
301

302
    if (connection_setup_sockets (config) < 1)
303
        return 0;
Jack Moffitt's avatar
Jack Moffitt committed
304

305
    if (!_start_listening()) {
306
        _fatal_error("Failed trying to listen on server socket");
307 308
        return 0;
    }
309

310 311 312 313 314 315 316 317 318 319 320 321
    /* 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);
        }
    }

322
    return 1;
323
}
Jack Moffitt's avatar
Jack Moffitt committed
324

325 326 327
/* this is the heart of the beast */
static void _server_proc(void)
{
328 329 330 331 332 333
    if (background)
    {
        fclose (stdin);
        fclose (stdout);
        fclose (stderr);
    }
334
    connection_accept_loop();
Jack Moffitt's avatar
Jack Moffitt committed
335

336
    connection_setup_sockets (NULL);
Jack Moffitt's avatar
Jack Moffitt committed
337 338
}

339
/* chroot the process. Watch out - we need to do this before starting other
340
 * threads. Change uid as well, after figuring out uid _first_ */
341

Michael Smith's avatar
Michael Smith committed
342
static void _ch_root_uid_setup(void)
343
{
Michael Smith's avatar
Michael Smith committed
344
   ice_config_t *conf = config_get_config_unlocked();
345
#ifdef HAVE_SETUID
346 347 348 349 350 351 352
   struct passwd *user;
   struct group *group;
   uid_t uid=-1;
   gid_t gid=-1;

   if(conf->chuid)
   {
353 354 355 356 357 358 359 360 361
       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);
362

363 364 365 366 367
           if(group)
               gid = group->gr_gid;
           else
               fprintf(stderr, "Couldn't find group \"%s\" in groups file\n", conf->group);
       }
368 369 370
   }
#endif

371
#if HAVE_CHROOT
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
   if (conf->chroot)
   {
       if(getuid()) /* root check */
       {
           fprintf(stderr, "WARNING: Cannot change server root unless running as root.\n");
           return;
       }
       if(chroot(conf->base_dir))
       {
           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);

   }   
#endif
389
#if HAVE_SETUID
390

391 392 393 394 395 396 397 398
   if(conf->chuid)
   {
       if(getuid()) /* root check */
       {
           fprintf(stderr, "WARNING: Can't change user id unless you are root.\n");
           return;
       }

399
       if(gid != (gid_t)-1) {
400
           if(!setgid(gid))
401
               fprintf(stdout, "Changed groupid to %i.\n", (int)gid);
402 403 404
           else
               fprintf(stdout, "Error changing groupid: %s.\n", strerror(errno));
       }
405

406
       if(uid != (uid_t)-1) {
407
           if(!setuid(uid))
408
               fprintf(stdout, "Changed userid to %i.\n", (int)uid);
409 410 411
           else
               fprintf(stdout, "Error changing userid: %s.\n", strerror(errno));
       }
412 413
   }
#endif
414
}
Philipp Schafft's avatar
Philipp Schafft committed
415

416
#ifdef WIN32_SERVICE
Philipp Schafft's avatar
Philipp Schafft committed
417 418 419 420
int mainService(int argc, char **argv)
#else
int main(int argc, char **argv)
#endif
Jack Moffitt's avatar
Jack Moffitt committed
421
{
422 423
    int res, ret;
    char filename[512];
424
    char pbuf[1024];
425 426 427 428

    /* parse the '-c icecast.xml' option
    ** only, so that we can read a configfile
    */
429
    res = _parse_config_opts(argc, argv, filename, 512);
430
    if (res == 1) {
431
#if !defined(_WIN32) || defined(_CONSOLE) || defined(__MINGW32__) || defined(__MINGW64__)
432
        /* startup all the modules */
433 434
        initialize_subsystems();
#endif
435
        /* parse the config file */
Michael Smith's avatar
Michael Smith committed
436
        config_get_config();
437
        ret = config_initial_parse_file(filename);
Michael Smith's avatar
Michael Smith committed
438
        config_release_config();
439
        if (ret < 0) {
440 441 442 443
            memset(pbuf, '\000', sizeof(pbuf));
            snprintf(pbuf, sizeof(pbuf)-1, 
                "FATAL: error parsing config file (%s)", filename);
            _fatal_error(pbuf);
444 445
            switch (ret) {
            case CONFIG_EINSANE:
446
                _fatal_error("filename was null or blank");
447 448
                break;
            case CONFIG_ENOROOT:
449
                _fatal_error("no root element found");
450 451
                break;
            case CONFIG_EBADROOT:
452
                _fatal_error("root element is not <icecast>");
453 454
                break;
            default:
455
                _fatal_error("XML config parsing error");
456 457
                break;
            }
458
#if !defined(_WIN32) || defined(_CONSOLE) || defined(__MINGW32__) || defined(__MINGW64__)
459 460
            shutdown_subsystems();
#endif
461
            return 1;
462 463 464 465 466 467 468 469
        }
    } else if (res == -1) {
        _print_usage();
        return 1;
    }
    
    /* override config file options with commandline options */
    config_parse_cmdline(argc, argv);
Jack Moffitt's avatar
Jack Moffitt committed
470

471 472
    /* Bind socket, before we change userid */
    if(!_server_proc_init()) {
473
        _fatal_error("Server startup failed. Exiting");
474
        shutdown_subsystems();
475 476
        return 1;
    }
477

Michael Smith's avatar
Michael Smith committed
478
    _ch_root_uid_setup(); /* Change user id and root if requested/possible */
479 480

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

483
#ifdef HAVE_SETUID 
484 485 486 487
    /* We'll only have getuid() if we also have setuid(), it's reasonable to
     * assume */
    if(!getuid()) /* Running as root! Don't allow this */
    {
488
        fprintf(stderr, "ERROR: You should not run icecast2 as root\n");
489
        fprintf(stderr, "Use the changeowner directive in the config file\n");
490
        shutdown_subsystems();
491 492 493 494 495 496 497
        return 1;
    }
#endif

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

498
    if (!_start_logging()) {
499
        _fatal_error("FATAL: Could not start logging");
500
        shutdown_subsystems();
501 502
        return 1;
    }
Jack Moffitt's avatar
Jack Moffitt committed
503

504
    INFO1 ("%s server started", ICECAST_VERSION_STRING);
Jack Moffitt's avatar
Jack Moffitt committed
505

506
    /* REM 3D Graphics */
Jack Moffitt's avatar
Jack Moffitt committed
507

508 509
    /* let her rip */
    global.running = ICE_RUNNING;
510 511 512 513

    /* Startup yp thread */
    yp_initialize();

514 515
    /* Do this after logging init */
    slave_initialize();
516
    auth_initialise ();
517

518
    _server_proc();
Jack Moffitt's avatar
Jack Moffitt committed
519

520
    INFO0("Shutting down");
521
#if !defined(_WIN32) || defined(_CONSOLE) || defined(__MINGW32__) || defined(__MINGW64__)
522 523
    shutdown_subsystems();
#endif
524 525 526 527 528 529
    if (pidfile)
    {
        remove (pidfile);
        free (pidfile);
    }

530
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
531 532 533
}