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

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

Jack Moffitt's avatar
Jack Moffitt committed
18 19 20
#include <stdio.h>
#include <string.h>

21 22 23
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
24 25 26
#ifdef HAVE_CURL
#include <curl/curl.h>
#endif
27

Karl Heyes's avatar
Karl Heyes committed
28 29 30 31 32
#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
33

34 35 36 37 38 39
#ifdef CHUID
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
#include <errno.h>
#endif
Jack Moffitt's avatar
Jack Moffitt committed
40

41
#include "cfgfile.h"
Jack Moffitt's avatar
Jack Moffitt committed
42 43 44
#include "sighandler.h"

#include "global.h"
45
#include "compat.h"
Jack Moffitt's avatar
Jack Moffitt committed
46 47 48
#include "connection.h"
#include "refbuf.h"
#include "client.h"
49
#include "slave.h"
Jack Moffitt's avatar
Jack Moffitt committed
50 51
#include "stats.h"
#include "logging.h"
52
#include "xslt.h"
53
#include "fserve.h"
54
#include "yp.h"
55
#include "auth.h"
Jack Moffitt's avatar
Jack Moffitt committed
56

57 58
#include <libxml/xmlmemory.h>

59
#ifdef _WIN32
60 61
/* For getpid() */
#include <process.h>
Karl Heyes's avatar
Karl Heyes committed
62
#include <windows.h>
63
#define snprintf _snprintf
64
#define getpid _getpid
65
#endif
66

Jack Moffitt's avatar
Jack Moffitt committed
67 68 69
#undef CATMODULE
#define CATMODULE "main"

70 71 72
static int background;
static char *pidfile = NULL;

73 74 75 76 77 78 79 80 81
static void _fatal_error(char *perr)
{
#ifdef WIN32
    MessageBox(NULL, perr, "Error", MB_OK);
#else
    fprintf(stdout, "%s\n", perr);
#endif
}

82
static void _print_usage(void)
Jack Moffitt's avatar
Jack Moffitt committed
83
{
84
    printf("%s\n\n", ICECAST_VERSION_STRING);
85
    printf("usage: icecast [-b -v] -c <file>\n");
86
    printf("options:\n");
87 88 89
    printf("\t-c <file>\tSpecify configuration file\n");
    printf("\t-v\t\tDisplay version info\n");
    printf("\t-b\t\tRun icecast in the background\n");
90
    printf("\n");
Jack Moffitt's avatar
Jack Moffitt committed
91 92
}

93 94
static void _stop_logging(void)
{
95 96
    log_close(errorlog);
    log_close(accesslog);
97
    log_close(playlistlog);
98 99
}

100
static void _initialize_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
101
{
102 103 104 105 106 107 108 109
    log_initialize();
    thread_initialize();
    sock_initialize();
    resolver_initialize();
    config_initialize();
    connection_initialize();
    global_initialize();
    refbuf_initialize();
110 111
#if !defined(WIN32) || defined(WIN32_SERVICE)
    /* win32 GUI needs to do the initialise before here */
112
    xslt_initialize();
113
#ifdef HAVE_CURL_GLOBAL_INIT
114 115
    curl_global_init (CURL_GLOBAL_ALL);
#endif
116
#endif
Jack Moffitt's avatar
Jack Moffitt committed
117 118
}

119
static void _shutdown_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
120
{
121
    fserve_shutdown();
122 123 124
#if !defined(WIN32) || defined(WIN32_SERVICE)
    /* If we do the following cleanup on the win32 GUI then the app will crash when libxml2 is
     * initialised again as the process doesn't terminate */
125
    xslt_shutdown();
126
#endif
127 128
    refbuf_shutdown();
    slave_shutdown();
129
    auth_shutdown();
130
    yp_shutdown();
131
    stats_shutdown();
132

133 134 135 136 137 138
    global_shutdown();
    connection_shutdown();
    config_shutdown();
    resolver_shutdown();
    sock_shutdown();
    thread_shutdown();
139

140 141 142 143
#ifdef HAVE_CURL
    curl_global_cleanup();
#endif

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

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

154
    background = 0;
155
    if (argc < 2) return -1;
Jack Moffitt's avatar
Jack Moffitt committed
156

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

            pid = fork();

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

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

193 194 195 196
    if(config_ok)
        return 1;
    else
        return -1;
Jack Moffitt's avatar
Jack Moffitt committed
197 198
}

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

207
    ice_config_t *config = config_get_config_unlocked();
