a4115eb65734391128481f6fa421d548aba78e20
[paraslash.git] / server.c
1 /*
2  * Copyright (C) 1997-2009 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 fsck.c, \ref afh.c
18  *      - Server: \ref server_command, \ref sender,
19  *      - Audio file selector: \ref audio_format_handler, \ref mood, \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, \ref ogg_afh.c, \ref aac_afh.c,
26  *      - Decoders: \ref mp3dec_filter.c, \ref oggdec_filter.c, \ref aacdec_filter.c,
27  *      - Volume normalizer: \ref compress_filter.c,
28  *      - Output: \ref alsa_write.c, \ref osx_write.c,
29  *      - http: \ref http_recv.c, \ref http_send.c,
30  *      - udp: \ref udp_recv.c, \ref udp_send.c,
31  *      - dccp: \ref dccp_recv.c, \ref dccp_send.c,
32  *      - Audio file selector: \ref afs.c, \ref aft.c, \ref mood.c,
33  *      - Afs structures: \ref afs_table, \ref audio_file_data,
34  *        \ref afs_info \ref afh_info,
35  *      - Afs tables: \ref aft.c, \ref mood.c, \ref playlist.c,
36  *        \ref attribute.c, \ref score.c,
37  *      - The virtual streaming system: \ref vss.c, \ref chunk_queue.c.
38  *
39  * Lower levels:
40  *
41  *      - Scheduling: \ref sched.c, \ref sched.h,
42  *      - Networking: \ref net.c,
43  *      - File descriptors: \ref fd.c,
44  *      - Signals: \ref signal.c,
45  *      - Daemons: \ref daemon.c,
46  *      - Strings: \ref string.c, \ref string.h,
47  *      - Time: \ref time.c,
48  *      - Spawning processes: \ref exec.c,
49  *      - Inter process communication: \ref ipc.c,
50  *      - The object storage layer: \ref osl.c,
51  *      - Blob tables: \ref blob.c,
52  *      - The error subssystem: \ref error.h.
53  *      - Access control for paraslash senders: \ref acl.c, \ref acl.h.
54  *
55  * Low-level data structures:
56  *
57  *      - Doubly linked lists: \ref list.h,
58  *      - Red-black trees: \ref rbtree.h, \ref rbtree.c,
59  *      - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
60  *      - Hashing: \ref hash.h, \ref sha1.h, \ref sha1.c,
61  *      - Crypto: \ref crypt.c.
62  *
63  */
64
65 #include <signal.h>
66 #include <dirent.h>
67 #include <sys/time.h>
68
69 #include "para.h"
70 #include "error.h"
71 #include "server.cmdline.h"
72 #include "afh.h"
73 #include "string.h"
74 #include "afs.h"
75 #include "server.h"
76 #include "vss.h"
77 #include "config.h"
78 #include "close_on_fork.h"
79 #include "list.h"
80 #include "send.h"
81 #include "net.h"
82 #include "daemon.h"
83 #include "ipc.h"
84 #include "fd.h"
85 #include "sched.h"
86 #include "signal.h"
87 #include "user_list.h"
88 #include "color.h"
89
90 /** Define the array of error lists needed by para_server. */
91 INIT_SERVER_ERRLISTS;
92
93 /** Shut down non-authorized connections after that many seconds. */
94 #define ALARM_TIMEOUT 10
95
96 /**
97  * Pointer to shared memory area for communication between para_server
98  * and its children. Exported to vss.c. command.c and to afs.
99  */
100 struct misc_meta_data *mmd;
101
102 /**
103  * The configuration of para_server
104  *
105  * It also contains the options for the audio file selector, audio format
106  * handler and all supported senders.
107  */
108 struct server_args_info conf;
109
110 /** A random value used in child context for authentication. */
111 uint32_t afs_socket_cookie;
112
113 /** The mutex protecting the shared memory area containing the mmd struct. */
114 int mmd_mutex;
115
116 /** The file containing user information (public key, permissions). */
117 static char *user_list_file = NULL;
118
119
120 /** The task responsible for server command handling. */
121 struct server_command_task {
122         /** TCP port on which para_server listens for connections. */
123         int listen_fd;
124         /** Copied from para_server's main function. */
125         int argc;
126         /** Argument vector passed to para_server's main function. */
127         char **argv;
128         /** The command task structure for scheduling. */
129         struct task task;
130 };
131
132 static int want_colors(void)
133 {
134         if (conf.color_arg == color_arg_no)
135                 return 0;
136         if (conf.color_arg == color_arg_yes)
137                 return 1;
138         if (conf.logfile_given)
139                 return 0;
140         return isatty(STDERR_FILENO);
141 }
142
143 static void init_colors_or_die(void)
144 {
145         int ret, i;
146
147         if (!want_colors())
148                 return;
149         daemon_set_flag(DF_COLOR_LOG);
150         daemon_set_default_log_colors();
151         for (i = 0; i < conf.log_color_given; i++) {
152                 ret = daemon_set_log_color(conf.log_color_arg[i]);
153                 if (ret < 0)
154                         exit(EXIT_FAILURE);
155         }
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         ret = 1;
245 out:
246         free(cf);
247         free(home);
248         if (ret > 0)
249                 return;
250         free(user_list_file);
251         user_list_file = NULL;
252         exit(EXIT_FAILURE);
253 }
254
255 static void signal_pre_select(struct sched *s, struct task *t)
256 {
257         struct signal_task *st = container_of(t, struct signal_task, task);
258         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
259 }
260
261 /*
262  * called when server gets SIGHUP or when client invokes hup command.
263  */
264 static void handle_sighup(void)
265 {
266         PARA_NOTICE_LOG("SIGHUP\n");
267         parse_config_or_die(1); /* reopens log */
268         init_user_list(user_list_file); /* reload user list */
269         if (mmd->afs_pid)
270                 kill(mmd->afs_pid, SIGHUP);
271 }
272
273 static void signal_post_select(struct sched *s, struct task *t)
274 {
275         struct signal_task *st = container_of(t, struct signal_task, task);
276
277         if (!FD_ISSET(st->fd, &s->rfds))
278                 return;
279
280         st->signum = para_next_signal();
281         switch (st->signum) {
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                         goto genocide;
295                 }
296                 break;
297         /* die on sigint/sigterm. Kill all children too. */
298         case SIGINT:
299         case SIGTERM:
300                 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
301 genocide:
302                 kill(0, SIGTERM);
303                 free(mmd->afd.afhi.chunk_table);
304                 free(mmd->afd.afhi.info_string);
305                 close_listed_fds();
306                 mutex_destroy(mmd_mutex);
307                 shm_detach(mmd);
308                 exit(EXIT_FAILURE);
309         }
310 }
311
312 static void init_signal_task(void)
313 {
314         static struct signal_task signal_task_struct,
315                 *st = &signal_task_struct;
316
317         st->task.pre_select = signal_pre_select;
318         st->task.post_select = signal_post_select;
319         sprintf(st->task.status, "signal task");
320
321         st->fd = para_signal_init(); /* always successful */
322
323         PARA_NOTICE_LOG("setting up signal handlers\n");
324         if (para_install_sighandler(SIGINT) < 0)
325                 goto err;
326         if (para_install_sighandler(SIGTERM) < 0)
327                 goto err;
328         if (para_install_sighandler(SIGHUP) < 0)
329                 goto err;
330         if (para_install_sighandler(SIGCHLD) < 0)
331                 goto err;
332         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
333                 goto err;
334         add_close_on_fork_list(st->fd);
335         register_task(&st->task);
336         return;
337 err:
338         PARA_EMERG_LOG("could not install signal handlers\n");
339         exit(EXIT_FAILURE);
340 }
341
342 static void command_pre_select(struct sched *s, struct task *t)
343 {
344         struct server_command_task *sct = container_of(t, struct server_command_task, task);
345         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
346 }
347
348 static void command_post_select(struct sched *s, struct task *t)
349 {
350         struct server_command_task *sct = container_of(t, struct server_command_task, task);
351
352         int new_fd, ret, i;
353         char *peer_name;
354         pid_t child_pid;
355         uint32_t *chunk_table;
356         char *info_string;
357
358         if (!FD_ISSET(sct->listen_fd, &s->rfds))
359                 return;
360         ret = para_accept(sct->listen_fd, NULL, 0);
361         if (ret < 0)
362                 goto out;
363         new_fd = ret;
364         peer_name = remote_name(new_fd);
365         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
366         mmd->num_connects++;
367         mmd->active_connections++;
368         random();
369         /* The chunk table and the info_string are pointers located in the
370          * mmd struct that point to dynamically allocated memory that must be
371          * freed by the parent and the child. However, as the mmd struct is in
372          * a shared memory area, there's no guarantee that after the fork these
373          * pointers are still valid in child context. As these two pointers are
374          * not used in the child anyway, we save them to local variables and
375          * free the memory via that copy in the child.
376          */
377         info_string = mmd->afd.afhi.info_string;
378         chunk_table = mmd->afd.afhi.chunk_table;
379         child_pid = fork();
380         if (child_pid < 0) {
381                 ret = -ERRNO_TO_PARA_ERROR(errno);
382                 goto out;
383         }
384         if (child_pid) {
385                 close(new_fd);
386                 /* parent keeps accepting connections */
387                 return;
388         }
389         /* mmd might already have changed at this point */
390         free(info_string);
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(AF_UNSPEC, 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         register_task(&sct->task);
428         return;
429 err:
430         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
431         exit(EXIT_FAILURE);
432 }
433
434 static void init_random_seed(void)
435 {
436         unsigned int seed;
437         int fd, ret = para_open("/dev/urandom", O_RDONLY, 0);
438
439         if (ret < 0)
440                 goto err;
441         fd = ret;
442         ret = read(fd, &seed, sizeof(seed));
443         if (ret < 0) {
444                 ret = -ERRNO_TO_PARA_ERROR(errno);
445                 goto out;
446         }
447         if (ret != sizeof(seed)) {
448                 ret = -ERRNO_TO_PARA_ERROR(EIO);
449                 goto out;
450         }
451         srandom(seed);
452         ret = 1;
453 out:
454         close(fd);
455         if (ret >= 0)
456                 return;
457 err:
458         PARA_EMERG_LOG("can not seed pseudo random number generator: %s\n",
459                 para_strerror(-ret));
460         exit(EXIT_FAILURE);
461 }
462
463 static int init_afs(void)
464 {
465         int ret, afs_server_socket[2];
466
467         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
468         if (ret < 0)
469                 exit(EXIT_FAILURE);
470         afs_socket_cookie = para_random((uint32_t)-1);
471         mmd->afs_pid = fork();
472         if (mmd->afs_pid < 0)
473                 exit(EXIT_FAILURE);
474         if (!mmd->afs_pid) { /* child (afs) */
475                 close(afs_server_socket[0]);
476                 afs_init(afs_socket_cookie, afs_server_socket[1]);
477         }
478         close(afs_server_socket[1]);
479         ret = mark_fd_nonblocking(afs_server_socket[0]);
480         if (ret < 0)
481                 exit(EXIT_FAILURE);
482         add_close_on_fork_list(afs_server_socket[0]);
483         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
484                 afs_server_socket[0], (unsigned) afs_socket_cookie);
485         return afs_server_socket[0];
486 }
487
488 __noreturn static void tmp_sigchld_handler(__a_unused int s)
489 {
490         PARA_EMERG_LOG("caught early SIGCHLD\n");
491         exit(EXIT_FAILURE);
492 }
493
494 static void server_init(int argc, char **argv)
495 {
496         struct server_cmdline_parser_params params = {
497                 .override = 0,
498                 .initialize = 1,
499                 .check_required = 0,
500                 .check_ambiguity = 0,
501                 .print_errors = 1
502         };
503         int afs_socket;
504
505         valid_fd_012();
506         init_random_seed();
507         /* parse command line options */
508         server_cmdline_parser_ext(argc, argv, &conf, &params);
509         HANDLE_VERSION_FLAG("server", conf);
510         drop_privileges_or_die(conf.user_arg, conf.group_arg);
511         /* parse config file, open log and set defaults */
512         parse_config_or_die(0);
513         log_welcome("para_server");
514         init_ipc_or_die(); /* init mmd struct and mmd->lock */
515         /* make sure, the global now pointer is uptodate */
516         gettimeofday(now, NULL);
517         server_uptime(UPTIME_SET); /* reset server uptime */
518         init_user_list(user_list_file);
519         /* become daemon */
520         if (conf.daemon_given)
521                 daemonize();
522         PARA_NOTICE_LOG("initializing audio format handlers\n");
523         afh_init();
524
525         /*
526          * Although afs uses its own signal handling we must ignore SIGUSR1
527          * _before_ the afs child process gets born by init_afs() below.  It's
528          * racy to do this in the child because the parent might send SIGUSR1
529          * before the child gets a chance to ignore this signal -- only the
530          * good die young.
531          */
532         if (signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
533                 PARA_EMERG_LOG("failed to ignore SIGUSR1\n");
534                 exit(EXIT_FAILURE);
535         }
536         /*
537          * We have to install a SIGCHLD handler before the afs process is being
538          * forked off. Otherwise, para_server does not notice if afs dies before
539          * the SIGCHLD handler has been installed by init_signal_task() below.
540          */
541         if (signal(SIGCHLD, tmp_sigchld_handler) == SIG_ERR) {
542                 PARA_EMERG_LOG("failed to install temporary SIGCHLD handler\n");
543                 exit(EXIT_FAILURE);
544         }
545         PARA_NOTICE_LOG("initializing the audio file selector\n");
546         afs_socket = init_afs();
547         init_signal_task();
548         PARA_NOTICE_LOG("initializing virtual streaming system\n");
549         init_vss_task(afs_socket);
550         init_server_command_task(argc, argv);
551         PARA_NOTICE_LOG("server init complete\n");
552 }
553
554 static void status_refresh(void)
555 {
556         static int prev_uptime = -1, prev_events = -1;
557         int uptime = server_uptime(UPTIME_GET), ret = 1;
558
559         if (prev_events != mmd->events)
560                 goto out;
561         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
562                 goto out_inc_events;
563         if (uptime / 60 != prev_uptime / 60)
564                 goto out_inc_events;
565         return;
566 out_inc_events:
567         mmd->events++;
568 out:
569         prev_uptime = uptime;
570         prev_events = mmd->events;
571         mmd->vss_status_flags = mmd->new_vss_status_flags;
572         if (ret) {
573                 PARA_DEBUG_LOG("%d events, forcing status update\n",
574                         mmd->events);
575                 killpg(0, SIGUSR1);
576         }
577 }
578
579 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
580                 struct timeval *timeout_tv)
581 {
582         int ret;
583
584         status_refresh();
585         mutex_unlock(mmd_mutex);
586         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
587         mutex_lock(mmd_mutex);
588         return ret;
589 }
590
591 /**
592  * The main function of para_server.
593  *
594  * \param argc Usual argument count.
595  * \param argv Usual argument vector.
596  *
597  * \return EXIT_SUCCESS or EXIT_FAILURE.
598  */
599 int main(int argc, char *argv[])
600 {
601         int ret;
602         static struct sched s = {
603                 .default_timeout = {
604                         .tv_sec = 1,
605                         .tv_usec = 0
606                 },
607                 .select_function = server_select
608         };
609         server_init(argc, argv);
610         mutex_lock(mmd_mutex);
611         ret = schedule(&s);
612         if (ret < 0) {
613                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
614                 exit(EXIT_FAILURE);
615         }
616         exit(EXIT_SUCCESS);
617 }