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
#include <stdio.h>
#include <string.h>
20 21 22 23 24 25 26 27 28 29
#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
30

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

Karl Heyes's avatar
Karl Heyes committed
38 39 40 41 42
#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
43

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

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

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

70 71
#include <libxml/xmlmemory.h>

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

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

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

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

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

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

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

124
void shutdown_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
125
{
126
    fserve_shutdown();
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();
147
    xslt_shutdown();
Jack Moffitt's avatar
Jack Moffitt committed
148 149
}

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

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

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

            pid = fork();

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

369
#if HAVE_CHROOT
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
387
#if HAVE_SETUID
388

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

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

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

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

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

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

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

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

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

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

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

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

504
    /* REM 3D Graphics */
Jack Moffitt's avatar
Jack Moffitt committed
505

506 507
    /* let her rip */
    global.running = ICE_RUNNING;
508 509 510 511

    /* Startup yp thread */
    yp_initialize();

512 513
    /* Do this after logging init */
    slave_initialize();
514
    auth_initialise ();
515

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

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

528
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
529 530 531
}