interactive: Set stderr to nonbuffered mode.
[paraslash.git] / server.c
1 /*
2  * Copyright (C) 1997-2012 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file server.c Paraslash's main server. */
8
9
10 /**
11  * \mainpage Paraslash API Reference
12  *
13  * Starting points for getting an overview:
14  *
15  *
16  *      - The main programs: \ref server.c, \ref audiod.c, \ref client.c,
17  *        \ref audioc.c, \ref afh.c
18  *      - Server: \ref server_command, \ref sender,
19  *      - Audio file selector: \ref audio_format_handler, \ref afs_table,
20  *      - Client: \ref receiver, \ref receiver_node, \ref filter, \ref filter_node.
21  *
22  *
23  * The gory details, listed by topic:
24  *
25  *      - Audio format handlers: \ref send_common.c \ref mp3_afh.c,
26  *        \ref ogg_afh.c, \ref aac_afh.c, \ref wma_afh.c, \ref spx_afh.c
27  *      - Decoders: \ref mp3dec_filter.c, \ref oggdec_filter.c,
28  *        \ref aacdec_filter.c, \ref wmadec_filter.c, spxdec_filter.c,
29  *      - Volume normalizer: \ref compress_filter.c,
30  *      - Output: \ref alsa_write.c, \ref osx_write.c, \ref oss_write.c,
31  *      - http: \ref http_recv.c, \ref http_send.c,
32  *      - udp: \ref udp_recv.c, \ref udp_send.c,
33  *      - dccp: \ref dccp_recv.c, \ref dccp_send.c,
34  *      - Audio file selector: \ref afs.c, \ref aft.c, \ref mood.c,
35  *      - Afs structures: \ref afs_table, \ref audio_file_data,
36  *        \ref afs_info \ref afh_info,
37  *      - Afs tables: \ref aft.c, \ref mood.c, \ref playlist.c,
38  *        \ref attribute.c, \ref score.c,
39  *      - The virtual streaming system: \ref vss.c, \ref chunk_queue.c.
40  *
41  * Lower levels:
42  *
43  *      - Scheduling: \ref sched.c, \ref sched.h,
44  *      - Networking: \ref net.c,
45  *      - File descriptors: \ref fd.c,
46  *      - Signals: \ref signal.c,
47  *      - Daemons: \ref daemon.c,
48  *      - Strings: \ref string.c, \ref string.h,
49  *      - Time: \ref time.c,
50  *      - Spawning processes: \ref exec.c,
51  *      - Inter process communication: \ref ipc.c,
52  *      - Blob tables: \ref blob.c,
53  *      - The error subssystem: \ref error.h.
54  *      - Access control for paraslash senders: \ref acl.c, \ref acl.h.
55  *      - Internal crypto API: \ref crypt.h.
56  *
57  * Low-level data structures:
58  *
59  *      - Doubly linked lists: \ref list.h,
60  *      - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
61  *      - openssl: \ref crypt.c
62  *      - libgcrypt: \ref gcrypt.c
63  *      - Forward error correction: \ref fec.c.
64  */
65
66 #include <signal.h>
67 #include <sys/time.h>
68 #include <regex.h>
69 #include <osl.h>
70
71 #include "para.h"
72 #include "error.h"
73 #include "crypt.h"
74 #include "server.cmdline.h"
75 #include "afh.h"
76 #include "string.h"
77 #include "afs.h"
78 #include "server.h"
79 #include "list.h"
80 #include "send.h"
81 #include "sched.h"
82 #include "vss.h"
83 #include "config.h"
84 #include "close_on_fork.h"
85 #include "net.h"
86 #include "daemon.h"
87 #include "ipc.h"
88 #include "fd.h"
89 #include "signal.h"
90 #include "user_list.h"
91 #include "color.h"
92 #include "version.h"
93
94 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
95
96 /** Define the array of error lists needed by para_server. */
97 INIT_SERVER_ERRLISTS;
98
99 /** Shut down non-authorized connections after that many seconds. */
100 #define ALARM_TIMEOUT 10
101
102 /**
103  * Pointer to shared memory area for communication between para_server
104  * and its children. Exported to vss.c. command.c and to afs.
105  */
106 struct misc_meta_data *mmd;
107
108 /**
109  * The configuration of para_server
110  *
111  * It also contains the options for the audio file selector, audio format
112  * handler and all supported senders.
113  */
114 struct server_args_info conf;
115
116 /** A random value used in child context for authentication. */
117 uint32_t afs_socket_cookie;
118
119 /** The mutex protecting the shared memory area containing the mmd struct. */
120 int mmd_mutex;
121
122 /** The file containing user information (public key, permissions). */
123 static char *user_list_file = NULL;
124
125 static struct sched sched;
126
127 /** The task responsible for server command handling. */
128 struct server_command_task {
129         /** TCP port on which para_server listens for connections. */
130         int listen_fd;
131         /** Copied from para_server's main function. */
132         int argc;
133         /** Argument vector passed to para_server's main function. */
134         char **argv;
135         /** The command task structure for scheduling. */
136         struct task task;
137 };
138
139 static int want_colors(void)
140 {
141         if (conf.color_arg == color_arg_no)
142                 return 0;
143         if (conf.color_arg == color_arg_yes)
144                 return 1;
145         if (conf.logfile_given)
146                 return 0;
147         return isatty(STDERR_FILENO);
148 }
149
150 static void init_colors_or_die(void)
151 {
152         int i;
153
154         if (!want_colors())
155                 return;
156         daemon_set_flag(DF_COLOR_LOG);
157         daemon_set_default_log_colors();
158         for (i = 0; i < conf.log_color_given; i++)
159                 daemon_set_log_color_or_die(conf.log_color_arg[i]);
160 }
161
162 /*
163  * setup shared memory area and get mutex for locking
164  */
165 static void init_ipc_or_die(void)
166 {
167         void *shm;
168         int shmid, ret = shm_new(sizeof(struct misc_meta_data));
169
170         if (ret < 0)
171                 goto err_out;
172         shmid = ret;
173         ret = shm_attach(shmid, ATTACH_RW, &shm);
174         shm_destroy(shmid);
175         if (ret < 0)
176                 goto err_out;
177         mmd = shm;
178
179         ret = mutex_new();
180         if (ret < 0)
181                 goto err_out;
182         mmd_mutex = ret;
183
184         mmd->num_played = 0;
185         mmd->num_commands = 0;
186         mmd->events = 0;
187         mmd->num_connects = 0;
188         mmd->active_connections = 0;
189         mmd->vss_status_flags = VSS_NEXT;
190         mmd->new_vss_status_flags = VSS_NEXT;
191         return;
192 err_out:
193         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
194         exit(EXIT_FAILURE);
195 }
196
197 /**
198  * (Re-)read the server configuration files.
199  *
200  * \param override Passed to gengetopt to activate the override feature.
201  *
202  * This function also re-opens the logfile and sets the global \a
203  * user_list_file variable.
204  */
205 void parse_config_or_die(int override)
206 {
207         char *home = para_homedir();
208         int ret;
209         char *cf;
210
211         daemon_close_log();
212         if (conf.config_file_given)
213                 cf = para_strdup(conf.config_file_arg);
214         else
215                 cf = make_message("%s/.paraslash/server.conf", home);
216         free(user_list_file);
217         if (!conf.user_list_given)
218                 user_list_file = make_message("%s/.paraslash/server.users", home);
219         else
220                 user_list_file = para_strdup(conf.user_list_arg);
221         ret = file_exists(cf);
222         if (conf.config_file_given && !ret)  {
223                 ret = -1;
224                 PARA_EMERG_LOG("can not read config file %s\n", cf);
225                 goto out;
226         }
227         if (ret) {
228                 int tmp = conf.daemon_given;
229                 struct server_cmdline_parser_params params = {
230                         .override = override,
231                         .initialize = 0,
232                         .check_required = 1,
233                         .check_ambiguity = 0,
234                         .print_errors = !conf.daemon_given
235                 };
236                 server_cmdline_parser_config_file(cf, &conf, &params);
237                 conf.daemon_given = tmp;
238         }
239         if (conf.logfile_given) {
240                 daemon_set_logfile(conf.logfile_arg);
241                 daemon_open_log_or_die();
242         }
243         daemon_set_loglevel(conf.loglevel_arg);
244         init_colors_or_die();
245         daemon_set_flag(DF_LOG_PID);
246         daemon_set_flag(DF_LOG_LL);
247         daemon_set_flag(DF_LOG_TIME);
248         if (conf.log_timing_given)
249                 daemon_set_flag(DF_LOG_TIMING);
250         ret = 1;
251 out:
252         free(cf);
253         free(home);
254         if (ret > 0)
255                 return;
256         free(user_list_file);
257         user_list_file = NULL;
258         exit(EXIT_FAILURE);
259 }
260
261 static void signal_pre_select(struct sched *s, struct task *t)
262 {
263         struct signal_task *st = container_of(t, struct signal_task, task);
264         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
265 }
266
267 /*
268  * called when server gets SIGHUP or when client invokes hup command.
269  */
270 static void handle_sighup(void)
271 {
272         PARA_NOTICE_LOG("SIGHUP\n");
273         parse_config_or_die(1); /* reopens log */
274         init_user_list(user_list_file); /* reload user list */
275         if (mmd->afs_pid)
276                 kill(mmd->afs_pid, SIGHUP);
277 }
278
279 static void signal_post_select(struct sched *s, __a_unused struct task *t)
280 {
281         int signum = para_next_signal(&s->rfds);
282
283         switch (signum) {
284         case 0:
285                 return;
286         case SIGHUP:
287                 handle_sighup();
288                 break;
289         case SIGCHLD:
290                 for (;;) {
291                         pid_t pid;
292                         int ret = para_reap_child(&pid);
293                         if (ret <= 0)
294                                 break;
295                         if (pid != mmd->afs_pid)
296                                 continue;
297                         PARA_EMERG_LOG("fatal: afs died\n");
298                         kill(0, SIGTERM);
299                         goto cleanup;
300                 }
301                 break;
302         /* die on sigint/sigterm. Kill all children too. */
303         case SIGINT:
304         case SIGTERM:
305                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
306                 kill(0, SIGTERM);
307                 /*
308                  * We must wait for afs because afs catches SIGINT/SIGTERM.
309                  * Before reacting to the signal, afs might want to use the
310                  * shared memory area and the mmd mutex.  If we destroy this
311                  * mutex too early and afs tries to lock the shared memory
312                  * area, the call to mutex_lock() will fail and terminate the
313                  * afs process. This leads to dirty osl tables.
314                  *
315                  * There's no such problem with the other children of the
316                  * server process (the command handlers) as these reset their
317                  * SIGINT/SIGTERM handlers to the default action, i.e.  these
318                  * processes get killed immediately by the above kill().
319                  */
320                 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
321                         (int)mmd->afs_pid);
322                 waitpid(mmd->afs_pid, NULL, 0);
323 cleanup:
324                 free(mmd->afd.afhi.chunk_table);
325                 close_listed_fds();
326                 mutex_destroy(mmd_mutex);
327                 shm_detach(mmd);
328                 exit(EXIT_FAILURE);
329         }
330 }
331
332 static void init_signal_task(void)
333 {
334         static struct signal_task signal_task_struct,
335                 *st = &signal_task_struct;
336
337         st->task.pre_select = signal_pre_select;
338         st->task.post_select = signal_post_select;
339         sprintf(st->task.status, "signal task");
340
341         PARA_NOTICE_LOG("setting up signal handling\n");
342         st->fd = para_signal_init(); /* always successful */
343         para_install_sighandler(SIGINT);
344         para_install_sighandler(SIGTERM);
345         para_install_sighandler(SIGHUP);
346         para_install_sighandler(SIGCHLD);
347         para_sigaction(SIGPIPE, SIG_IGN);
348         add_close_on_fork_list(st->fd);
349         register_task(&sched, &st->task);
350 }
351
352 static void command_pre_select(struct sched *s, struct task *t)
353 {
354         struct server_command_task *sct = container_of(t, struct server_command_task, task);
355         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
356 }
357
358 static void command_post_select(struct sched *s, struct task *t)
359 {
360         struct server_command_task *sct = container_of(t, struct server_command_task, task);
361
362         int new_fd, ret, i;
363         char *peer_name;
364         pid_t child_pid;
365         uint32_t *chunk_table;
366
367         ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
368         if (ret <= 0)
369                 goto out;
370         peer_name = remote_name(new_fd);
371         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
372         mmd->num_connects++;
373         mmd->active_connections++;
374         /*
375          * The chunk table is a pointer located in the mmd struct that points
376          * to dynamically allocated memory, i.e. it must be freed by the parent
377          * and the child. However, as the mmd struct is in a shared memory
378          * area, there's no guarantee that after the fork this pointer is still
379          * valid in child context. As it is not used in the child anyway, we
380          * save it to a local variable before the fork and free the memory via
381          * that copy in the child directly after the fork.
382          */
383         chunk_table = mmd->afd.afhi.chunk_table;
384         child_pid = fork();
385         if (child_pid < 0) {
386                 ret = -ERRNO_TO_PARA_ERROR(errno);
387                 goto out;
388         }
389         if (child_pid) {
390                 close(new_fd);
391                 /* parent keeps accepting connections */
392                 return;
393         }
394         /* mmd might already have changed at this point */
395         free(chunk_table);
396         alarm(ALARM_TIMEOUT);
397         close_listed_fds();
398         para_signal_shutdown();
399         /*
400          * put info on who we are serving into argv[0] to make
401          * client ip visible in top/ps
402          */
403         for (i = sct->argc - 1; i >= 0; i--)
404                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
405         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
406         return handle_connect(new_fd, peer_name);
407 out:
408         if (ret < 0)
409                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
410 }
411
412 static void init_server_command_task(int argc, char **argv)
413 {
414         int ret;
415         static struct server_command_task server_command_task_struct,
416                 *sct = &server_command_task_struct;
417
418         PARA_NOTICE_LOG("initializing tcp command socket\n");
419         sct->task.pre_select = command_pre_select;
420         sct->task.post_select = command_post_select;
421         sct->argc = argc;
422         sct->argv = argv;
423         ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
424         if (ret < 0)
425                 goto err;
426         sct->listen_fd = ret;
427         ret = mark_fd_nonblocking(sct->listen_fd);
428         if (ret < 0)
429                 goto err;
430         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
431         sprintf(sct->task.status, "server command task");
432         register_task(&sched, &sct->task);
433         return;
434 err:
435         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
436         exit(EXIT_FAILURE);
437 }
438
439 static int init_afs(int argc, char **argv)
440 {
441         int ret, afs_server_socket[2];
442         pid_t afs_pid;
443
444         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
445         if (ret < 0)
446                 exit(EXIT_FAILURE);
447         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
448                 sizeof(afs_socket_cookie));
449         afs_pid = fork();
450         if (afs_pid < 0)
451                 exit(EXIT_FAILURE);
452         if (afs_pid == 0) { /* child (afs) */
453                 int i;
454                 for (i = argc - 1; i >= 0; i--)
455                         memset(argv[i], 0, strlen(argv[i]));
456                 sprintf(argv[0], "para_server (afs)");
457                 close(afs_server_socket[0]);
458                 afs_init(afs_socket_cookie, afs_server_socket[1]);
459         }
460         mmd->afs_pid = afs_pid;
461         close(afs_server_socket[1]);
462         ret = mark_fd_nonblocking(afs_server_socket[0]);
463         if (ret < 0)
464                 exit(EXIT_FAILURE);
465         add_close_on_fork_list(afs_server_socket[0]);
466         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
467                 afs_server_socket[0], (unsigned) afs_socket_cookie);
468         return afs_server_socket[0];
469 }
470
471 static void server_init(int argc, char **argv)
472 {
473         struct server_cmdline_parser_params params = {
474                 .override = 0,
475                 .initialize = 1,
476                 .check_required = 0,
477                 .check_ambiguity = 0,
478                 .print_errors = 1
479         };
480         int afs_socket;
481
482         valid_fd_012();
483         init_random_seed_or_die();
484         /* parse command line options */
485         server_cmdline_parser_ext(argc, argv, &conf, &params);
486         HANDLE_VERSION_FLAG("server", conf);
487         drop_privileges_or_die(conf.user_arg, conf.group_arg);
488         /* parse config file, open log and set defaults */
489         parse_config_or_die(0);
490         log_welcome("para_server");
491         init_ipc_or_die(); /* init mmd struct and mmd->lock */
492         /* make sure, the global now pointer is uptodate */
493         gettimeofday(now, NULL);
494         set_server_start_time(now);
495         init_user_list(user_list_file);
496         /* become daemon */
497         if (conf.daemon_given)
498                 daemonize(true /* parent waits for SIGTERM */);
499         PARA_NOTICE_LOG("initializing audio format handlers\n");
500         afh_init();
501
502         /*
503          * Although afs uses its own signal handling we must ignore SIGUSR1
504          * _before_ the afs child process gets born by init_afs() below.  It's
505          * racy to do this in the child because the parent might send SIGUSR1
506          * before the child gets a chance to ignore this signal -- only the
507          * good die young.
508          */
509         para_sigaction(SIGUSR1, SIG_IGN);
510         /*
511          * We have to block SIGCHLD before the afs process is being forked off.
512          * Otherwise, para_server does not notice if afs dies before the
513          * SIGCHLD handler has been installed for the parent process by
514          * init_signal_task() below.
515          */
516         para_block_signal(SIGCHLD);
517         PARA_NOTICE_LOG("initializing the audio file selector\n");
518         afs_socket = init_afs(argc, argv);
519         init_signal_task();
520         para_unblock_signal(SIGCHLD);
521         PARA_NOTICE_LOG("initializing virtual streaming system\n");
522         init_vss_task(afs_socket, &sched);
523         init_server_command_task(argc, argv);
524         if (conf.daemon_given)
525                 kill(getppid(), SIGTERM);
526         PARA_NOTICE_LOG("server init complete\n");
527 }
528
529 static void status_refresh(void)
530 {
531         static int prev_uptime = -1, prev_events = -1;
532         int uptime = get_server_uptime(now);
533
534         if (prev_events != mmd->events)
535                 goto out;
536         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
537                 goto out_inc_events;
538         if (uptime / 60 != prev_uptime / 60)
539                 goto out_inc_events;
540         return;
541 out_inc_events:
542         mmd->events++;
543 out:
544         prev_uptime = uptime;
545         prev_events = mmd->events;
546         mmd->vss_status_flags = mmd->new_vss_status_flags;
547         PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
548         killpg(0, SIGUSR1);
549 }
550
551 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
552                 struct timeval *timeout_tv)
553 {
554         int ret;
555
556         status_refresh();
557         mutex_unlock(mmd_mutex);
558         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
559         mutex_lock(mmd_mutex);
560         return ret;
561 }
562
563 /**
564  * The main function of para_server.
565  *
566  * \param argc Usual argument count.
567  * \param argv Usual argument vector.
568  *
569  * \return EXIT_SUCCESS or EXIT_FAILURE.
570  */
571 int main(int argc, char *argv[])
572 {
573         int ret;
574
575         sched.default_timeout.tv_sec = 1;
576         sched.select_function = server_select;
577
578         server_init(argc, argv);
579         mutex_lock(mmd_mutex);
580         ret = schedule(&sched);
581         if (ret < 0) {
582                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
583                 exit(EXIT_FAILURE);
584         }
585         exit(EXIT_SUCCESS);
586 }