main.c 12.4 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 24
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

Karl Heyes's avatar
Karl Heyes committed
25 26 27 28 29
#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
30

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

38
#include "cfgfile.h"
Jack Moffitt's avatar
Jack Moffitt committed
39 40 41
#include "sighandler.h"

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

54 55
#include <libxml/xmlmemory.h>

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

Jack Moffitt's avatar
Jack Moffitt committed
64 65 66
#undef CATMODULE
#define CATMODULE "main"

67 68 69
static int background;
static char *pidfile = NULL;

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

79
static void _print_usage(void)
Jack Moffitt's avatar
Jack Moffitt committed
80
{
81
    printf("%s\n\n", ICECAST_VERSION_STRING);
82
    printf("usage: icecast [-b -v] -c <file>\n");
83
    printf("options:\n");
84 85 86
    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");
87
    printf("\n");
Jack Moffitt's avatar
Jack Moffitt committed
88 89
}

90 91
static void _stop_logging(void)
{
92 93
    log_close(errorlog);
    log_close(accesslog);
94
    log_close(playlistlog);
95 96
}

97
static void _initialize_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
98
{
99 100 101 102 103 104 105 106
    log_initialize();
    thread_initialize();
    sock_initialize();
    resolver_initialize();
    config_initialize();
    connection_initialize();
    global_initialize();
    refbuf_initialize();
107
    xslt_initialize();
Jack Moffitt's avatar
Jack Moffitt committed
108 109
}

110
static void _shutdown_subsystems(void)
Jack Moffitt's avatar
Jack Moffitt committed
111
{
112
    fserve_shutdown();
113
    xslt_shutdown();
114 115
    refbuf_shutdown();
    slave_shutdown();
116
    auth_shutdown();
117
    yp_shutdown();
118
    stats_shutdown();
119

120 121 122 123 124 125
    global_shutdown();
    connection_shutdown();
    config_shutdown();
    resolver_shutdown();
    sock_shutdown();
    thread_shutdown();
126 127 128

    /* Now that these are done, we can stop the loggers. */
    _stop_logging();
129
    log_shutdown();
130 131

    xmlCleanupParser();
Jack Moffitt's avatar
Jack Moffitt committed
132 133
}

134
static int _parse_config_opts(int argc, char **argv, char *filename, int size)
Jack Moffitt's avatar
Jack Moffitt committed
135
{
136
    int i = 1;
137 138
    int config_ok = 0;

139
    background = 0;
140
    if (argc < 2) return -1;
Jack Moffitt's avatar
Jack Moffitt committed
141

142 143
    while (i < argc) {
        if (strcmp(argv[i], "-b") == 0) {
144
#ifndef WIN32
Michael Smith's avatar
Michael Smith committed
145
            pid_t pid;
146
            fprintf(stdout, "Starting icecast2\nDetaching from the console\n");
Michael Smith's avatar
Michael Smith committed
147 148 149 150

            pid = fork();

            if (pid > 0) {
151
                /* exit the parent */
152 153
                exit(0);
            }
Michael Smith's avatar
Michael Smith committed
154
            else if(pid < 0) {
155 156
                fprintf(stderr, "FATAL: Unable to fork child!");
                exit(1);
157
            }
158
            background = 1;
159
#endif
160
        }
161 162
        if (strcmp(argv[i], "-v") == 0) {
            fprintf(stdout, "%s\n", ICECAST_VERSION_STRING);
163 164 165
            exit(0);
        }

166 167 168
        if (strcmp(argv[i], "-c") == 0) {
            if (i + 1 < argc) {
                strncpy(filename, argv[i + 1], size-1);
169
                filename[size-1] = 0;
170
                config_ok = 1;
171 172 173 174 175 176 177
            } else {
                return -1;
            }
        }
        i++;
    }

178 179 180 181
    if(config_ok)
        return 1;
    else
        return -1;
Jack Moffitt's avatar
Jack Moffitt committed
182 183
}

