server.c: Init the now timeval early.
[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
89 /** Define the array of error lists needed by para_server. */
90 INIT_SERVER_ERRLISTS;
91
92 /** Shut down non-authorized connections after that many seconds. */
93 #define ALARM_TIMEOUT 10
94
95 /**
96  * Pointer to shared memory area for communication between para_server
97  * and its children. Exported to vss.c. command.c and to afs.
98  */
99 struct misc_meta_data *mmd;
100
101 /**
102  * The configuration of para_server
103  *
104  * It also contains the options for the audio file selector, audio format
105  * handler and all supported senders.
106  */
107 struct server_args_info conf;
108
109 /** A random value used in child context for authentication. */
110 uint32_t afs_socket_cookie;
111
112 /** The mutex protecting the shared memory area containing the mmd struct. */
113 int mmd_mutex;
114
115 /* global variables for server-internal use */
116 static FILE *logfile;
117 /** The file containing user information (public key, permissions). */
118 static char *user_list_file = NULL;
119 static int mmd_shm_id;
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 /**
135  * Para_server's log function.
136  *
137  * \param ll The log level.
138  * \param fmt The format string describing the log message.
139  */
140 __printf_2_3 void para_log(int ll, const char* fmt,...)
141 {
142         va_list argp;
143         FILE *outfd;
144         struct tm *tm;
145         time_t t1;
146         char str[MAXLINE] = "";
147         pid_t mypid;
148
149         if (ll < conf.loglevel_arg)
150                 return;
151         outfd = logfile? logfile : stderr;
152         time(&t1);
153         tm = localtime(&t1);
154         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
155         fprintf(outfd, "%s ", str);
156         if (conf.loglevel_arg <= INFO)
157                 fprintf(outfd, "%i: ", ll);
158         mypid = getpid();
159         if (conf.loglevel_arg <= INFO)
160                 fprintf(outfd, "(%d) ", (int)mypid);
161         va_start(argp, fmt);
162         vfprintf(outfd, fmt, argp);
163         va_end(argp);
164 }
165
166 /*
167  * setup shared memory area and get mutex for locking
168  */
169 static void shm_init(void)
170 {
171         void *shm;
172         int ret = shm_new(sizeof(struct misc_meta_data));
173
174         if (ret < 0)
175                 goto err_out;
176
177         ret = shm_attach(ret, ATTACH_RW, &shm);
178         if (ret < 0)
179                 goto err_out;
180         mmd = shm;
181         mmd_shm_id = ret;
182
183         ret = mutex_new();
184         if (ret < 0)
185                 goto err_out;
186         mmd_mutex = ret;
187
188         mmd->num_played = 0;
189         mmd->num_commands = 0;
190         mmd->events = 0;
191         mmd->num_connects = 0;
192         mmd->active_connections = 0;
193         mmd->vss_status_flags = VSS_NEXT;
194         mmd->new_vss_status_flags = VSS_NEXT;
195         return;
196 err_out:
197         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
198         exit(EXIT_FAILURE);
199 }
200
201 static void parse_config(int override)
202 {
203         char *home = para_homedir();
204         struct stat statbuf;
205         int ret;
206         char *cf;
207
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 = stat(cf, &statbuf);
218         if (ret && conf.config_file_given) {
219                 ret = -1;
220                 PARA_EMERG_LOG("can not stat 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 = 1
231                 };
232                 server_cmdline_parser_config_file(cf, &conf, &params);
233                 conf.daemon_given = tmp;
234         }
235         if (conf.logfile_given)
236                 logfile = open_log(conf.logfile_arg);
237         ret = 1;
238 out:
239         free(cf);
240         free(home);
241         if (ret > 0)
242                 return;
243         free(user_list_file);
244         user_list_file = NULL;
245         exit(EXIT_FAILURE);
246 }
247
248 static void signal_pre_select(struct sched *s, struct task *t)
249 {
250         struct signal_task *st = container_of(t, struct signal_task, task);
251         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
252 }
253
254 /*
255  * called when server gets SIGHUP or when client invokes hup command.
256  */
257 static void handle_sighup(void)
258 {
259         PARA_NOTICE_LOG("SIGHUP\n");
260         close_log(logfile); /* gets reopened if necessary by parse_config */
261         logfile = NULL;
262         parse_config(1); /* reopens log */
263         init_user_list(user_list_file); /* reload user list */
264         if (mmd->afs_pid)
265                 kill(mmd->afs_pid, SIGHUP);
266 }
267
268 static void signal_post_select(struct sched *s, struct task *t)
269 {
270         struct signal_task *st = container_of(t, struct signal_task, task);
271
272         if (!FD_ISSET(st->fd, &s->rfds))
273                 return;
274
275         st->signum = para_next_signal();
276         switch (st->signum) {
277         case SIGHUP:
278                 handle_sighup();
279                 break;
280         case SIGCHLD:
281                 for (;;) {
282                         pid_t pid;
283                         int ret = para_reap_child(&pid);
284                         if (ret <= 0)
285                                 break;
286                         if (pid != mmd->afs_pid)
287                                 continue;
288                         PARA_EMERG_LOG("fatal: afs died\n");
289                         goto genocide;
290                 }
291                 break;
292         /* die on sigint/sigterm. Kill all children too. */
293         case SIGINT:
294         case SIGTERM:
295                 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
296 genocide:
297                 kill(0, SIGTERM);
298                 mutex_destroy(mmd_mutex);
299                 shm_detach(mmd);
300                 shm_destroy(mmd_shm_id);
301
302                 exit(EXIT_FAILURE);
303         }
304 }
305
306 static void init_signal_task(void)
307 {
308         static struct signal_task signal_task_struct,
309                 *st = &signal_task_struct;
310
311         st->task.pre_select = signal_pre_select;
312         st->task.post_select = signal_post_select;
313         sprintf(st->task.status, "signal task");
314
315         st->fd = para_signal_init(); /* always successful */
316
317         PARA_NOTICE_LOG("setting up signal handlers\n");
318         if (para_install_sighandler(SIGINT) < 0)
319                 goto err;
320         if (para_install_sighandler(SIGTERM) < 0)
321                 goto err;
322         if (para_install_sighandler(SIGHUP) < 0)
323                 goto err;
324         if (para_install_sighandler(SIGCHLD) < 0)
325                 goto err;
326         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
327                 goto err;
328         if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
329                 goto err;
330         add_close_on_fork_list(st->fd);
331         register_task(&st->task);
332         return;
333 err:
334         PARA_EMERG_LOG("could not install signal handlers\n");
335         exit(EXIT_FAILURE);
336 }
337
338 static void command_pre_select(struct sched *s, struct task *t)
339 {
340         struct server_command_task *sct = container_of(t, struct server_command_task, task);
341         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
342 }
343
344 static void command_post_select(struct sched *s, struct task *t)
345 {
346         struct server_command_task *sct = container_of(t, struct server_command_task, task);
347
348         int new_fd, ret, i;
349         char *peer_name;
350         pid_t child_pid;
351
352         if (!FD_ISSET(sct->listen_fd, &s->rfds))
353                 return;
354         ret = para_accept(sct->listen_fd, NULL, 0);
355         if (ret < 0)
356                 goto out;
357         new_fd = ret;
358         peer_name = remote_name(new_fd);
359         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
360         mmd->num_connects++;
361         mmd->active_connections++;
362         random();
363         child_pid = fork();
364         if (child_pid < 0) {
365                 ret = -ERRNO_TO_PARA_ERROR(errno);
366                 goto out;
367         }
368         if (child_pid) {
369                 close(new_fd);
370                 /* parent keeps accepting connections */
371                 return;
372         }
373         alarm(ALARM_TIMEOUT);
374         close_listed_fds();
375         para_signal_shutdown();
376         /*
377          * put info on who we are serving into argv[0] to make
378          * client ip visible in top/ps
379          */
380         for (i = sct->argc - 1; i >= 0; i--)
381                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
382         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
383         return handle_connect(new_fd, peer_name);
384 out:
385         if (ret < 0)
386                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
387 }
388
389 static void init_server_command_task(int argc, char **argv)
390 {
391         int ret;
392         static struct server_command_task server_command_task_struct,
393                 *sct = &server_command_task_struct;
394
395         PARA_NOTICE_LOG("initializing tcp command socket\n");
396         sct->task.pre_select = command_pre_select;
397         sct->task.post_select = command_post_select;
398         sct->argc = argc;
399         sct->argv = argv;
400         ret = para_listen(AF_UNSPEC, IPPROTO_TCP, conf.port_arg);
401         if (ret < 0)
402                 goto err;
403         sct->listen_fd = ret;
404         ret = mark_fd_nonblocking(sct->listen_fd);
405         if (ret < 0)
406                 goto err;
407         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
408         register_task(&sct->task);
409         return;
410 err:
411         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
412         exit(EXIT_FAILURE);
413 }
414
415 static void init_random_seed(void)
416 {
417         unsigned int seed;
418         int fd, ret = para_open("/dev/urandom", O_RDONLY, 0);
419
420         if (ret < 0)
421                 goto err;
422         fd = ret;
423         ret = read(fd, &seed, sizeof(seed));
424         if (ret < 0) {
425                 ret = -ERRNO_TO_PARA_ERROR(errno);
426                 goto out;
427         }
428         if (ret != sizeof(seed)) {
429                 ret = -ERRNO_TO_PARA_ERROR(EIO);
430                 goto out;
431         }
432         srandom(seed);
433         ret = 1;
434 out:
435         close(fd);
436         if (ret >= 0)
437                 return;
438 err:
439         PARA_EMERG_LOG("can not seed pseudo random number generator: %s\n",
440                 para_strerror(-ret));
441         exit(EXIT_FAILURE);
442 }
443
444 static int init_afs(void)
445 {
446         int ret, afs_server_socket[2];
447
448         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
449         if (ret < 0)
450                 exit(EXIT_FAILURE);
451         afs_socket_cookie = para_random((uint32_t)-1);
452         mmd->afs_pid = fork();
453         if (mmd->afs_pid < 0)
454                 exit(EXIT_FAILURE);
455         if (!mmd->afs_pid) { /* child (afs) */
456                 close(afs_server_socket[0]);
457                 afs_init(afs_socket_cookie, afs_server_socket[1]);
458         }
459         close(afs_server_socket[1]);
460         ret = mark_fd_nonblocking(afs_server_socket[0]);
461         if (ret < 0)
462                 exit(EXIT_FAILURE);
463         add_close_on_fork_list(afs_server_socket[0]);
464         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
465                 afs_server_socket[0], (unsigned) afs_socket_cookie);
466         return afs_server_socket[0];
467 }
468
469 static void server_init(int argc, char **argv)
470 {
471         struct server_cmdline_parser_params params = {
472                 .override = 0,
473                 .initialize = 1,
474                 .check_required = 0,
475                 .check_ambiguity = 0,
476                 .print_errors = 1
477         };
478         int afs_socket;
479
480         valid_fd_012();
481         init_random_seed();
482         /* parse command line options */
483         server_cmdline_parser_ext(argc, argv, &conf, &params);
484         HANDLE_VERSION_FLAG("server", conf);
485         para_drop_privileges(conf.user_arg, conf.group_arg);
486         /* parse config file, open log and set defaults */
487         parse_config(0);
488         log_welcome("para_server", conf.loglevel_arg);
489         shm_init(); /* init mmd struct */
490         /* make sure, the global now pointer is uptodate */
491         gettimeofday(now, NULL);
492         server_uptime(UPTIME_SET); /* reset server uptime */
493         init_user_list(user_list_file);
494         /* become daemon */
495         if (conf.daemon_given)
496                 daemon_init();
497         PARA_NOTICE_LOG("initializing audio format handlers\n");
498         afh_init();
499         PARA_NOTICE_LOG("initializing the audio file selector\n");
500         afs_socket = init_afs();
501         init_signal_task();
502         PARA_NOTICE_LOG("initializing virtual streaming system\n");
503         init_vss_task(afs_socket);
504         init_server_command_task(argc, argv);
505         PARA_NOTICE_LOG("server init complete\n");
506 }
507
508 static void status_refresh(void)
509 {
510         static int prev_uptime = -1, prev_events = -1;
511         int uptime = server_uptime(UPTIME_GET), ret = 1;
512
513         if (prev_events != mmd->events)
514                 goto out;
515         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
516                 goto out_inc_events;
517         if (uptime / 60 != prev_uptime / 60)
518                 goto out_inc_events;
519         return;
520 out_inc_events:
521         mmd->events++;
522 out:
523         prev_uptime = uptime;
524         prev_events = mmd->events;
525         mmd->vss_status_flags = mmd->new_vss_status_flags;
526         if (ret) {
527                 PARA_DEBUG_LOG("%d events, forcing status update\n",
528                         mmd->events);
529                 killpg(0, SIGUSR1);
530         }
531 }
532
533 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
534                 struct timeval *timeout_tv)
535 {
536         int ret;
537
538         status_refresh();
539         mutex_unlock(mmd_mutex);
540         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
541         mutex_lock(mmd_mutex);
542         return ret;
543 }
544
545 /**
546  * The main function of para_server.
547  *
548  * \param argc Usual argument count.
549  * \param argv Usual argument vector.
550  *
551  * \return EXIT_SUCCESS or EXIT_FAILURE.
552  */
553 int main(int argc, char *argv[])
554 {
555         int ret;
556         static struct sched s = {
557                 .default_timeout = {
558                         .tv_sec = 1,
559                         .tv_usec = 0
560                 },
561                 .select_function = server_select
562         };
563         server_init(argc, argv);
564         mutex_lock(mmd_mutex);
565         ret = schedule(&s);
566         if (ret < 0) {
567                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
568                 exit(EXIT_FAILURE);
569         }
570         exit(EXIT_SUCCESS);
571 }