Remove some unnecessary includes.
[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
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 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                 daemon_set_log_color_or_die(conf.log_color_arg[i]);
155 }
156
157 /*
158  * setup shared memory area and get mutex for locking
159  */
160 static void init_ipc_or_die(void)
161 {
162         void *shm;
163         int shmid, ret = shm_new(sizeof(struct misc_meta_data));
164
165         if (ret < 0)
166                 goto err_out;
167         shmid = ret;
168         ret = shm_attach(shmid, ATTACH_RW, &shm);
169         shm_destroy(shmid);
170         if (ret < 0)
171                 goto err_out;
172         mmd = shm;
173
174         ret = mutex_new();
175         if (ret < 0)
176                 goto err_out;
177         mmd_mutex = ret;
178
179         mmd->num_played = 0;
180         mmd->num_commands = 0;
181         mmd->events = 0;
182         mmd->num_connects = 0;
183         mmd->active_connections = 0;
184         mmd->vss_status_flags = VSS_NEXT;
185         mmd->new_vss_status_flags = VSS_NEXT;
186         return;
187 err_out:
188         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
189         exit(EXIT_FAILURE);
190 }
191
192 /**
193  * (Re-)read the server configuration files.
194  *
195  * \param override Passed to gengetopt to activate the override feature.
196  *
197  * This function also re-opens the logfile and sets the global \a
198  * user_list_file variable.
199  */
200 void parse_config_or_die(int override)
201 {
202         char *home = para_homedir();
203         int ret;
204         char *cf;
205
206         daemon_close_log();
207         if (conf.config_file_given)
208                 cf = para_strdup(conf.config_file_arg);
209         else
210                 cf = make_message("%s/.paraslash/server.conf", home);
211         free(user_list_file);
212         if (!conf.user_list_given)
213                 user_list_file = make_message("%s/.paraslash/server.users", home);
214         else
215                 user_list_file = para_strdup(conf.user_list_arg);
216         ret = file_exists(cf);
217         if (conf.config_file_given && !ret)  {
218                 ret = -1;
219                 PARA_EMERG_LOG("can not read config file %s\n", cf);
220                 goto out;
221         }
222         if (ret) {
223                 int tmp = conf.daemon_given;
224                 struct server_cmdline_parser_params params = {
225                         .override = override,
226                         .initialize = 0,
227                         .check_required = 1,
228                         .check_ambiguity = 0,
229                         .print_errors = !conf.daemon_given
230                 };
231                 server_cmdline_parser_config_file(cf, &conf, &params);
232                 conf.daemon_given = tmp;
233         }
234         if (conf.logfile_given) {
235                 daemon_set_logfile(conf.logfile_arg);
236                 daemon_open_log_or_die();
237         }
238         daemon_set_loglevel(conf.loglevel_arg);
239         init_colors_or_die();
240         daemon_set_flag(DF_LOG_PID);
241         daemon_set_flag(DF_LOG_LL);
242         daemon_set_flag(DF_LOG_TIME);
243         if (conf.log_timing_given)
244                 daemon_set_flag(DF_LOG_TIMING);
245         ret = 1;
246 out:
247         free(cf);
248         free(home);
249         if (ret > 0)
250                 return;
251         free(user_list_file);
252         user_list_file = NULL;
253         exit(EXIT_FAILURE);
254 }
255
256 static void signal_pre_select(struct sched *s, struct task *t)
257 {
258         struct signal_task *st = container_of(t, struct signal_task, task);
259         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
260 }
261
262 /*
263  * called when server gets SIGHUP or when client invokes hup command.
264  */
265 static void handle_sighup(void)
266 {
267         PARA_NOTICE_LOG("SIGHUP\n");
268         parse_config_or_die(1); /* reopens log */
269         init_user_list(user_list_file); /* reload user list */
270         if (mmd->afs_pid)
271                 kill(mmd->afs_pid, SIGHUP);
272 }
273
274 static void signal_post_select(struct sched *s, __a_unused struct task *t)
275 {
276         int signum = para_next_signal(&s->rfds);
277
278         switch (signum) {
279         case 0:
280                 return;
281         case SIGHUP:
282                 handle_sighup();
283                 break;
284         case SIGCHLD:
285                 for (;;) {
286                         pid_t pid;
287                         int ret = para_reap_child(&pid);
288                         if (ret <= 0)
289                                 break;
290                         if (pid != mmd->afs_pid)
291                                 continue;
292                         PARA_EMERG_LOG("fatal: afs died\n");
293                         kill(0, SIGTERM);
294                         goto cleanup;
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", signum);
301                 kill(0, SIGTERM);
302                 /*
303                  * We must wait for afs because afs catches SIGINT/SIGTERM.
304                  * Before reacting to the signal, afs might want to use the
305                  * shared memory area and the mmd mutex.  If we destroy this
306                  * mutex too early and afs tries to lock the shared memory
307                  * area, the call to mutex_lock() will fail and terminate the
308                  * afs process. This leads to dirty osl tables.
309                  *
310                  * There's no such problem with the other children of the
311                  * server process (the command handlers) as these reset their
312                  * SIGINT/SIGTERM handlers to the default action, i.e.  these
313                  * processes get killed immediately by the above kill().
314                  */
315                 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
316                         (int)mmd->afs_pid);
317                 waitpid(mmd->afs_pid, NULL, 0);
318 cleanup:
319                 free(mmd->afd.afhi.chunk_table);
320                 close_listed_fds();
321                 mutex_destroy(mmd_mutex);
322                 shm_detach(mmd);
323                 exit(EXIT_FAILURE);
324         }
325 }
326
327 static void init_signal_task(void)
328 {
329         static struct signal_task signal_task_struct,
330                 *st = &signal_task_struct;
331
332         st->task.pre_select = signal_pre_select;
333         st->task.post_select = signal_post_select;
334         sprintf(st->task.status, "signal task");
335
336         PARA_NOTICE_LOG("setting up signal handling\n");
337         st->fd = para_signal_init(); /* always successful */
338         para_install_sighandler(SIGINT);
339         para_install_sighandler(SIGTERM);
340         para_install_sighandler(SIGHUP);
341         para_install_sighandler(SIGCHLD);
342         para_sigaction(SIGPIPE, SIG_IGN);
343         add_close_on_fork_list(st->fd);
344         register_task(&st->task);
345 }
346
347 static void command_pre_select(struct sched *s, struct task *t)
348 {
349         struct server_command_task *sct = container_of(t, struct server_command_task, task);
350         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
351 }
352
353 static void command_post_select(struct sched *s, struct task *t)
354 {
355         struct server_command_task *sct = container_of(t, struct server_command_task, task);
356
357         int new_fd, ret, i;
358         char *peer_name;
359         pid_t child_pid;
360         uint32_t *chunk_table;
361
362         ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
363         if (ret <= 0)
364                 goto out;
365         peer_name = remote_name(new_fd);
366         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
367         mmd->num_connects++;
368         mmd->active_connections++;
369         /*
370          * The chunk table is a pointer located in the mmd struct that points
371          * to dynamically allocated memory, i.e. it must be freed by the parent
372          * and the child. However, as the mmd struct is in a shared memory
373          * area, there's no guarantee that after the fork this pointer is still
374          * valid in child context. As it is not used in the child anyway, we
375          * save it to a local variable before the fork and free the memory via
376          * that copy in the child directly after the fork.
377          */
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(chunk_table);
391         alarm(ALARM_TIMEOUT);
392         close_listed_fds();
393         para_signal_shutdown();
394         /*
395          * put info on who we are serving into argv[0] to make
396          * client ip visible in top/ps
397          */
398         for (i = sct->argc - 1; i >= 0; i--)
399                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
400         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
401         return handle_connect(new_fd, peer_name);
402 out:
403         if (ret < 0)
404                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
405 }
406
407 static void init_server_command_task(int argc, char **argv)
408 {
409         int ret;
410         static struct server_command_task server_command_task_struct,
411                 *sct = &server_command_task_struct;
412
413         PARA_NOTICE_LOG("initializing tcp command socket\n");
414         sct->task.pre_select = command_pre_select;
415         sct->task.post_select = command_post_select;
416         sct->argc = argc;
417         sct->argv = argv;
418         ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
419         if (ret < 0)
420                 goto err;
421         sct->listen_fd = ret;
422         ret = mark_fd_nonblocking(sct->listen_fd);
423         if (ret < 0)
424                 goto err;
425         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
426         sprintf(sct->task.status, "server command task");
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 int init_afs(void)
435 {
436         int ret, afs_server_socket[2];
437         pid_t afs_pid;
438
439         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
440         if (ret < 0)
441                 exit(EXIT_FAILURE);
442         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
443                 sizeof(afs_socket_cookie));
444         afs_pid = fork();
445         if (afs_pid < 0)
446                 exit(EXIT_FAILURE);
447         if (afs_pid == 0) { /* child (afs) */
448                 close(afs_server_socket[0]);
449                 afs_init(afs_socket_cookie, afs_server_socket[1]);
450         }
451         mmd->afs_pid = afs_pid;
452         close(afs_server_socket[1]);
453         ret = mark_fd_nonblocking(afs_server_socket[0]);
454         if (ret < 0)
455                 exit(EXIT_FAILURE);
456         add_close_on_fork_list(afs_server_socket[0]);
457         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
458                 afs_server_socket[0], (unsigned) afs_socket_cookie);
459         return afs_server_socket[0];
460 }
461
462 __noreturn static void tmp_sigchld_handler(__a_unused int s)
463 {
464         PARA_EMERG_LOG("caught early SIGCHLD\n");
465         exit(EXIT_FAILURE);
466 }
467
468 static void server_init(int argc, char **argv)
469 {
470         struct server_cmdline_parser_params params = {
471                 .override = 0,
472                 .initialize = 1,
473                 .check_required = 0,
474                 .check_ambiguity = 0,
475                 .print_errors = 1
476         };
477         int afs_socket;
478
479         valid_fd_012();
480         init_random_seed_or_die();
481         /* parse command line options */
482         server_cmdline_parser_ext(argc, argv, &conf, &params);
483         HANDLE_VERSION_FLAG("server", conf);
484         drop_privileges_or_die(conf.user_arg, conf.group_arg);
485         /* parse config file, open log and set defaults */
486         parse_config_or_die(0);
487         log_welcome("para_server");
488         init_ipc_or_die(); /* init mmd struct and mmd->lock */
489         /* make sure, the global now pointer is uptodate */
490         gettimeofday(now, NULL);
491         server_uptime(UPTIME_SET); /* reset server uptime */
492         init_user_list(user_list_file);
493         /* become daemon */
494         if (conf.daemon_given)
495                 daemonize();
496         PARA_NOTICE_LOG("initializing audio format handlers\n");
497         afh_init();
498
499         /*
500          * Although afs uses its own signal handling we must ignore SIGUSR1
501          * _before_ the afs child process gets born by init_afs() below.  It's
502          * racy to do this in the child because the parent might send SIGUSR1
503          * before the child gets a chance to ignore this signal -- only the
504          * good die young.
505          */
506         para_sigaction(SIGUSR1, SIG_IGN);
507         /*
508          * We have to install a SIGCHLD handler before the afs process is being
509          * forked off. Otherwise, para_server does not notice if afs dies before
510          * the SIGCHLD handler has been installed by init_signal_task() below.
511          */
512         para_sigaction(SIGCHLD, tmp_sigchld_handler);
513         PARA_NOTICE_LOG("initializing the audio file selector\n");
514         afs_socket = init_afs();
515         init_signal_task();
516         PARA_NOTICE_LOG("initializing virtual streaming system\n");
517         init_vss_task(afs_socket);
518         init_server_command_task(argc, argv);
519         PARA_NOTICE_LOG("server init complete\n");
520 }
521
522 static void status_refresh(void)
523 {
524         static int prev_uptime = -1, prev_events = -1;
525         int uptime = server_uptime(UPTIME_GET), ret = 1;
526
527         if (prev_events != mmd->events)
528                 goto out;
529         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
530                 goto out_inc_events;
531         if (uptime / 60 != prev_uptime / 60)
532                 goto out_inc_events;
533         return;
534 out_inc_events:
535         mmd->events++;
536 out:
537         prev_uptime = uptime;
538         prev_events = mmd->events;
539         mmd->vss_status_flags = mmd->new_vss_status_flags;
540         if (ret) {
541                 PARA_DEBUG_LOG("%d events, forcing status update\n",
542                         mmd->events);
543                 killpg(0, SIGUSR1);
544         }
545 }
546
547 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
548                 struct timeval *timeout_tv)
549 {
550         int ret;
551
552         status_refresh();
553         mutex_unlock(mmd_mutex);
554         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
555         mutex_lock(mmd_mutex);
556         return ret;
557 }
558
559 /**
560  * The main function of para_server.
561  *
562  * \param argc Usual argument count.
563  * \param argv Usual argument vector.
564  *
565  * \return EXIT_SUCCESS or EXIT_FAILURE.
566  */
567 int main(int argc, char *argv[])
568 {
569         int ret;
570         static struct sched s = {
571                 .default_timeout = {
572                         .tv_sec = 1,
573                         .tv_usec = 0
574                 },
575                 .select_function = server_select
576         };
577         server_init(argc, argv);
578         mutex_lock(mmd_mutex);
579         ret = schedule(&s);
580         if (ret < 0) {
581                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
582                 exit(EXIT_FAILURE);
583         }
584         exit(EXIT_SUCCESS);
585 }