184
static int _start_logging(void)
Jack Moffitt's avatar
Jack Moffitt committed
185
{
186 187
    char fn_error[FILENAME_MAX];
    char fn_access[FILENAME_MAX];
188
    char fn_playlist[FILENAME_MAX];
189
    char buf[1024];
190
    int log_to_stderr;
191

192
    ice_config_t *config = config_get_config_unlocked();
Jack Moffitt's avatar
Jack Moffitt committed
193

194
    if(strcmp(config->error_log, "-")) {
195
        snprintf(fn_error, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->error_log);
196
        errorlog = log_open(fn_error);
197
        log_to_stderr = 0;
198 199 200
        if (config->logsize)
            log_set_trigger (errorlog, config->logsize);
        log_set_archive_timestamp(errorlog, config->logarchive);
201 202
    } else {
        errorlog = log_open_file(stderr);
203
        log_to_stderr = 1;
204
    }
205 206 207

    if (errorlog < 0) {
        buf[sizeof(buf)-1] = 0;
208 209 210
        snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open error logging (%s): %s",
                log_to_stderr?"standard error":fn_error,
211 212 213 214 215
                strerror(errno));
        _fatal_error(buf);
    }
    log_set_level(errorlog, config->loglevel);

216
    if(strcmp(config->access_log, "-")) {
217
        snprintf(fn_access, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->access_log);
218
        accesslog = log_open(fn_access);
219
        log_to_stderr = 0;
220 221 222
        if (config->logsize)
            log_set_trigger (accesslog, config->logsize);
        log_set_archive_timestamp(accesslog, config->logarchive);
223 224
    } else {
        accesslog = log_open_file(stderr);
225
        log_to_stderr = 1;
226
    }
227 228 229

    if (accesslog < 0) {
        buf[sizeof(buf)-1] = 0;
230 231 232
        snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open access logging (%s): %s",
                log_to_stderr?"standard error":fn_access,
233 234 235
                strerror(errno));
        _fatal_error(buf);
    }
236 237 238 239 240 241 242 243 244 245 246 247 248

    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;
249 250 251
        if (config->logsize)
            log_set_trigger (playlistlog, config->logsize);
        log_set_archive_timestamp(playlistlog, config->logarchive);
252 253 254
    } else {
        playlistlog = -1;
    }
255

256 257
    log_set_level(errorlog, config->loglevel);
    log_set_level(accesslog, 4);
258
    log_set_level(playlistlog, 4);
259 260 261 262

    if (errorlog >= 0 && accesslog >= 0) return 1;
    
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
263 264 265
}


266
static int _start_listening(void)
Jack Moffitt's avatar
Jack Moffitt committed
267
{
268 269
    int i;
    for(i=0; i < global.server_sockets; i++) {
270 271
        if (sock_listen(global.serversock[i], ICE_LISTEN_QUEUE) == SOCK_ERROR)
            return 0;
Jack Moffitt's avatar
Jack Moffitt committed
272

273
        sock_set_blocking(global.serversock[i], SOCK_NONBLOCK);
274
    }
Jack Moffitt's avatar
Jack Moffitt committed
275

276
    return 1;
Jack Moffitt's avatar
Jack Moffitt committed
277 278
}

279
/* bind the socket and start listening */
280
static int _server_proc_init(void)
Jack Moffitt's avatar
Jack Moffitt committed
281
{
282
    ice_config_t *config = config_get_config_unlocked();
283

284
    if (connection_setup_sockets (config) < 1)
285
        return 0;
Jack Moffitt's avatar
Jack Moffitt committed
286

287
    if (!_start_listening()) {
288
        _fatal_error("Failed trying to listen on server socket");
289 290
        return 0;
    }
291

292 293 294 295 296 297 298 299 300 301 302 303
    /* 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);
        }
    }

304
    return 1;
305
}
Jack Moffitt's avatar
Jack Moffitt committed
306

307 308 309
/* this is the heart of the beast */
static void _server_proc(void)
{
310 311 312 313 314 315
    if (background)
    {
        fclose (stdin);
        fclose (stdout);
        fclose (stderr);
    }
316
    connection_accept_loop();
Jack Moffitt's avatar
Jack Moffitt committed
317

318
    connection_setup_sockets (NULL);
Jack Moffitt's avatar
Jack Moffitt committed
319 320
}

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

Michael Smith's avatar
Michael Smith committed
324
static void _ch_root_uid_setup(void)
325
{
Michael Smith's avatar
Michael Smith committed
326
   ice_config_t *conf = config_get_config_unlocked();
327 328 329 330 331 332 333 334
#ifdef CHUID
   struct passwd *user;
   struct group *group;
   uid_t uid=-1;
   gid_t gid=-1;

   if(conf->chuid)
   {
335 336 337 338 339 340 341 342 343
       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);
344

345 346 347 348 349
           if(group)
               gid = group->gr_gid;
           else
               fprintf(stderr, "Couldn't find group \"%s\" in groups file\n", conf->group);
       }
350 351 352 353
   }
