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