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