para_fade: Add description of the three modes of operation.
[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 init_ipc_or_die(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 /**
202  * (Re-)read the server configuration files.
203  *
204  * \param override Passed to gengetopt to activate the override feature.
205  *
206  * This function also re-opens the logfile and sets the global \a
207  * user_list_file variable.
208  */
209 void parse_config_or_die(int override)
210 {
211         char *home = para_homedir();
212         struct stat statbuf;
213         int ret;
214         char *cf;
215
216         close_log(logfile);
217         logfile = NULL;
218         if (conf.config_file_given)
219                 cf = para_strdup(conf.config_file_arg);
220         else
221                 cf = make_message("%s/.paraslash/server.conf", home);
222         free(user_list_file);
223         if (!conf.user_list_given)
224                 user_list_file = make_message("%s/.paraslash/server.users", home);
225         else
226                 user_list_file = para_strdup(conf.user_list_arg);
227         ret = stat(cf, &statbuf);
228         if (ret && conf.config_file_given) {
229                 ret = -1;
230                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
231                 goto out;
232         }
233         if (!ret) {
234                 int tmp = conf.daemon_given;
235                 struct server_cmdline_parser_params params = {
236                         .override = override,
237                         .initialize = 0,
238                         .check_required = 1,
239                         .check_ambiguity = 0,
240                         .print_errors = 1
241                 };
242                 server_cmdline_parser_config_file(cf, &conf, &params);
243                 conf.daemon_given = tmp;
244         }
245         if (conf.logfile_given)
246                 logfile = open_log(conf.logfile_arg);
247         ret = 1;
248 out:
249         free(cf);
250         free(home);
251         if (ret > 0)
252                 return;
253         free(user_list_file);
254         user_list_file = NULL;
255         exit(EXIT_FAILURE);
256 }
257
258 static void signal_pre_select(struct sched *s, struct task *t)
259 {
260         struct signal_task *st = container_of(t, struct signal_task, task);
261         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
262 }
263
264 /*
265  * called when server gets SIGHUP or when client invokes hup command.
266  */
267 static void handle_sighup(void)
268 {
269         PARA_NOTICE_LOG("SIGHUP\n");
270         parse_config_or_die(1); /* reopens log */
271         init_user_list(user_list_file); /* reload user list */
272         if (mmd->afs_pid)
273                 kill(mmd->afs_pid, SIGHUP);
274 }
275
276 static void signal_post_select(struct sched *s, struct task *t)
277 {
278         struct signal_task *st = container_of(t, struct signal_task, task);
279
280         if (!FD_ISSET(st->fd, &s->rfds))
281                 return;
282
283         st->signum = para_next_signal();
284         switch (st->signum) {
285         case SIGHUP:
286                 handle_sighup();
287                 break;
288         case SIGCHLD:
289                 for (;;) {
290                         pid_t pid;
291                         int ret = para_reap_child(&pid);
292                         if (ret <= 0)
293                                 break;
294                         if (pid != mmd->afs_pid)
295                                 continue;
296                         PARA_EMERG_LOG("fatal: afs died\n");
297                         goto genocide;
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 genocide:
305                 kill(0, SIGTERM);
306                 mutex_destroy(mmd_mutex);
307                 shm_detach(mmd);
308                 shm_destroy(mmd_shm_id);
309
310                 exit(EXIT_FAILURE);
311         }
312 }
313
314 static void init_signal_task(void)
315 {
316         static struct signal_task signal_task_struct,
317                 *st = &signal_task_struct;
318
319         st->task.pre_select = signal_pre_select;
320         st->task.post_select = signal_post_select;
321         sprintf(st->task.status, "signal task");
322
323         st->fd = para_signal_init(); /* always successful */
324
325         PARA_NOTICE_LOG("setting up signal handlers\n");
326         if (para_install_sighandler(SIGINT) < 0)
327                 goto err;
328         if (para_install_sighandler(SIGTERM) < 0)
329                 goto err;
330         if (para_install_sighandler(SIGHUP) < 0)
331                 goto err;
332         if (para_install_sighandler(SIGCHLD) < 0)
333                 goto err;
334         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
335                 goto err;
336         if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
337                 goto err;
338         add_close_on_fork_list(st->fd);
339         register_task(&st->task);
340         return;
341 err:
342         PARA_EMERG_LOG("could not install signal handlers\n");
343         exit(EXIT_FAILURE);
344 }
345
346 static void command_pre_select(struct sched *s, struct task *t)
347 {
348         struct server_command_task *sct = container_of(t, struct server_command_task, task);
349         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
350 }
351
352 static void command_post_select(struct sched *s, struct task *t)
353 {
354         struct server_command_task *sct = container_of(t, struct server_command_task, task);
355
356         int new_fd, ret, i;
357         char *peer_name;
358         pid_t child_pid;
359
360         if (!FD_ISSET(sct->listen_fd, &s->rfds))
361                 return;
362         ret = para_accept(sct->listen_fd, NULL, 0);
363         if (ret < 0)
364                 goto out;
365         new_fd = ret;
366         peer_name = remote_name(new_fd);
367         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
368         mmd->num_connects++;
369         mmd->active_connections++;
370         random();
371         child_pid = fork();
372         if (child_pid < 0) {
373                 ret = -ERRNO_TO_PARA_ERROR(errno);
374                 goto out;
375         }
376         if (child_pid) {
377                 close(new_fd);
378                 /* parent keeps accepting connections */
379                 return;
380         }
381         alarm(ALARM_TIMEOUT);
382         close_listed_fds();
383         para_signal_shutdown();
384         /*
385          * put info on who we are serving into argv[0] to make
386          * client ip visible in top/ps
387          */
388         for (i = sct->argc - 1; i >= 0; i--)
389                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
390         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
391         return handle_connect(new_fd, peer_name);
392 out:
393         if (ret < 0)
394                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
395 }
396
397 static void init_server_command_task(int argc, char **argv)
398 {
399         int ret;
400         static struct server_command_task server_command_task_struct,
401                 *sct = &server_command_task_struct;
402
403         PARA_NOTICE_LOG("initializing tcp command socket\n");
404         sct->task.pre_select = command_pre_select;
405         sct->task.post_select = command_post_select;
406         sct->argc = argc;
407         sct->argv = argv;
408         ret = para_listen(AF_UNSPEC, IPPROTO_TCP, conf.port_arg);
409         if (ret < 0)
410                 goto err;
411         sct->listen_fd = ret;
412         ret = mark_fd_nonblocking(sct->listen_fd);
413         if (ret < 0)
414                 goto err;
415         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
416         register_task(&sct->task);
417         return;
418 err:
419         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
420         exit(EXIT_FAILURE);
421 }
422
423 static void init_random_seed(void)
424 {
425         unsigned int seed;
426         int fd, ret = para_open("/dev/urandom", O_RDONLY, 0);
427
428         if (ret < 0)
429                 goto err;
430         fd = ret;
431         ret = read(fd, &seed, sizeof(seed));
432         if (ret < 0) {
433                 ret = -ERRNO_TO_PARA_ERROR(errno);
434                 goto out;
435         }
436         if (ret != sizeof(seed)) {
437                 ret = -ERRNO_TO_PARA_ERROR(EIO);
438                 goto out;
439         }
440         srandom(seed);
441         ret = 1;
442 out:
443         close(fd);
444         if (ret >= 0)
445                 return;
446 err:
447         PARA_EMERG_LOG("can not seed pseudo random number generator: %s\n",
448                 para_strerror(-ret));
449         exit(EXIT_FAILURE);
450 }
451
452 static int init_afs(void)
453 {
454         int ret, afs_server_socket[2];
455
456         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
457         if (ret < 0)
458                 exit(EXIT_FAILURE);
459         afs_socket_cookie = para_random((uint32_t)-1);
460         mmd->afs_pid = fork();
461         if (mmd->afs_pid < 0)
462                 exit(EXIT_FAILURE);
463         if (!mmd->afs_pid) { /* child (afs) */
464                 close(afs_server_socket[0]);
465                 afs_init(afs_socket_cookie, afs_server_socket[1]);
466         }
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 static void server_init(int argc, char **argv)
478 {
479         struct server_cmdline_parser_params params = {
480                 .override = 0,
481                 .initialize = 1,
482                 .check_required = 0,
483                 .check_ambiguity = 0,
484                 .print_errors = 1
485         };
486         int afs_socket;
487
488         valid_fd_012();
489         init_random_seed();
490         /* parse command line options */
491         server_cmdline_parser_ext(argc, argv, &conf, &params);
492         HANDLE_VERSION_FLAG("server", conf);
493         drop_privileges_or_die(conf.user_arg, conf.group_arg);
494         /* parse config file, open log and set defaults */
495         parse_config_or_die(0);
496         log_welcome("para_server", conf.loglevel_arg);
497         init_ipc_or_die(); /* init mmd struct and mmd->lock */
498         /* make sure, the global now pointer is uptodate */
499         gettimeofday(now, NULL);
500         server_uptime(UPTIME_SET); /* reset server uptime */
501         init_user_list(user_list_file);
502         /* become daemon */
503         if (conf.daemon_given)
504                 daemon_init();
505         PARA_NOTICE_LOG("initializing audio format handlers\n");
506         afh_init();
507         PARA_NOTICE_LOG("initializing the audio file selector\n");
508         afs_socket = init_afs();
509         init_signal_task();
510         PARA_NOTICE_LOG("initializing virtual streaming system\n");
511         init_vss_task(afs_socket);
512         init_server_command_task(argc, argv);
513         PARA_NOTICE_LOG("server init complete\n");
514 }
515
516 static void status_refresh(void)
517 {
518         static int prev_uptime = -1, prev_events = -1;
519         int uptime = server_uptime(UPTIME_GET), ret = 1;
520
521         if (prev_events != mmd->events)
522                 goto out;
523         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
524                 goto out_inc_events;
525         if (uptime / 60 != prev_uptime / 60)
526                 goto out_inc_events;
527         return;
528 out_inc_events:
529         mmd->events++;
530 out:
531         prev_uptime = uptime;
532         prev_events = mmd->events;
533         mmd->vss_status_flags = mmd->new_vss_status_flags;
534         if (ret) {
535                 PARA_DEBUG_LOG("%d events, forcing status update\n",
536                         mmd->events);
537                 killpg(0, SIGUSR1);
538         }
539 }
540
541 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
542                 struct timeval *timeout_tv)
543 {
544         int ret;
545
546         status_refresh();
547         mutex_unlock(mmd_mutex);
548         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
549         mutex_lock(mmd_mutex);
550         return ret;
551 }
552
553 /**
554  * The main function of para_server.
555  *
556  * \param argc Usual argument count.
557  * \param argv Usual argument vector.
558  *
559  * \return EXIT_SUCCESS or EXIT_FAILURE.
560  */
561 int main(int argc, char *argv[])
562 {
563         int ret;
564         static struct sched s = {
565                 .default_timeout = {
566                         .tv_sec = 1,
567                         .tv_usec = 0
568                 },
569                 .select_function = server_select
570         };
571         server_init(argc, argv);
572         mutex_lock(mmd_mutex);
573         ret = schedule(&s);
574         if (ret < 0) {
575                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
576                 exit(EXIT_FAILURE);
577         }
578         exit(EXIT_SUCCESS);
579 }