Jack Moffitt's avatar
Jack Moffitt committed
208

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

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

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

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

    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;
264 265 266
        if (config->logsize)
            log_set_trigger (playlistlog, config->logsize);
        log_set_archive_timestamp(playlistlog, config->logarchive);
267 268 269
    } else {
        playlistlog = -1;
    }
270

271 272
    log_set_level(errorlog, config->loglevel);
    log_set_level(accesslog, 4);
273
    log_set_level(playlistlog, 4);
274 275 276 277

    if (errorlog >= 0 && accesslog >= 0) return 1;
    
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
278 279 280
}


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

288
        sock_set_blocking(global.serversock[i], 0);
289
    }
Jack Moffitt's avatar
Jack Moffitt committed
290

291
    return 1;
Jack Moffitt's avatar
Jack Moffitt committed
292 293
}

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

299
    if (connection_setup_sockets (config) < 1)
300
        return 0;
Jack Moffitt's avatar
Jack Moffitt committed
301

302
    if (!_start_listening()) {
303
        _fatal_error("Failed trying to listen on server socket");
304 305
        return 0;
    }
306

307 308 309 310 311 312 313 314 315 316 317 318
    /* 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);
        }
    }

319
    return 1;
320
}
Jack Moffitt's avatar
Jack Moffitt committed
321

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

333
    connection_setup_sockets (NULL);
Jack Moffitt's avatar
Jack Moffitt committed
334 335
}

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

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

   if(conf->chuid)
   {
350 351 352 353 354 355 356 357 358
       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);
359

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

#ifdef CHROOT
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
   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
#ifdef CHUID
387

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

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

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

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

    /* parse the '-c icecast.xml' option
    ** only, so that we can read a configfile
    */
426
    res = _parse_config_opts(argc, argv, filename, 512);
427 428 429 430 431
    if (res == 1) {
        /* startup all the modules */
        _initialize_subsystems();

        /* parse the config file */
Michael Smith's avatar
Michael Smith committed
432
        config_get_config();
433
        ret = config_initial_parse_file(filename);
Michael Smith's avatar
Michael Smith committed
434
        config_release_config();
435
        if (ret < 0) {
436 437 438 439
            memset(pbuf, '\000', sizeof(pbuf));
            snprintf(pbuf, sizeof(pbuf)-1, 
                "FATAL: error parsing config file (%s)", filename);
            _fatal_error(pbuf);
440 441
            switch (ret) {
            case CONFIG_EINSANE:
442
                _fatal_error("filename was null or blank");
443 444
                break;
            case CONFIG_ENOROOT:
445
                _fatal_error("no root element found");
446 447
                break;
            case CONFIG_EBADROOT:
448
                _fatal_error("root element is not <icecast>");
449 450
                break;
            default:
451
                _fatal_error("XML config parsing error");
452 453
                break;
            }
454 455
            _shutdown_subsystems();
            return 1;
456 457 458 459 460 461 462 463
        }
    } 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
464

465 466
    /* Bind socket, before we change userid */
    if(!_server_proc_init()) {
467
        _fatal_error("Server startup failed. Exiting");
468 469 470
        _shutdown_subsystems();
        return 1;
    }
471

Michael Smith's avatar
Michael Smith committed
472
    _ch_root_uid_setup(); /* Change user id and root if requested/possible */
473 474

    stats_initialize(); /* We have to do this later on because of threading */
475
    fserve_initialize(); /* This too */
476 477 478 479 480 481

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

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

492
    if (!_start_logging()) {
493
        _fatal_error("FATAL: Could not start logging");
494 495 496
        _shutdown_subsystems();
        return 1;
    }
Jack Moffitt's avatar
Jack Moffitt committed
497

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

500
    /* REM 3D Graphics */
Jack Moffitt's avatar
Jack Moffitt committed
501

502 503
    /* let her rip */
    global.running = ICE_RUNNING;
504 505 506 507

    /* Startup yp thread */
    yp_initialize();

508 509
    /* Do this after logging init */
    slave_initialize();
510
    auth_initialise ();
511

512
    _server_proc();
Jack Moffitt's avatar
Jack Moffitt committed
513

514
    INFO0("Shutting down");
Jack Moffitt's avatar
Jack Moffitt committed
515

516
    _shutdown_subsystems();
Jack Moffitt's avatar
Jack Moffitt committed
517

518 519 520 521 522 523
    if (pidfile)
    {
        remove (pidfile);
        free (pidfile);
    }

524
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
525 526 527
}