net: Improve error handling of makesock_addrinfo().
[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 Starting points for getting an overview:
12  *
13  *      - The main programs: \ref server.c, \ref audiod.c, \ref client.c,
14  *        \ref audioc.c, \ref afh.c, \ref play.c,
15  *      - Server: \ref server_command, \ref sender,
16  *      - Audio file selector: \ref audio_format_handler, \ref afs_table,
17  *      - Client: \ref receiver, \ref receiver_node, \ref filter,
18  *        \ref filter_node, \ref writer_node.
19  *
20  *
21  * The gory details, listed by topic:
22  *
23  *      - Audio format handlers: \ref send_common.c \ref mp3_afh.c,
24  *        \ref ogg_afh.c, \ref aac_afh.c, \ref wma_afh.c, \ref spx_afh.c
25  *      - Decoders: \ref mp3dec_filter.c, \ref oggdec_filter.c,
26  *        \ref aacdec_filter.c, \ref wmadec_filter.c, spxdec_filter.c,
27  *        \ref flacdec_filter.c,
28  *      - Volume normalizer: \ref compress_filter.c,
29  *      - Output: \ref alsa_write.c, \ref osx_write.c, \ref oss_write.c,
30  *      - http: \ref http_recv.c, \ref http_send.c,
31  *      - udp: \ref udp_recv.c, \ref udp_send.c,
32  *      - dccp: \ref dccp_recv.c, \ref dccp_send.c,
33  *      - Audio file selector: \ref afs.c, \ref aft.c, \ref mood.c,
34  *      - Afs structures: \ref afs_table, \ref audio_file_data,
35  *        \ref afs_info \ref afh_info,
36  *      - Afs tables: \ref aft.c, \ref mood.c, \ref playlist.c,
37  *        \ref attribute.c, \ref score.c,
38  *      - The virtual streaming system: \ref vss.c, \ref chunk_queue.c.
39  *
40  * Lower levels:
41  *
42  *      - Scheduling: \ref sched.c, \ref sched.h,
43  *      - Networking: \ref net.c,
44  *      - File descriptors: \ref fd.c,
45  *      - Signals: \ref signal.c,
46  *      - Daemons: \ref daemon.c,
47  *      - Strings: \ref string.c, \ref string.h,
48  *      - Time: \ref time.c,
49  *      - Spawning processes: \ref exec.c,
50  *      - Inter process communication: \ref ipc.c,
51  *      - Blob tables: \ref blob.c,
52  *      - The error subsystem: \ref error.h.
53  *      - Access control for paraslash senders: \ref acl.c, \ref acl.h.
54  *      - Internal crypto API: \ref crypt.h.
55  *      - interactive sessions (libreadline): \ref interactive.c.
56  *
57  * Low-level data structures:
58  *
59  *      - Doubly linked lists: \ref list.h,
60  *      - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
61  *      - openssl: \ref crypt.c
62  *      - libgcrypt: \ref gcrypt.c
63  *      - Forward error correction: \ref fec.c.
64  */
65
66 #include <signal.h>
67 #include <regex.h>
68 #include <osl.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 "sched.h"
81 #include "vss.h"
82 #include "config.h"
83 #include "close_on_fork.h"
84 #include "net.h"
85 #include "daemon.h"
86 #include "ipc.h"
87 #include "fd.h"
88 #include "signal.h"
89 #include "user_list.h"
90 #include "color.h"
91 #include "ggo.h"
92 #include "version.h"
93
94 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
95
96 /** Define the array of error lists needed by para_server. */
97 INIT_SERVER_ERRLISTS;
98
99 /** Shut down non-authorized connections after that many seconds. */
100 #define ALARM_TIMEOUT 10
101
102 /**
103  * Pointer to shared memory area for communication between para_server
104  * and its children. Exported to vss.c. command.c and to afs.
105  */
106 struct misc_meta_data *mmd;
107
108 /**
109  * The configuration of para_server
110  *
111  * It also contains the options for the audio file selector, audio format
112  * handler and all supported senders.
113  */
114 struct server_args_info conf;
115
116 /** A random value used in child context for authentication. */
117 uint32_t afs_socket_cookie;
118
119 /** The mutex protecting the shared memory area containing the mmd struct. */
120 int mmd_mutex;
121
122 /** The file containing user information (public key, permissions). */
123 static char *user_list_file = NULL;
124
125 static struct sched sched;
126
127 /** The task responsible for server command handling. */
128 struct server_command_task {
129         /** TCP port on which para_server listens for connections. */
130         int listen_fd;
131         /** Copied from para_server's main function. */
132         int argc;
133         /** Argument vector passed to para_server's main function. */
134         char **argv;
135         /** The command task structure for scheduling. */
136         struct task task;
137 };
138
139 static int want_colors(void)
140 {
141         if (conf.color_arg == color_arg_no)
142                 return 0;
143         if (conf.color_arg == color_arg_yes)
144                 return 1;
145         if (conf.logfile_given)
146                 return 0;
147         return isatty(STDERR_FILENO);
148 }
149
150 static void init_colors_or_die(void)
151 {
152         int i;
153
154         if (!want_colors())
155                 return;
156         daemon_set_flag(DF_COLOR_LOG);
157         daemon_set_default_log_colors();
158         for (i = 0; i < conf.log_color_given; i++)
159                 daemon_set_log_color_or_die(conf.log_color_arg[i]);
160 }
161
162 /*
163  * setup shared memory area and get mutex for locking
164  */
165 static void init_ipc_or_die(void)
166 {
167         void *shm;
168         int shmid, ret = shm_new(sizeof(struct misc_meta_data));
169
170         if (ret < 0)
171                 goto err_out;
172         shmid = ret;
173         ret = shm_attach(shmid, ATTACH_RW, &shm);
174         shm_destroy(shmid);
175         if (ret < 0)
176                 goto err_out;
177         mmd = shm;
178
179         ret = mutex_new();
180         if (ret < 0)
181                 goto err_out;
182         mmd_mutex = ret;
183
184         mmd->num_played = 0;
185         mmd->num_commands = 0;
186         mmd->events = 0;
187         mmd->num_connects = 0;
188         mmd->active_connections = 0;
189         mmd->vss_status_flags = VSS_NEXT;
190         mmd->new_vss_status_flags = VSS_NEXT;
191         return;
192 err_out:
193         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
194         exit(EXIT_FAILURE);
195 }
196
197 /**
198  * (Re-)read the server configuration files.
199  *
200  * \param override Passed to gengetopt to activate the override feature.
201  *
202  * This function also re-opens the logfile and sets the global \a
203  * user_list_file variable.
204  */
205 void parse_config_or_die(int override)
206 {
207         char *home = para_homedir();
208         int ret;
209         char *cf;
210
211         daemon_close_log();
212         if (conf.config_file_given)
213                 cf = para_strdup(conf.config_file_arg);
214         else
215                 cf = make_message("%s/.paraslash/server.conf", home);
216         free(user_list_file);
217         if (!conf.user_list_given)
218                 user_list_file = make_message("%s/.paraslash/server.users", home);
219         else
220                 user_list_file = para_strdup(conf.user_list_arg);
221         ret = file_exists(cf);
222         if (conf.config_file_given && !ret)  {
223                 ret = -1;
224                 PARA_EMERG_LOG("can not read config file %s\n", cf);
225                 goto out;
226         }
227         if (ret) {
228                 int tmp = conf.daemon_given;
229                 struct server_cmdline_parser_params params = {
230                         .override = override,
231                         .initialize = 0,
232                         .check_required = 1,
233                         .check_ambiguity = 0,
234                         .print_errors = !conf.daemon_given
235                 };
236                 server_cmdline_parser_config_file(cf, &conf, &params);
237                 daemon_set_loglevel(conf.loglevel_arg);
238                 conf.daemon_given = tmp;
239         }
240         if (conf.logfile_given) {
241                 daemon_set_logfile(conf.logfile_arg);
242                 daemon_open_log_or_die();
243         }
244         init_colors_or_die();
245         daemon_set_flag(DF_LOG_PID);
246         daemon_set_flag(DF_LOG_LL);
247         daemon_set_flag(DF_LOG_TIME);
248         if (conf.log_timing_given)
249                 daemon_set_flag(DF_LOG_TIMING);
250         ret = 1;
251 out:
252         free(cf);
253         free(home);
254         if (ret > 0)
255                 return;
256         free(user_list_file);
257         user_list_file = NULL;
258         exit(EXIT_FAILURE);
259 }
260
261 static void signal_pre_select(struct sched *s, struct task *t)
262 {
263         struct signal_task *st = container_of(t, struct signal_task, task);
264         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
265 }
266
267 /*
268  * called when server gets SIGHUP or when client invokes hup command.
269  */
270 static void handle_sighup(void)
271 {
272         PARA_NOTICE_LOG("SIGHUP\n");
273         parse_config_or_die(1); /* reopens log */
274         init_user_list(user_list_file); /* reload user list */
275         if (mmd->afs_pid)
276                 kill(mmd->afs_pid, SIGHUP);
277 }
278
279 static int signal_post_select(struct sched *s, __a_unused struct task *t)
280 {
281         int signum = para_next_signal(&s->rfds);
282
283         switch (signum) {
284         case 0:
285                 return 0;
286         case SIGHUP:
287                 handle_sighup();
288                 break;
289         case SIGCHLD:
290                 for (;;) {
291                         pid_t pid;
292                         int ret = para_reap_child(&pid);
293                         if (ret <= 0)
294                                 break;
295                         if (pid != mmd->afs_pid)
296                                 continue;
297                         PARA_EMERG_LOG("fatal: afs died\n");
298                         kill(0, SIGTERM);
299                         goto cleanup;
300                 }
301                 break;
302         /* die on sigint/sigterm. Kill all children too. */
303         case SIGINT:
304         case SIGTERM:
305                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
306                 kill(0, SIGTERM);
307                 /*
308                  * We must wait for afs because afs catches SIGINT/SIGTERM.
309                  * Before reacting to the signal, afs might want to use the
310                  * shared memory area and the mmd mutex.  If we destroy this
311                  * mutex too early and afs tries to lock the shared memory
312                  * area, the call to mutex_lock() will fail and terminate the
313                  * afs process. This leads to dirty osl tables.
314                  *
315                  * There's no such problem with the other children of the
316                  * server process (the command handlers) as these reset their
317                  * SIGINT/SIGTERM handlers to the default action, i.e.  these
318                  * processes get killed immediately by the above kill().
319                  */
320                 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
321                         (int)mmd->afs_pid);
322                 waitpid(mmd->afs_pid, NULL, 0);
323 cleanup:
324                 free(mmd->afd.afhi.chunk_table);
325                 close_listed_fds();
326                 mutex_destroy(mmd_mutex);
327                 shm_detach(mmd);
328                 exit(EXIT_FAILURE);
329         }
330         return 0;
331 }
332
333 static void init_signal_task(void)
334 {
335         static struct signal_task signal_task_struct,
336                 *st = &signal_task_struct;
337
338         st->task.pre_select = signal_pre_select;
339         st->task.post_select = signal_post_select;
340         sprintf(st->task.status, "signal task");
341
342         PARA_NOTICE_LOG("setting up signal handling\n");
343         st->fd = para_signal_init(); /* always successful */
344         para_install_sighandler(SIGINT);
345         para_install_sighandler(SIGTERM);
346         para_install_sighandler(SIGHUP);
347         para_install_sighandler(SIGCHLD);
348         para_sigaction(SIGPIPE, SIG_IGN);
349         add_close_on_fork_list(st->fd);
350         register_task(&sched, &st->task);
351 }
352
353 static void command_pre_select(struct sched *s, struct task *t)
354 {
355         struct server_command_task *sct = container_of(t, struct server_command_task, task);
356         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
357 }
358
359 static int command_post_select(struct sched *s, struct task *t)
360 {
361         struct server_command_task *sct = container_of(t, struct server_command_task, task);
362
363         int new_fd, ret, i;
364         char *peer_name;
365         pid_t child_pid;
366         uint32_t *chunk_table;
367
368         ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
369         if (ret <= 0)
370                 goto out;
371         peer_name = remote_name(new_fd);
372         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
373         mmd->num_connects++;
374         mmd->active_connections++;
375         /*
376          * The chunk table is a pointer located in the mmd struct that points
377          * to dynamically allocated memory, i.e. it must be freed by the parent
378          * and the child. However, as the mmd struct is in a shared memory
379          * area, there's no guarantee that after the fork this pointer is still
380          * valid in child context. As it is not used in the child anyway, we
381          * save it to a local variable before the fork and free the memory via
382          * that copy in the child directly after the fork.
383          */
384         chunk_table = mmd->afd.afhi.chunk_table;
385         child_pid = fork();
386         if (child_pid < 0) {
387                 ret = -ERRNO_TO_PARA_ERROR(errno);
388                 goto out;
389         }
390         if (child_pid) {
391                 /* avoid problems with non-fork-safe PRNGs */
392                 unsigned char buf[16];
393                 get_random_bytes_or_die(buf, sizeof(buf));
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 }