]> git.tuebingen.mpg.de Git - paraslash.git/blob - server.c
Merge branch 'crypt' into next
[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  *      - Forward error correction: \ref fec.c
63  */
64
65 #include <signal.h>
66 #include <dirent.h>
67 #include <sys/time.h>
68 #include <openssl/rc4.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 "vss.h"
79 #include "config.h"
80 #include "close_on_fork.h"
81 #include "list.h"
82 #include "send.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
92 /** Define the array of error lists needed by para_server. */
93 INIT_SERVER_ERRLISTS;
94
95 /** Shut down non-authorized connections after that many seconds. */
96 #define ALARM_TIMEOUT 10
97
98 /**
99  * Pointer to shared memory area for communication between para_server
100  * and its children. Exported to vss.c. command.c and to afs.
101  */
102 struct misc_meta_data *mmd;
103
104 /**
105  * The configuration of para_server
106  *
107  * It also contains the options for the audio file selector, audio format
108  * handler and all supported senders.
109  */
110 struct server_args_info conf;
111
112 /** A random value used in child context for authentication. */
113 uint32_t afs_socket_cookie;
114
115 /** The mutex protecting the shared memory area containing the mmd struct. */
116 int mmd_mutex;
117
118 /** The file containing user information (public key, permissions). */
119 static char *user_list_file = NULL;
120
121
122 /** The task responsible for server command handling. */
123 struct server_command_task {
124         /** TCP port on which para_server listens for connections. */
125         int listen_fd;
126         /** Copied from para_server's main function. */
127         int argc;
128         /** Argument vector passed to para_server's main function. */
129         char **argv;
130         /** The command task structure for scheduling. */
131         struct task task;
132 };
133
134 static int want_colors(void)
135 {
136         if (conf.color_arg == color_arg_no)
137                 return 0;
138         if (conf.color_arg == color_arg_yes)
139                 return 1;
140         if (conf.logfile_given)
141                 return 0;
142         return isatty(STDERR_FILENO);
143 }
144
145 static void init_colors_or_die(void)
146 {
147         int ret, i;
148
149         if (!want_colors())
150                 return;
151         daemon_set_flag(DF_COLOR_LOG);
152         daemon_set_default_log_colors();
153         for (i = 0; i < conf.log_color_given; i++) {
154                 ret = daemon_set_log_color(conf.log_color_arg[i]);
155                 if (ret < 0)
156                         exit(EXIT_FAILURE);
157         }
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         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, struct task *t)
276 {
277         struct signal_task *st = container_of(t, struct signal_task, task);
278
279         if (!FD_ISSET(st->fd, &s->rfds))
280                 return;
281
282         st->signum = para_next_signal();
283         switch (st->signum) {
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", st->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                 free(mmd->afd.afhi.info_string);
324                 close_listed_fds();
325                 mutex_destroy(mmd_mutex);
326                 shm_detach(mmd);
327                 exit(EXIT_FAILURE);
328         }
329 }
330
331 static void init_signal_task(void)
332 {
333         static struct signal_task signal_task_struct,
334                 *st = &signal_task_struct;
335
336         st->task.pre_select = signal_pre_select;
337         st->task.post_select = signal_post_select;
338         sprintf(st->task.status, "signal task");
339
340         PARA_NOTICE_LOG("setting up signal handling\n");
341         st->fd = para_signal_init(); /* always successful */
342         para_install_sighandler(SIGINT);
343         para_install_sighandler(SIGTERM);
344         para_install_sighandler(SIGHUP);
345         para_install_sighandler(SIGCHLD);
346         para_sigaction(SIGPIPE, SIG_IGN);
347         add_close_on_fork_list(st->fd);
348         register_task(&st->task);
349 }
350
351 static void command_pre_select(struct sched *s, struct task *t)
352 {
353         struct server_command_task *sct = container_of(t, struct server_command_task, task);
354         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
355 }
356
357 static void command_post_select(struct sched *s, struct task *t)
358 {
359         struct server_command_task *sct = container_of(t, struct server_command_task, task);
360
361         int new_fd, ret, i;
362         char *peer_name;
363         pid_t child_pid;
364         uint32_t *chunk_table;
365         char *info_string;
366
367         if (!FD_ISSET(sct->listen_fd, &s->rfds))
368                 return;
369         ret = para_accept(sct->listen_fd, NULL, 0);
370         if (ret < 0)
371                 goto out;
372         new_fd = ret;
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         /* The chunk table and the info_string are pointers located in the
378          * mmd struct that point to dynamically allocated memory that must be
379          * freed by the parent and the child. However, as the mmd struct is in
380          * a shared memory area, there's no guarantee that after the fork these
381          * pointers are still valid in child context. As these two pointers are
382          * not used in the child anyway, we save them to local variables and
383          * free the memory via that copy in the child.
384          */
385         info_string = mmd->afd.afhi.info_string;
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;
396         }
397         /* mmd might already have changed at this point */
398         free(info_string);
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         return handle_connect(new_fd, peer_name);
411 out:
412         if (ret < 0)
413                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
414 }
415
416 static void init_server_command_task(int argc, char **argv)
417 {
418         int ret;
419         static struct server_command_task server_command_task_struct,
420                 *sct = &server_command_task_struct;
421
422         PARA_NOTICE_LOG("initializing tcp command socket\n");
423         sct->task.pre_select = command_pre_select;
424         sct->task.post_select = command_post_select;
425         sct->argc = argc;
426         sct->argv = argv;
427         ret = para_listen(AF_UNSPEC, IPPROTO_TCP, conf.port_arg);
428         if (ret < 0)
429                 goto err;
430         sct->listen_fd = ret;
431         ret = mark_fd_nonblocking(sct->listen_fd);
432         if (ret < 0)
433                 goto err;
434         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
435         register_task(&sct->task);
436         return;
437 err:
438         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
439         exit(EXIT_FAILURE);
440 }
441
442 static int init_afs(void)
443 {
444         int ret, afs_server_socket[2];
445
446         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
447         if (ret < 0)
448                 exit(EXIT_FAILURE);
449         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
450                 sizeof(afs_socket_cookie));
451         mmd->afs_pid = fork();
452         if (mmd->afs_pid < 0)
453                 exit(EXIT_FAILURE);
454         if (!mmd->afs_pid) { /* child (afs) */
455                 close(afs_server_socket[0]);
456                 afs_init(afs_socket_cookie, afs_server_socket[1]);
457         }
458         close(afs_server_socket[1]);
459         ret = mark_fd_nonblocking(afs_server_socket[0]);
460         if (ret < 0)
461                 exit(EXIT_FAILURE);
462         add_close_on_fork_list(afs_server_socket[0]);
463         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
464                 afs_server_socket[0], (unsigned) afs_socket_cookie);
465         return afs_server_socket[0];
466 }
467
468 __noreturn static void tmp_sigchld_handler(__a_unused int s)
469 {
470         PARA_EMERG_LOG("caught early SIGCHLD\n");
471         exit(EXIT_FAILURE);
472 }
473
474 static void server_init(int argc, char **argv)
475 {
476         struct server_cmdline_parser_params params = {
477                 .override = 0,
478                 .initialize = 1,
479                 .check_required = 0,
480                 .check_ambiguity = 0,
481                 .print_errors = 1
482         };
483         int afs_socket;
484
485         valid_fd_012();
486         init_random_seed_or_die();
487         /* parse command line options */
488         server_cmdline_parser_ext(argc, argv, &conf, &params);
489         HANDLE_VERSION_FLAG("server", conf);
490         drop_privileges_or_die(conf.user_arg, conf.group_arg);
491         /* parse config file, open log and set defaults */
492         parse_config_or_die(0);
493         log_welcome("para_server");
494         init_ipc_or_die(); /* init mmd struct and mmd->lock */
495         /* make sure, the global now pointer is uptodate */
496         gettimeofday(now, NULL);
497         server_uptime(UPTIME_SET); /* reset server uptime */
498         init_user_list(user_list_file);
499         /* become daemon */
500         if (conf.daemon_given)
501                 daemonize();
502         PARA_NOTICE_LOG("initializing audio format handlers\n");
503         afh_init();
504
505         /*
506          * Although afs uses its own signal handling we must ignore SIGUSR1
507          * _before_ the afs child process gets born by init_afs() below.  It's
508          * racy to do this in the child because the parent might send SIGUSR1
509          * before the child gets a chance to ignore this signal -- only the
510          * good die young.
511          */
512         para_sigaction(SIGUSR1, SIG_IGN);
513         /*
514          * We have to install a SIGCHLD handler before the afs process is being
515          * forked off. Otherwise, para_server does not notice if afs dies before
516          * the SIGCHLD handler has been installed by init_signal_task() below.
517          */
518         para_sigaction(SIGCHLD, tmp_sigchld_handler);
519         PARA_NOTICE_LOG("initializing the audio file selector\n");
520         afs_socket = init_afs();
521         init_signal_task();
522         PARA_NOTICE_LOG("initializing virtual streaming system\n");
523         init_vss_task(afs_socket);
524         init_server_command_task(argc, argv);
525         PARA_NOTICE_LOG("server init complete\n");
526 }
527
528 static void status_refresh(void)
529 {
530         static int prev_uptime = -1, prev_events = -1;
531         int uptime = server_uptime(UPTIME_GET), ret = 1;
532
533         if (prev_events != mmd->events)
534                 goto out;
535         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
536                 goto out_inc_events;
537         if (uptime / 60 != prev_uptime / 60)
538                 goto out_inc_events;
539         return;
540 out_inc_events:
541         mmd->events++;
542 out:
543         prev_uptime = uptime;
544         prev_events = mmd->events;
545         mmd->vss_status_flags = mmd->new_vss_status_flags;
546         if (ret) {
547                 PARA_DEBUG_LOG("%d events, forcing status update\n",
548                         mmd->events);
549                 killpg(0, SIGUSR1);
550         }
551 }
552
553 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
554                 struct timeval *timeout_tv)
555 {
556         int ret;
557
558         status_refresh();
559         mutex_unlock(mmd_mutex);
560         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
561         mutex_lock(mmd_mutex);
562         return ret;
563 }
564
565 /**
566  * The main function of para_server.
567  *
568  * \param argc Usual argument count.
569  * \param argv Usual argument vector.
570  *
571  * \return EXIT_SUCCESS or EXIT_FAILURE.
572  */
573 int main(int argc, char *argv[])
574 {
575         int ret;
576         static struct sched s = {
577                 .default_timeout = {
578                         .tv_sec = 1,
579                         .tv_usec = 0
580                 },
581                 .select_function = server_select
582         };
583         server_init(argc, argv);
584         mutex_lock(mmd_mutex);
585         ret = schedule(&s);
586         if (ret < 0) {
587                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
588                 exit(EXIT_FAILURE);
589         }
590         exit(EXIT_SUCCESS);
591 }