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