server.c: Introduce server_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
118 /**
119 * para_server's log function
120 *
121 * \param ll the log level
122 * \param fmt the format string describing the log message
123 */
124 void para_log(int ll, const char* fmt,...)
125 {
126 va_list argp;
127 FILE *outfd;
128 struct tm *tm;
129 time_t t1;
130 char str[MAXLINE] = "";
131 pid_t mypid;
132
133 if (ll < conf.loglevel_arg)
134 return;
135 outfd = logfile? logfile : stderr;
136 time(&t1);
137 tm = localtime(&t1);
138 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
139 fprintf(outfd, "%s ", str);
140 if (conf.loglevel_arg <= INFO)
141 fprintf(outfd, "%i: ", ll);
142 mypid = getpid();
143 if (conf.loglevel_arg <= INFO)
144 fprintf(outfd, "(%d) ", (int)mypid);
145 va_start(argp, fmt);
146 vfprintf(outfd, fmt, argp);
147 va_end(argp);
148 }
149
150 /*
151 * setup shared memory area and get mutex for locking
152 */
153 static void shm_init(void)
154 {
155 void *shm;
156 int ret = shm_new(sizeof(struct misc_meta_data));
157
158 if (ret < 0)
159 goto err_out;
160
161 ret = shm_attach(ret, ATTACH_RW, &shm);
162 if (ret < 0)
163 goto err_out;
164 mmd = shm;
165 mmd_shm_id = ret;
166
167 ret = mutex_new();
168 if (ret < 0)
169 goto err_out;
170 mmd_mutex = ret;
171
172 mmd->num_played = 0;
173 mmd->num_commands = 0;
174 mmd->events = 0;
175 mmd->num_connects = 0;
176 mmd->active_connections = 0;
177 mmd->vss_status_flags = VSS_NEXT;
178 mmd->new_vss_status_flags = VSS_NEXT;
179 return;
180 err_out:
181 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
182 exit(EXIT_FAILURE);
183 }
184
185 /**
186 * lock the shared memory area containing the mmd struct
187 *
188 * \sa semop(2), struct misc_meta_data.
189 */
190 void mmd_lock(void)
191 {
192 mutex_lock(mmd_mutex);
193 }
194
195 /**
196 * unlock the shared memory area containing the mmd struct
197 *
198 * \sa semop(2), struct misc_meta_data
199 */
200
201 void mmd_unlock(void)
202 {
203 mutex_unlock(mmd_mutex);
204 }
205
206 static void parse_config(int override)
207 {
208 char *home = para_homedir();
209 struct stat statbuf;
210 int ret;
211 char *cf;
212
213 if (conf.config_file_given)
214 cf = para_strdup(conf.config_file_arg);
215 else
216 cf = make_message("%s/.paraslash/server.conf", home);
217 free(user_list_file);
218 if (!conf.user_list_given)
219 user_list_file = make_message("%s/.paraslash/server.users", home);
220 else
221 user_list_file = para_strdup(conf.user_list_arg);
222 ret = stat(cf, &statbuf);
223 if (ret && conf.config_file_given) {
224 ret = -1;
225 PARA_EMERG_LOG("can not stat config file %s\n", cf);
226 goto out;
227 }
228 if (!ret) {
229 int tmp = conf.daemon_given;
230 struct server_cmdline_parser_params params = {
231 .override = override,
232 .initialize = 0,
233 .check_required = 1,
234 .check_ambiguity = 0,
235 .print_errors = 1
236 };
237 server_cmdline_parser_config_file(cf, &conf, &params);
238 conf.daemon_given = tmp;
239 }
240 if (conf.logfile_given)
241 logfile = open_log(conf.logfile_arg);
242 ret = 1;
243 out:
244 free(cf);
245 free(home);
246 if (ret > 0)
247 return;
248 free(user_list_file);
249 user_list_file = NULL;
250 exit(EXIT_FAILURE);
251 }
252
253 static void setup_signal_handling(void)
254 {
255 signal_pipe = para_signal_init(); /* always successful */
256
257 PARA_NOTICE_LOG("setting up signal handlers\n");
258 if (para_install_sighandler(SIGINT) < 0)
259 goto err;
260 if (para_install_sighandler(SIGTERM) < 0)
261 goto err;
262 if (para_install_sighandler(SIGHUP) < 0)
263 goto err;
264 if (para_install_sighandler(SIGCHLD) < 0)
265 goto err;
266 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
267 goto err;
268 if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
269 goto err;
270 add_close_on_fork_list(signal_pipe);
271 return;
272 err:
273 PARA_EMERG_LOG("could not install signal handlers\n");
274 exit(EXIT_FAILURE);
275 }
276
277 static unsigned init_network(void)
278 {
279 int fd, ret = para_listen(AF_UNSPEC, IPPROTO_TCP, conf.port_arg);
280
281 if (ret < 0)
282 goto err;
283 fd = ret;
284 ret = mark_fd_nonblocking(fd);
285 if (ret < 0)
286 goto err;
287 add_close_on_fork_list(fd); /* child doesn't need the listener */
288 return fd;
289 err:
290 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
291 exit(EXIT_FAILURE);
292 }
293
294 static void init_random_seed(void)
295 {
296 unsigned int seed;
297 int fd, ret = para_open("/dev/urandom", O_RDONLY, 0);
298
299 if (ret < 0)
300 goto err;
301 fd = ret;
302 ret = read(fd, &seed, sizeof(seed));
303 if (ret < 0) {
304 ret = -ERRNO_TO_PARA_ERROR(errno);
305 goto out;
306 }
307 if (ret != sizeof(seed)) {
308 ret = -ERRNO_TO_PARA_ERROR(EIO);
309 goto out;
310 }
311 srandom(seed);
312 ret = 1;
313 out:
314 close(fd);
315 if (ret >= 0)
316 return;
317 err:
318 PARA_EMERG_LOG("can not seed pseudo random number generator: %s\n",
319 para_strerror(-ret));
320 exit(EXIT_FAILURE);
321 }
322
323 uint32_t afs_socket_cookie;
324 int afs_socket;
325 static pid_t afs_pid;
326
327 static void init_afs(void)
328 {
329 int ret, afs_server_socket[2];
330
331 ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
332 if (ret < 0)
333 exit(EXIT_FAILURE);
334 afs_socket_cookie = para_random((uint32_t)-1);
335 afs_pid = fork();
336 if (afs_pid < 0)
337 exit(EXIT_FAILURE);
338 if (!afs_pid) { /* child (afs) */
339 close(afs_server_socket[0]);
340 afs_init(afs_socket_cookie, afs_server_socket[1]);
341 }
342 close(afs_server_socket[1]);
343 afs_socket = afs_server_socket[0];
344 ret = mark_fd_nonblocking(afs_socket);
345 if (ret < 0)
346 exit(EXIT_FAILURE);
347 add_close_on_fork_list(afs_socket);
348 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n", afs_socket,
349 (unsigned) afs_socket_cookie);
350 }
351
352 static unsigned server_init(int argc, char **argv)
353 {
354 /* connector's address information */
355 int sockfd;
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 sockfd = init_network();
389 PARA_NOTICE_LOG("server init complete\n");
390 return sockfd;
391 }
392
393 /*
394 * called when server gets SIGHUP or when client invokes hup command.
395 */
396 static void handle_sighup(void)
397 {
398 PARA_NOTICE_LOG("SIGHUP\n");
399 close_log(logfile); /* gets reopened if necessary by parse_config */
400 logfile = NULL;
401 parse_config(1); /* reopens log */
402 init_user_list(user_list_file); /* reload user list */
403 if (afs_pid)
404 kill(afs_pid, SIGHUP);
405 }
406
407 static void status_refresh(void)
408 {
409 static int prev_uptime = -1, prev_events = -1;
410 int uptime = server_uptime(UPTIME_GET), ret = 1;
411
412 if (prev_events != mmd->events)
413 goto out;
414 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
415 goto out;
416 if (uptime / 60 != prev_uptime / 60)
417 goto out;
418 ret = 0;
419 out:
420 prev_uptime = uptime;
421 prev_events = mmd->events;
422 mmd->vss_status_flags = mmd->new_vss_status_flags;
423 if (ret) {
424 PARA_DEBUG_LOG("%d events, forcing status update\n",
425 mmd->events);
426 killpg(0, SIGUSR1);
427 }
428 }
429
430 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
431 struct timeval *timeout_tv)
432 {
433 int ret;
434
435 status_refresh();
436 mmd_unlock();
437 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
438 mmd_lock();
439 return ret;
440 }
441
442 /**
443 * the main function of para_server
444 *
445 * \param argc usual argument count
446 * \param argv usual argument vector
447 *
448 * \return EXIT_SUCCESS or EXIT_FAILURE
449 *
450 */
451 int main(int argc, char *argv[])
452 {
453 /* listen on sock_fd, new connection on new_fd */
454 int sockfd, new_fd;
455 char *peer_name;
456 int i, max_fileno, ret;
457 pid_t chld_pid;
458 fd_set rfds, wfds;
459 struct timeval *timeout;
460
461 valid_fd_012();
462 sockfd = server_init(argc, argv);
463 repeat:
464 FD_ZERO(&rfds);
465 FD_ZERO(&wfds);
466 max_fileno = -1;
467 /* check socket and signal pipe in any case */
468 para_fd_set(sockfd, &rfds, &max_fileno);
469 para_fd_set(signal_pipe, &rfds, &max_fileno);
470 timeout = vss_preselect(&rfds, &wfds, &max_fileno);
471 server_select(max_fileno + 1, &rfds, &wfds, timeout);
472 vss_post_select(&rfds, &wfds);
473 if (FD_ISSET(signal_pipe, &rfds)) {
474 int sig;
475 pid_t pid;
476 sig = para_next_signal();
477 switch (sig) {
478 case SIGHUP:
479 handle_sighup();
480 break;
481 case SIGCHLD:
482 for (;;) {
483 ret = para_reap_child(&pid);
484 if (ret <= 0)
485 break;
486 if (pid != afs_pid)
487 continue;
488 PARA_EMERG_LOG("fatal: afs died\n");
489 goto genocide;
490 }
491 break;
492 /* die on sigint/sigterm. Kill all children too. */
493 case SIGINT:
494 case SIGTERM:
495 PARA_EMERG_LOG("terminating on signal %d\n", sig);
496 genocide:
497 kill(0, SIGTERM);
498 mutex_destroy(mmd_mutex);
499 shm_detach(mmd);
500 shm_destroy(mmd_shm_id);
501
502 exit(EXIT_FAILURE);
503 }
504 }
505 if (!FD_ISSET(sockfd, &rfds))
506 goto repeat;
507
508 new_fd = para_accept(sockfd, NULL, 0);
509 if (new_fd < 0)
510 goto repeat;
511 peer_name = remote_name(new_fd);
512 PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
513 mmd->num_connects++;
514 mmd->active_connections++;
515 random();
516 chld_pid = fork();
517 if (chld_pid < 0) {
518 PARA_CRIT_LOG("fork failed\n");
519 goto repeat;
520 }
521 if (chld_pid) {
522 close(new_fd);
523 /* parent keeps accepting connections */
524 goto repeat;
525 }
526 alarm(ALARM_TIMEOUT);
527 close_listed_fds();
528 para_signal_shutdown();
529 /*
530 * put info on who we are serving into argv[0] to make
531 * client ip visible in top/ps
532 */
533 for (i = argc - 1; i >= 0; i--)
534 memset(argv[i], 0, strlen(argv[i]));
535 sprintf(argv[0], "para_server (serving %s)", peer_name);
536 return handle_connect(new_fd, peer_name);
537 }