15ae5c9a296be654471fd1f95aa9395629fae097
[paraslash.git] / server.c
1 /*
2  * Copyright (C) 1997-2011 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 #include <stdbool.h>
71
72 #include "para.h"
73 #include "error.h"
74 #include "crypt.h"
75 #include "server.cmdline.h"
76 #include "afh.h"
77 #include "string.h"
78 #include "afs.h"
79 #include "server.h"
80 #include "list.h"
81 #include "send.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 "sched.h"
90 #include "signal.h"
91 #include "user_list.h"
92 #include "color.h"
93 #include "version.h"
94
95 /** Define the array of error lists needed by para_server. */
96 INIT_SERVER_ERRLISTS;
97
98 /** Shut down non-authorized connections after that many seconds. */
99 #define ALARM_TIMEOUT 10
100
101 /**
102  * Pointer to shared memory area for communication between para_server
103  * and its children. Exported to vss.c. command.c and to afs.
104  */
105 struct misc_meta_data *mmd;
106
107 /**
108  * The configuration of para_server
109  *
110  * It also contains the options for the audio file selector, audio format
111  * handler and all supported senders.
112  */
113 struct server_args_info conf;
114
115 /** A random value used in child context for authentication. */
116 uint32_t afs_socket_cookie;
117
118 /** The mutex protecting the shared memory area containing the mmd struct. */
119 int mmd_mutex;
120
121 /** The file containing user information (public key, permissions). */
122 static char *user_list_file = NULL;
123
124
125 /** The task responsible for server command handling. */
126 struct server_command_task {
127         /** TCP port on which para_server listens for connections. */
128         int listen_fd;
129         /** Copied from para_server's main function. */
130         int argc;
131         /** Argument vector passed to para_server's main function. */
132         char **argv;
133         /** The command task structure for scheduling. */
134         struct task task;
135 };
136
137 static int want_colors(void)
138 {
139         if (conf.color_arg == color_arg_no)
140                 return 0;
141         if (conf.color_arg == color_arg_yes)
142                 return 1;
143         if (conf.logfile_given)
144                 return 0;
145         return isatty(STDERR_FILENO);
146 }
147
148 static void init_colors_or_die(void)
149 {
150         int i;
151
152         if (!want_colors())
153                 return;
154         daemon_set_flag(DF_COLOR_LOG);
155         daemon_set_default_log_colors();
156         for (i = 0; i < conf.log_color_given; i++)
157                 daemon_set_log_color_or_die(conf.log_color_arg[i]);
158 }
159
160 /*
161  * setup shared memory area and get mutex for locking
162  */
163 static void init_ipc_or_die(void)
164 {
165         void *shm;
166         int shmid, ret = shm_new(sizeof(struct misc_meta_data));
167
168         if (ret < 0)
169                 goto err_out;
170         shmid = ret;
171         ret = shm_attach(shmid, ATTACH_RW, &shm);
172         shm_destroy(shmid);
173         if (ret < 0)
174                 goto err_out;
175         mmd = shm;
176
177         ret = mutex_new();
178         if (ret < 0)
179                 goto err_out;
180         mmd_mutex = ret;
181
182         mmd->num_played = 0;
183         mmd->num_commands = 0;
184         mmd->events = 0;
185         mmd->num_connects = 0;
186         mmd->active_connections = 0;
187         mmd->vss_status_flags = VSS_NEXT;
188         mmd->new_vss_status_flags = VSS_NEXT;
189         return;
190 err_out:
191         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
192         exit(EXIT_FAILURE);
193 }
194
195 /**
196  * (Re-)read the server configuration files.
197  *
198  * \param override Passed to gengetopt to activate the override feature.
199  *
200  * This function also re-opens the logfile and sets the global \a
201  * user_list_file variable.
202  */
203 void parse_config_or_die(int override)
204 {
205         char *home = para_homedir();
206         int ret;
207         char *cf;
208
209         daemon_close_log();
210         if (conf.config_file_given)
211                 cf = para_strdup(conf.config_file_arg);
212         else
213                 cf = make_message("%s/.paraslash/server.conf", home);
214         free(user_list_file);
215         if (!conf.user_list_given)
216                 user_list_file = make_message("%s/.paraslash/server.users", home);
217         else
218                 user_list_file = para_strdup(conf.user_list_arg);
219         ret = file_exists(cf);
220         if (conf.config_file_given && !ret)  {
221                 ret = -1;
222                 PARA_EMERG_LOG("can not read config file %s\n", cf);
223                 goto out;
224         }
225         if (ret) {
226                 int tmp = conf.daemon_given;
227                 struct server_cmdline_parser_params params = {
228                         .override = override,
229                         .initialize = 0,
230                         .check_required = 1,
231                         .check_ambiguity = 0,
232                         .print_errors = !conf.daemon_given
233                 };
234                 server_cmdline_parser_config_file(cf, &conf, &params);
235                 conf.daemon_given = tmp;
236         }
237         if (conf.logfile_given) {
238                 daemon_set_logfile(conf.logfile_arg);
239                 daemon_open_log_or_die();
240         }
241         daemon_set_loglevel(conf.loglevel_arg);
242         init_colors_or_die();
243         daemon_set_flag(DF_LOG_PID);
244         daemon_set_flag(DF_LOG_LL);
245         daemon_set_flag(DF_LOG_TIME);
246         if (conf.log_timing_given)
247                 daemon_set_flag(DF_LOG_TIMING);
248         ret = 1;
249 out:
250         free(cf);
251         free(home);
252         if (ret > 0)
253                 return;
254         free(user_list_file);
255         user_list_file = NULL;
256         exit(EXIT_FAILURE);
257 }
258
259 static void signal_pre_select(struct sched *s, struct task *t)
260 {
261         struct signal_task *st = container_of(t, struct signal_task, task);
262         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
263 }
264
265 /*
266  * called when server gets SIGHUP or when client invokes hup command.
267  */
268 static void handle_sighup(void)
269 {
270         PARA_NOTICE_LOG("SIGHUP\n");
271         parse_config_or_die(1); /* reopens log */
272         init_user_list(user_list_file); /* reload user list */
273         if (mmd->afs_pid)
274                 kill(mmd->afs_pid, SIGHUP);
275 }
276
277 static void signal_post_select(struct sched *s, __a_unused struct task *t)
278 {
279         int signum = para_next_signal(&s->rfds);
280
281         switch (signum) {
282         case 0:
283                 return;
284         case SIGHUP:
285                 handle_sighup();
286                 break;
287         case SIGCHLD:
288                 for (;;) {
289                         pid_t pid;
290                         int ret = para_reap_child(&pid);
291                         if (ret <= 0)
292                                 break;
293                         if (pid != mmd->afs_pid)
294                                 continue;
295                         PARA_EMERG_LOG("fatal: afs died\n");
296                         kill(0, SIGTERM);
297                         goto cleanup;
298                 }
299                 break;
300         /* die on sigint/sigterm. Kill all children too. */
301         case SIGINT:
302         case SIGTERM:
303                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
304                 kill(0, SIGTERM);
305                 /*
306                  * We must wait for afs because afs catches SIGINT/SIGTERM.
307                  * Before reacting to the signal, afs might want to use the
308                  * shared memory area and the mmd mutex.  If we destroy this
309                  * mutex too early and afs tries to lock the shared memory
310                  * area, the call to mutex_lock() will fail and terminate the
311                  * afs process. This leads to dirty osl tables.
312                  *
313                  * There's no such problem with the other children of the
314                  * server process (the command handlers) as these reset their
315                  * SIGINT/SIGTERM handlers to the default action, i.e.  these
316                  * processes get killed immediately by the above kill().
317                  */
318                 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
319                         (int)mmd->afs_pid);
320                 waitpid(mmd->afs_pid, NULL, 0);
321 cleanup:
322                 free(mmd->afd.afhi.chunk_table);
323                 close_listed_fds();
324                 mutex_destroy(mmd_mutex);
325                 shm_detach(mmd);
326                 exit(EXIT_FAILURE);
327         }
328 }
329
330 static void init_signal_task(void)
331 {
332         static struct signal_task signal_task_struct,
333                 *st = &signal_task_struct;
334
335         st->task.pre_select = signal_pre_select;
336         st->task.post_select = signal_post_select;
337         sprintf(st->task.status, "signal task");
338
339         PARA_NOTICE_LOG("setting up signal handling\n");
340         st->fd = para_signal_init(); /* always successful */
341         para_install_sighandler(SIGINT);
342         para_install_sighandler(SIGTERM);
343         para_install_sighandler(SIGHUP);
344         para_install_sighandler(SIGCHLD);
345         para_sigaction(SIGPIPE, SIG_IGN);
346         add_close_on_fork_list(st->fd);
347         register_task(&st->task);
348 }
349
350 static void command_pre_select(struct sched *s, struct task *t)
351 {
352         struct server_command_task *sct = container_of(t, struct server_command_task, task);
353         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
354 }
355
356 static void command_post_select(struct sched *s, struct task *t)
357 {
358         struct server_command_task *sct = container_of(t, struct server_command_task, task);
359
360         int new_fd, ret, i;
361         char *peer_name;
362         pid_t child_pid;
363         uint32_t *chunk_table;
364
365         ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
366         if (ret <= 0)
367                 goto out;
368         peer_name = remote_name(new_fd);
369         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
370         mmd->num_connects++;
371         mmd->active_connections++;
372         /*
373          * The chunk table is a pointer located in the mmd struct that points
374          * to dynamically allocated memory, i.e. it must be freed by the parent
375          * and the child. However, as the mmd struct is in a shared memory
376          * area, there's no guarantee that after the fork this pointer is still
377          * valid in child context. As it is not used in the child anyway, we
378          * save it to a local variable before the fork and free the memory via
379          * that copy in the child directly after the fork.
380          */
381         chunk_table = mmd->afd.afhi.chunk_table;
382         child_pid = fork();
383         if (child_pid < 0) {
384                 ret = -ERRNO_TO_PARA_ERROR(errno);
385                 goto out;
386         }
387         if (child_pid) {
388                 close(new_fd);
389                 /* parent keeps accepting connections */
390                 return;
391         }
392         /* mmd might already have changed at this point */
393         free(chunk_table);
394         alarm(ALARM_TIMEOUT);
395         close_listed_fds();
396         para_signal_shutdown();
397         /*
398          * put info on who we are serving into argv[0] to make
399          * client ip visible in top/ps
400          */
401         for (i = sct->argc - 1; i >= 0; i--)
402                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
403         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
404         return handle_connect(new_fd, peer_name);
405 out:
406         if (ret < 0)
407                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
408 }
409
410 static void init_server_command_task(int argc, char **argv)
411 {
412         int ret;
413         static struct server_command_task server_command_task_struct,
414                 *sct = &server_command_task_struct;
415
416         PARA_NOTICE_LOG("initializing tcp command socket\n");
417         sct->task.pre_select = command_pre_select;
418         sct->task.post_select = command_post_select;
419         sct->argc = argc;
420         sct->argv = argv;
421         ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
422         if (ret < 0)
423                 goto err;
424         sct->listen_fd = ret;
425         ret = mark_fd_nonblocking(sct->listen_fd);
426         if (ret < 0)
427                 goto err;
428         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
429         sprintf(sct->task.status, "server command task");
430         register_task(&sct->task);
431         return;
432 err:
433         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
434         exit(EXIT_FAILURE);
435 }
436
437 static int init_afs(void)
438 {
439         int ret, afs_server_socket[2];
440         pid_t afs_pid;
441
442         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
443         if (ret < 0)
444                 exit(EXIT_FAILURE);
445         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
446                 sizeof(afs_socket_cookie));
447         afs_pid = fork();
448         if (afs_pid < 0)
449                 exit(EXIT_FAILURE);
450         if (afs_pid == 0) { /* child (afs) */
451                 close(afs_server_socket[0]);
452                 afs_init(afs_socket_cookie, afs_server_socket[1]);
453         }
454         mmd->afs_pid = afs_pid;
455         close(afs_server_socket[1]);
456         ret = mark_fd_nonblocking(afs_server_socket[0]);
457         if (ret < 0)
458                 exit(EXIT_FAILURE);
459         add_close_on_fork_list(afs_server_socket[0]);
460         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
461                 afs_server_socket[0], (unsigned) afs_socket_cookie);
462         return afs_server_socket[0];
463 }
464
465 __noreturn static void tmp_sigchld_handler(__a_unused int s)
466 {
467         PARA_EMERG_LOG("caught early SIGCHLD\n");
468         exit(EXIT_FAILURE);
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();
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 install a SIGCHLD handler before the afs process is being
512          * forked off. Otherwise, para_server does not notice if afs dies before
513          * the SIGCHLD handler has been installed by init_signal_task() below.
514          */
515         para_sigaction(SIGCHLD, tmp_sigchld_handler);
516         PARA_NOTICE_LOG("initializing the audio file selector\n");
517         afs_socket = init_afs();
518         init_signal_task();
519         PARA_NOTICE_LOG("initializing virtual streaming system\n");
520         init_vss_task(afs_socket);
521         init_server_command_task(argc, argv);
522         PARA_NOTICE_LOG("server init complete\n");
523 }
524
525 static void status_refresh(void)
526 {
527         static int prev_uptime = -1, prev_events = -1;
528         int uptime = get_server_uptime(now);
529
530         if (prev_events != mmd->events)
531                 goto out;
532         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
533                 goto out_inc_events;
534         if (uptime / 60 != prev_uptime / 60)
535                 goto out_inc_events;
536         return;
537 out_inc_events:
538         mmd->events++;
539 out:
540         prev_uptime = uptime;
541         prev_events = mmd->events;
542         mmd->vss_status_flags = mmd->new_vss_status_flags;
543         PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
544         killpg(0, SIGUSR1);
545 }
546
547 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
548                 struct timeval *timeout_tv)
549 {
550         int ret;
551
552         status_refresh();
553         mutex_unlock(mmd_mutex);
554         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
555         mutex_lock(mmd_mutex);
556         return ret;
557 }
558
559 /**
560  * The main function of para_server.
561  *
562  * \param argc Usual argument count.
563  * \param argv Usual argument vector.
564  *
565  * \return EXIT_SUCCESS or EXIT_FAILURE.
566  */
567 int main(int argc, char *argv[])
568 {
569         int ret;
570         static struct sched s = {
571                 .default_timeout = {
572                         .tv_sec = 1,
573                         .tv_usec = 0
574                 },
575                 .select_function = server_select
576         };
577         server_init(argc, argv);
578         mutex_lock(mmd_mutex);
579         ret = schedule(&s);
580         if (ret < 0) {
581                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
582                 exit(EXIT_FAILURE);
583         }
584         exit(EXIT_SUCCESS);
585 }