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