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