]> git.tuebingen.mpg.de Git - paraslash.git/blob - server.c
7da05898b69b528563fc0e902f0568c0728752a8
[paraslash.git] / server.c
1 /*
2  * Copyright (C) 1997-2008 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  *      - The main programs: \ref server.c, \ref audiod.c, \ref client.c,
16  *        \ref audioc.c, \ref fsck.c,
17  *      - Server: \ref server_command, \ref sender,
18  *      - Audio file selector: \ref audio_format_handler, \ref mood, \ref afs_table,
19  *      - Client: \ref receiver, \ref receiver_node, \ref filter, \ref filter_node.
20  *
21  *
22  * The gory details, listed by topic:
23  *
24  *      - Audio format handlers: \ref mp3_afh.c, \ref ogg_afh.c, \ref aac_afh.c,
25  *      - Decoders: \ref mp3dec.c, \ref oggdec.c, \ref aacdec.c,
26  *      - Volume normalizer: \ref compress.c,
27  *      - Output: \ref alsa_write.c, \ref osx_write.c,
28  *      - http: \ref http_recv.c, \ref http_send.c,
29  *      - ortp: \ref ortp_recv.c, \ref ortp_send.c,
30  *      - dccp: \ref dccp_recv.c, \ref dccp_send.c,
31  *      - Audio file selector: \ref afs.c, \ref aft.c, \ref mood.c,
32  *      - Afs structures: \ref afs_table, \ref audio_file_data,
33  *        \ref afs_info \ref afh_info,
34  *      - Afs tables: \ref aft.c, \ref mood.c, \ref playlist.c,
35  *        \ref attribute.c, \ref score.c,
36  *      - The virtual streaming system: \ref vss.c, \ref chunk_queue.c.
37  *
38  * Lower levels:
39  *
40  *      - Scheduling: \ref sched.c, \ref sched.h,
41  *      - Networking: \ref net.c,
42  *      - File descriptors: \ref fd.c,
43  *      - Signals: \ref signal.c,
44  *      - Daemons: \ref daemon.c,
45  *      - Strings: \ref string.c, \ref string.h,
46  *      - Time: \ref time.c,
47  *      - Spawning processes: \ref exec.c,
48  *      - Inter process communication: \ref ipc.c,
49  *      - The object storage layer: \ref osl.c,
50  *      - Blob tables: \ref blob.c,
51  *      - The error subssystem: \ref error.h.
52  *      - Access control for paraslash senders: \ref acl.c, \ref acl.h.
53  *
54  * Low-level data structures:
55  *
56  *      - Doubly linked lists: \ref list.h,
57  *      - Red-black trees: \ref rbtree.h, \ref rbtree.c,
58  *      - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
59  *      - Hashing: \ref hash.h, \ref sha1.h, \ref sha1.c,
60  *      - Crypto: \ref crypt.c.
61  *
62  */
63
64 #include <signal.h>
65 #include <dirent.h>
66
67 #include "para.h"
68 #include "error.h"
69 #include "server.cmdline.h"
70 #include "afh.h"
71 #include "string.h"
72 #include "afs.h"
73 #include "server.h"
74 #include "vss.h"
75 #include "config.h"
76 #include "close_on_fork.h"
77 #include "list.h"
78 #include "send.h"
79 #include "net.h"
80 #include "daemon.h"
81 #include "ipc.h"
82 #include "fd.h"
83 #include "sched.h"
84 #include "signal.h"
85 #include "user_list.h"
86
87 /** Define the array of error lists needed by para_server. */
88 INIT_SERVER_ERRLISTS;
89
90 /** Shut down non-authorized connections after that many seconds. */
91 #define ALARM_TIMEOUT 10
92
93 /**
94  * Pointer to shared memory area for communication between para_server
95  * and its children. Exported to vss.c. command.c and to afs.
96  */
97 struct misc_meta_data *mmd;
98
99 /**
100  * The configuration of para_server
101  *
102  * It also contains the options for the audio file selector, audio format
103  * handler and all supported senders.
104  */
105 struct server_args_info conf;
106
107 /** A random value used in child context for authentication. */
108 uint32_t afs_socket_cookie;
109
110 /** The mutex protecting the shared memory area containing the mmd struct. */
111 int mmd_mutex;
112
113 /* global variables for server-internal use */
114 static FILE *logfile;
115 /** The file containing user information (public key, permissions). */
116 static char *user_list_file = NULL;
117 static int mmd_shm_id;
118
119
120 /** The task responsible for server command handling. */
121 struct server_command_task {
122         /** TCP port on which para_server listens for connections. */
123         int listen_fd;
124         /** Copied from para_server's main function. */
125         int argc;
126         /** Argument vector passed to para_server's main function. */
127         char **argv;
128         /** The command task structure for scheduling. */
129         struct task task;
130 };
131
132 /**
133  * Para_server's log function.
134  *
135  * \param ll The log level.
136  * \param fmt The format string describing the log message.
137  */
138 void para_log(int ll, const char* fmt,...)
139 {
140         va_list argp;
141         FILE *outfd;
142         struct tm *tm;
143         time_t t1;
144         char str[MAXLINE] = "";
145         pid_t mypid;
146
147         if (ll < conf.loglevel_arg)
148                 return;
149         outfd = logfile? logfile : stderr;
150         time(&t1);
151         tm = localtime(&t1);
152         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
153         fprintf(outfd, "%s ", str);
154         if (conf.loglevel_arg <= INFO)
155                 fprintf(outfd, "%i: ", ll);
156         mypid = getpid();
157         if (conf.loglevel_arg <= INFO)
158                 fprintf(outfd, "(%d) ", (int)mypid);
159         va_start(argp, fmt);
160         vfprintf(outfd, fmt, argp);
161         va_end(argp);
162 }
163
164 /*
165  * setup shared memory area and get mutex for locking
166  */
167 static void shm_init(void)
168 {
169         void *shm;
170         int ret = shm_new(sizeof(struct misc_meta_data));
171
172         if (ret < 0)
173                 goto err_out;
174
175         ret = shm_attach(ret, ATTACH_RW, &shm);
176         if (ret < 0)
177                 goto err_out;
178         mmd = shm;
179         mmd_shm_id = ret;
180
181         ret = mutex_new();
182         if (ret < 0)
183                 goto err_out;
184         mmd_mutex = ret;
185
186         mmd->num_played = 0;
187         mmd->num_commands = 0;
188         mmd->events = 0;
189         mmd->num_connects = 0;
190         mmd->active_connections = 0;
191         mmd->vss_status_flags = VSS_NEXT;
192         mmd->new_vss_status_flags = VSS_NEXT;
193         return;
194 err_out:
195         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
196         exit(EXIT_FAILURE);
197 }
198
199 static void parse_config(int override)
200 {
201         char *home = para_homedir();
202         struct stat statbuf;
203         int ret;
204         char *cf;
205
206         if (conf.config_file_given)
207                 cf = para_strdup(conf.config_file_arg);
208         else
209                 cf = make_message("%s/.paraslash/server.conf", home);
210         free(user_list_file);
211         if (!conf.user_list_given)
212                 user_list_file = make_message("%s/.paraslash/server.users", home);
213         else
214                 user_list_file = para_strdup(conf.user_list_arg);
215         ret = stat(cf, &statbuf);
216         if (ret && conf.config_file_given) {
217                 ret = -1;
218                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
219                 goto out;
220         }
221         if (!ret) {
222                 int tmp = conf.daemon_given;
223                 struct server_cmdline_parser_params params = {
224                         .override = override,
225                         .initialize = 0,
226                         .check_required = 1,
227                         .check_ambiguity = 0,
228                         .print_errors = 1
229                 };
230                 server_cmdline_parser_config_file(cf, &conf, &params);
231                 conf.daemon_given = tmp;
232         }
233         if (conf.logfile_given)
234                 logfile = open_log(conf.logfile_arg);
235         ret = 1;
236 out:
237         free(cf);
238         free(home);
239         if (ret > 0)
240                 return;
241         free(user_list_file);
242         user_list_file = NULL;
243         exit(EXIT_FAILURE);
244 }
245
246 static void signal_pre_select(struct sched *s, struct task *t)
247 {
248         struct signal_task *st = container_of(t, struct signal_task, task);
249         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
250 }
251
252 /*
253  * called when server gets SIGHUP or when client invokes hup command.
254  */
255 static void handle_sighup(void)
256 {
257         PARA_NOTICE_LOG("SIGHUP\n");
258         close_log(logfile); /* gets reopened if necessary by parse_config */
259         logfile = NULL;
260         parse_config(1); /* reopens log */
261         init_user_list(user_list_file); /* reload user list */
262         if (mmd->afs_pid)
263                 kill(mmd->afs_pid, SIGHUP);
264 }
265
266 static void signal_post_select(struct sched *s, struct task *t)
267 {
268         struct signal_task *st = container_of(t, struct signal_task, task);
269
270         if (!FD_ISSET(st->fd, &s->rfds))
271                 return;
272
273         st->signum = para_next_signal();
274         switch (st->signum) {
275         case SIGHUP:
276                 handle_sighup();
277                 break;
278         case SIGCHLD:
279                 for (;;) {
280                         pid_t pid;
281                         int ret = para_reap_child(&pid);
282                         if (ret <= 0)
283                                 break;
284                         if (pid != mmd->afs_pid)
285                                 continue;
286                         PARA_EMERG_LOG("fatal: afs died\n");
287                         goto genocide;
288                 }
289                 break;
290         /* die on sigint/sigterm. Kill all children too. */
291         case SIGINT:
292         case SIGTERM:
293                 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
294 genocide:
295                 kill(0, SIGTERM);
296                 mutex_destroy(mmd_mutex);
297                 shm_detach(mmd);
298                 shm_destroy(mmd_shm_id);
299
300                 exit(EXIT_FAILURE);
301         }
302 }
303
304 static void init_signal_task(void)
305 {
306         static struct signal_task signal_task_struct,
307                 *st = &signal_task_struct;
308
309         st->task.pre_select = signal_pre_select;
310         st->task.post_select = signal_post_select;
311         sprintf(st->task.status, "signal task");
312
313         st->fd = para_signal_init(); /* always successful */
314
315         PARA_NOTICE_LOG("setting up signal handlers\n");
316         if (para_install_sighandler(SIGINT) < 0)
317                 goto err;
318         if (para_install_sighandler(SIGTERM) < 0)
319                 goto err;
320         if (para_install_sighandler(SIGHUP) < 0)
321                 goto err;
322         if (para_install_sighandler(SIGCHLD) < 0)
323                 goto err;
324         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
325                 goto err;
326         if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
327                 goto err;
328         add_close_on_fork_list(st->fd);
329         register_task(&st->task);
330         return;
331 err:
332         PARA_EMERG_LOG("could not install signal handlers\n");
333         exit(EXIT_FAILURE);
334 }
335
336 static void command_pre_select(struct sched *s, struct task *t)
337 {
338         struct server_command_task *sct = container_of(t, struct server_command_task, task);
339         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
340 }
341
342 static void command_post_select(struct sched *s, struct task *t)
343 {
344         struct server_command_task *sct = container_of(t, struct server_command_task, task);
345
346         int new_fd, ret, i;
347         char *peer_name;
348         pid_t child_pid;
349
350         if (!FD_ISSET(sct->listen_fd, &s->rfds))
351                 return;
352         ret = para_accept(sct->listen_fd, NULL, 0);
353         if (ret < 0)
354                 goto out;
355         new_fd = ret;
356         peer_name = remote_name(new_fd);
357         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
358         mmd->num_connects++;
359         mmd->active_connections++;
360         random();
361         child_pid = fork();
362         if (child_pid < 0) {
363                 ret = -ERRNO_TO_PARA_ERROR(errno);
364                 goto out;
365         }
366         if (child_pid) {
367                 close(new_fd);
368                 /* parent keeps accepting connections */
369                 return;
370         }
371         alarm(ALARM_TIMEOUT);
372         close_listed_fds();
373         para_signal_shutdown();
374         /*
375          * put info on who we are serving into argv[0] to make
376          * client ip visible in top/ps
377          */
378         for (i = sct->argc - 1; i >= 0; i--)
379                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
380         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
381         return handle_connect(new_fd, peer_name);
382 out:
383         if (ret < 0)
384                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
385 }
386
387 static void init_server_command_task(int argc, char **argv)
388 {
389         int ret;
390         static struct server_command_task server_command_task_struct,
391                 *sct = &server_command_task_struct;
392
393         PARA_NOTICE_LOG("initializing tcp command socket\n");
394         sct->task.pre_select = command_pre_select;
395         sct->task.post_select = command_post_select;
396         sct->argc = argc;
397         sct->argv = argv;
398         ret = para_listen(AF_UNSPEC, IPPROTO_TCP, conf.port_arg);
399         if (ret < 0)
400                 goto err;
401         sct->listen_fd = ret;
402         ret = mark_fd_nonblocking(sct->listen_fd);
403         if (ret < 0)
404                 goto err;
405         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
406         register_task(&sct->task);
407         return;
408 err:
409         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
410         exit(EXIT_FAILURE);
411 }
412
413 static void init_random_seed(void)
414 {
415         unsigned int seed;
416         int fd, ret = para_open("/dev/urandom", O_RDONLY, 0);
417
418         if (ret < 0)
419                 goto err;
420         fd = ret;
421         ret = read(fd, &seed, sizeof(seed));
422         if (ret < 0) {
423                 ret = -ERRNO_TO_PARA_ERROR(errno);
424                 goto out;
425         }
426         if (ret != sizeof(seed)) {
427                 ret = -ERRNO_TO_PARA_ERROR(EIO);
428                 goto out;
429         }
430         srandom(seed);
431         ret = 1;
432 out:
433         close(fd);
434         if (ret >= 0)
435                 return;
436 err:
437         PARA_EMERG_LOG("can not seed pseudo random number generator: %s\n",
438                 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         afs_socket_cookie = para_random((uint32_t)-1);
450         mmd->afs_pid = fork();
451         if (mmd->afs_pid < 0)
452                 exit(EXIT_FAILURE);
453         if (!mmd->afs_pid) { /* child (afs) */
454                 close(afs_server_socket[0]);
455                 afs_init(afs_socket_cookie, afs_server_socket[1]);
456         }
457         close(afs_server_socket[1]);
458         ret = mark_fd_nonblocking(afs_server_socket[0]);
459         if (ret < 0)
460                 exit(EXIT_FAILURE);
461         add_close_on_fork_list(afs_server_socket[0]);
462         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
463                 afs_server_socket[0], (unsigned) afs_socket_cookie);
464         return afs_server_socket[0];
465 }
466
467 static void server_init(int argc, char **argv)
468 {
469         struct server_cmdline_parser_params params = {
470                 .override = 0,
471                 .initialize = 1,
472                 .check_required = 0,
473                 .check_ambiguity = 0,
474                 .print_errors = 1
475         };
476         int afs_socket;
477
478         valid_fd_012();
479         init_random_seed();
480         /* parse command line options */
481         server_cmdline_parser_ext(argc, argv, &conf, &params);
482         HANDLE_VERSION_FLAG("server", conf);
483         para_drop_privileges(conf.user_arg, conf.group_arg);
484         /* parse config file, open log and set defaults */
485         parse_config(0);
486         log_welcome("para_server", conf.loglevel_arg);
487         shm_init(); /* init mmd struct */
488         server_uptime(UPTIME_SET); /* reset server uptime */
489         init_user_list(user_list_file);
490         /* become daemon */
491         if (conf.daemon_given)
492                 daemon_init();
493         PARA_NOTICE_LOG("initializing audio format handlers\n");
494         afh_init();
495         init_signal_task();
496         PARA_NOTICE_LOG("initializing the audio file selector\n");
497         afs_socket = init_afs();
498         PARA_NOTICE_LOG("initializing virtual streaming system\n");
499         init_vss_task(afs_socket);
500         init_server_command_task(argc, argv);
501         PARA_NOTICE_LOG("server init complete\n");
502 }
503
504 static void status_refresh(void)
505 {
506         static int prev_uptime = -1, prev_events = -1;
507         int uptime = server_uptime(UPTIME_GET), ret = 1;
508
509         if (prev_events != mmd->events)
510                 goto out;
511         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
512                 goto out_inc_events;
513         if (uptime / 60 != prev_uptime / 60)
514                 goto out_inc_events;
515         return;
516 out_inc_events:
517         mmd->events++;
518 out:
519         prev_uptime = uptime;
520         prev_events = mmd->events;
521         mmd->vss_status_flags = mmd->new_vss_status_flags;
522         if (ret) {
523                 PARA_DEBUG_LOG("%d events, forcing status update\n",
524                         mmd->events);
525                 killpg(0, SIGUSR1);
526         }
527 }
528
529 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
530                 struct timeval *timeout_tv)
531 {
532         int ret;
533
534         status_refresh();
535         mutex_unlock(mmd_mutex);
536         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
537         mutex_lock(mmd_mutex);
538         return ret;
539 }
540
541 /**
542  * The main function of para_server.
543  *
544  * \param argc Usual argument count.
545  * \param argv Usual argument vector.
546  *
547  * \return EXIT_SUCCESS or EXIT_FAILURE.
548  */
549 int main(int argc, char *argv[])
550 {
551         int ret;
552         static struct sched s = {
553                 .default_timeout = {
554                         .tv_sec = 1,
555                         .tv_usec = 0
556                 },
557                 .select_function = server_select
558         };
559         server_init(argc, argv);
560         mutex_lock(mmd_mutex);
561         ret = schedule(&s);
562         if (ret < 0) {
563                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
564                 exit(EXIT_FAILURE);
565         }
566         exit(EXIT_SUCCESS);
567 }