Kill mmd_lock() and mmd_unlock().
[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 static pid_t afs_pid;
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 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 = 1
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 (afs_pid)
264 kill(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 != 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 afs_pid = fork();
452 if (afs_pid < 0)
453 exit(EXIT_FAILURE);
454 if (!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 mmd->server_pid = getpid();
497 init_signal_task();
498 PARA_NOTICE_LOG("initializing the audio file selector\n");
499 afs_socket = init_afs();
500 PARA_NOTICE_LOG("initializing virtual streaming system\n");
501 init_vss_task(afs_socket);
502 init_server_command_task(argc, argv);
503 PARA_NOTICE_LOG("server init complete\n");
504 }
505
506 static void status_refresh(void)
507 {
508 static int prev_uptime = -1, prev_events = -1;
509 int uptime = server_uptime(UPTIME_GET), ret = 1;
510
511 if (prev_events != mmd->events)
512 goto out;
513 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
514 goto out_inc_events;
515 if (uptime / 60 != prev_uptime / 60)
516 goto out_inc_events;
517 return;
518 out_inc_events:
519 mmd->events++;
520 out:
521 prev_uptime = uptime;
522 prev_events = mmd->events;
523 mmd->vss_status_flags = mmd->new_vss_status_flags;
524 if (ret) {
525 PARA_DEBUG_LOG("%d events, forcing status update\n",
526 mmd->events);
527 killpg(0, SIGUSR1);
528 }
529 }
530
531 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
532 struct timeval *timeout_tv)
533 {
534 int ret;
535
536 status_refresh();
537 mutex_unlock(mmd_mutex);
538 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
539 mutex_lock(mmd_mutex);
540 return ret;
541 }
542
543 /**
544 * The main function of para_server.
545 *
546 * \param argc Usual argument count.
547 * \param argv Usual argument vector.
548 *
549 * \return EXIT_SUCCESS or EXIT_FAILURE.
550 */
551 int main(int argc, char *argv[])
552 {
553 int ret;
554 static struct sched s = {
555 .default_timeout = {
556 .tv_sec = 1,
557 .tv_usec = 0
558 },
559 .select_function = server_select
560 };
561 server_init(argc, argv);
562 mutex_lock(mmd_mutex);
563 ret = schedule(&s);
564 if (ret < 0) {
565 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
566 exit(EXIT_FAILURE);
567 }
568 exit(EXIT_SUCCESS);
569 }