#endif

#ifdef CHROOT
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
   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
372

373 374 375 376 377 378 379 380
   if(conf->chuid)
   {
       if(getuid()) /* root check */
       {
           fprintf(stderr, "WARNING: Can't change user id unless you are root.\n");
           return;
       }

381 382
       if(gid != -1) {
           if(!setgid(gid))
383
               fprintf(stdout, "Changed groupid to %i.\n", (int)gid);
384 385 386
           else
               fprintf(stdout, "Error changing groupid: %s.\n", strerror(errno));
       }
387

388 389
       if(uid != -1) {
           if(!setuid(uid))
390
               fprintf(stdout, "Changed userid to %i.\n", (int)uid);
391 392 393
           else
               fprintf(stdout, "Error changing userid: %s.\n", strerror(errno));
       }
394 395
   }
#endif
396
}
397 398 399 400 401 402

#ifdef WIN32_SERVICE
int mainService(int argc, char **argv)
#else
int main(int argc, char **argv)
#endif
Jack Moffitt's avatar
Jack Moffitt committed
403
{
404 405
    int res, ret;
    char filename[512];
406
    char pbuf[1024];
407 408 409 410

    /* parse the '-c icecast.xml' option
    ** only, so that we can read a configfile
    */
411
    res = _parse_config_opts(argc, argv, filename, 512);
412 413 414 415 416
    if (res == 1) {
        /* startup all the modules */
        _initialize_subsystems();

        /* parse the config file */
Michael Smith's avatar
Michael Smith committed
417
        config_get_config();
418
        ret = config_initial_parse_file(filename);
Michael Smith's avatar
Michael Smith committed
419
        config_release_config();
420
        if (ret < 0) {
421 422 423 424
            memset(pbuf, '\000', sizeof(pbuf));
            snprintf(pbuf, sizeof(pbuf)-1, 
                "FATAL: error parsing config file (%s)", filename);
            _fatal_error(pbuf);
425 426
            switch (ret) {
            case CONFIG_EINSANE:
427
                _fatal_error("filename was null or blank");
428 429
                break;
            case CONFIG_ENOROOT:
430
                _fatal_error("no root element found");
431 432
                break;
            case CONFIG_EBADROOT:
433
                _fatal_error("root element is not <icecast>");
434 435
                break;
            default:
436
                _fatal_error("XML config parsing error");
437 438
                break;
            }
439 440
            _shutdown_subsystems();
            return 1;
441 442 443 444 445 446 447 448
        }
    } 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
449

450 451
    /* Bind socket, before we change userid */
    if(!_server_proc_init()) {
452
        _fatal_error("Server startup failed. Exiting");
453 454 455
        _shutdown_subsystems();
        return 1;
    }
456

Michael Smith's avatar
Michael Smith committed
457
    _ch_root_uid_setup(); /* Change user id and root if requested/possible */
458 459

    stats_initialize(); /* We have to do this later on because of threading */
460
    fserve_initialize(); /* This too */
461 462 463 464 465 466

#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 */
    {
467
        fprintf(stderr, "ERROR: You should not run icecast2 as root\n");
468 469 470 471 472 473 474 475 476
        fprintf(stderr, "Use the changeowner directive in the config file\n");
        _shutdown_subsystems();
        return 1;
    }
#endif

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

477
    if (!_start_logging()) {
478
        _fatal_error("FATAL: Could not start logging");
479 480 481
        _shutdown_subsystems();
        return 1;
    }
Jack Moffitt's avatar
Jack Moffitt committed
482

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

485
    /* REM 3D Graphics */
Jack Moffitt's avatar
Jack Moffitt committed
486

487 488
    /* let her rip */
    global.running = ICE_RUNNING;
489 490 491 492

    /* Startup yp thread */
    yp_initialize();

493 494
    /* Do this after logging init */
    slave_initialize();
495
    auth_initialise ();
496

497
    _server_proc();
Jack Moffitt's avatar
Jack Moffitt committed
498

499
    INFO0("Shutting down");
Jack Moffitt's avatar
Jack Moffitt committed
500

501
    _shutdown_subsystems();
Jack Moffitt's avatar
Jack Moffitt committed
502

503 504 505 506 507 508
    if (pidfile)
    {
        remove (pidfile);
        free (pidfile);
    }

509
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
510 511 512
}