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