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