Switch to the new afs.
[paraslash.git] / server.c
1 /*
2 * Copyright (C) 1997-2007 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 /** \mainpage Paraslash API Reference
11 *
12 * Good starting points for reading are probably \ref audio_file_selector,
13 * \ref sender, \ref receiver, \ref receiver_node, \ref filter, \ref
14 * filter_node.
15 *
16 */
17
18 #include <signal.h>
19 #include <sys/types.h>
20 #include <dirent.h>
21
22 #include "para.h"
23 #include "error.h"
24 #include "server.cmdline.h"
25 #include "afs_common.h"
26 #include "afh.h"
27 #include "string.h"
28 #include "afs.h"
29 #include "server.h"
30 #include "vss.h"
31 #include "config.h"
32 #include "close_on_fork.h"
33 #include "send.h"
34 #include "net.h"
35 #include "daemon.h"
36 #include "ipc.h"
37 #include "fd.h"
38 #include "list.h"
39 #include "sched.h"
40 #include "signal.h"
41 #include "user_list.h"
42
43 /** define the array of error lists needed by para_server */
44 INIT_SERVER_ERRLISTS;
45
46 /** shut down non-authorized connections after that many seconds */
47 #define ALARM_TIMEOUT 10
48
49 /**
50 * pointer to shared memory area for communication between para_server
51 * and its children. exported to vss.c. command.c and to all selectors.
52 */
53 struct misc_meta_data *mmd;
54
55 /**
56 * the configuration of para_server
57 *
58 * It also contains the options for all audio file selectors, audio format handler
59 * and all supported senders.
60 */
61 struct server_args_info conf;
62
63 /** the file containing user information (public key, permissions) */
64 char *user_list_file = NULL;
65
66 extern void dccp_send_init(struct sender *);
67 extern void http_send_init(struct sender *);
68 extern void ortp_send_init(struct sender *);
69
70 /* TODO: This is better handled by autoconf */
71 /** the list of supported audio file selectors */
72 struct audio_file_selector selectors[] = {
73 {
74 .name = "random",
75 .init = random_selector_init,
76 .update_audio_file = NULL,
77 },
78 {
79 .name = "playlist",
80 .init = playlist_selector_init,
81 .update_audio_file = NULL,
82 .pre_select = NULL,
83 .post_select = NULL,
84 },
85 #ifdef HAVE_MYSQL
86 {
87 .name = "mysql",
88 .init = mysql_selector_init,
89 .update_audio_file = NULL,
90 .pre_select = NULL,
91 .post_select = NULL,
92 },
93 #endif
94 {
95 .name = NULL,
96 }
97 };
98
99 /** the list of supported senders */
100 struct sender senders[] = {
101 {
102 .name = "http",
103 .init = http_send_init,
104 },
105 {
106 .name = "dccp",
107 .init = dccp_send_init,
108 },
109 #ifdef HAVE_ORTP
110 {
111 .name = "ortp",
112 .init = ortp_send_init,
113 },
114 #endif
115 {
116 .name = NULL,
117 }
118 };
119
120
121 /* global variables for server-internal use */
122 static FILE *logfile;
123 static int mmd_mutex, mmd_shm_id;
124 static int signal_pipe;
125
126 /**
127 * para_server's log function
128 *
129 * \param ll the log level
130 * \param fmt the format string describing the log message
131 */
132 void para_log(int ll, const char* fmt,...)
133 {
134 va_list argp;
135 FILE *outfd;
136 struct tm *tm;
137 time_t t1;
138 char str[MAXLINE] = "";
139 pid_t mypid;
140
141 if (ll < conf.loglevel_arg)
142 return;
143 outfd = logfile? logfile : stderr;
144 time(&t1);
145 tm = localtime(&t1);
146 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
147 fprintf(outfd, "%s ", str);
148 if (conf.loglevel_arg <= INFO)
149 fprintf(outfd, "%i: ", ll);
150 mypid = getpid();
151 if (conf.loglevel_arg <= INFO)
152 fprintf(outfd, "(%d) ", mypid);
153 va_start(argp, fmt);
154 vfprintf(outfd, fmt, argp);
155 va_end(argp);
156 }
157
158 /*
159 * setup shared memory area and get mutex for locking
160 */
161 static void shm_init(void)
162 {
163 void *shm;
164 int ret = shm_new(sizeof(struct misc_meta_data));
165
166 if (ret < 0)
167 goto err_out;
168
169 ret = shm_attach(ret, ATTACH_RW, &shm);
170 if (ret < 0)
171 goto err_out;
172 mmd = shm;
173 mmd_shm_id = ret;
174
175 ret = mutex_new();
176 if (ret < 0)
177 goto err_out;
178 mmd_mutex = ret;
179
180 mmd->selector_num = 0;
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 strcpy(mmd->filename, "(none)");
187 mmd->audio_format = -1;
188 mmd->vss_status_flags = VSS_NEXT;
189 mmd->new_vss_status_flags = VSS_NEXT;
190 mmd->sender_cmd_data.cmd_num = -1;
191 return;
192 err_out:
193 PARA_EMERG_LOG("%s", PARA_STRERROR(-ret));
194 exit(EXIT_FAILURE);
195 }
196
197 /**
198 * lock the shared memory area containing the mmd struct
199 *
200 * \sa semop(2), struct misc_meta_data
201 */
202 void mmd_lock(void)
203 {
204 mutex_lock(mmd_mutex);
205 }
206
207 /**
208 * unlock the shared memory area containing the mmd struct
209 *
210 * \sa semop(2), struct misc_meta_data
211 */
212
213 void mmd_unlock(void)
214 {
215 mutex_unlock(mmd_mutex);
216 }
217
218 static void parse_config(int override)
219 {
220 char *home = para_homedir();
221 struct stat statbuf;
222 int ret;
223 char *cf;
224
225 if (conf.config_file_given)
226 cf = conf.config_file_arg;
227 else
228 cf = make_message("%s/.paraslash/server.conf", home);
229 free(user_list_file);
230 if (!conf.user_list_given)
231 user_list_file = make_message("%s/.paraslash/server.users", home);
232 else
233 user_list_file = para_strdup(conf.user_list_arg);
234 ret = stat(cf, &statbuf);
235 if (ret && conf.config_file_given) {
236 ret = -1;
237 PARA_EMERG_LOG("can not stat config file %s\n", cf);
238 goto out;
239 }
240 if (!ret) {
241 int tmp = conf.daemon_given;
242 struct server_cmdline_parser_params params = {
243 .override = override,
244 .initialize = 0,
245 .check_required = 0,
246 .check_ambiguity = 0
247 };
248 server_cmdline_parser_config_file(cf, &conf, &params);
249 conf.daemon_given = tmp;
250 }
251 /* logfile */
252 if (!conf.logfile_given && conf.daemon_given) {
253 ret = -1;
254 PARA_EMERG_LOG("%s", "daemon, but no log file\n");
255 goto out;
256 }
257 if (conf.logfile_given)
258 logfile = open_log(conf.logfile_arg);
259 ret = 1;
260 out:
261 free(cf);
262 free(home);
263 if (ret > 0)
264 return;
265 free(user_list_file);
266 user_list_file = NULL;
267 exit(EXIT_FAILURE);
268 }
269
270 static void setup_signal_handling(void)
271 {
272 int ret = 0;
273
274 signal_pipe = para_signal_init();
275 PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
276 ret += para_install_sighandler(SIGINT);
277 ret += para_install_sighandler(SIGTERM);
278 ret += para_install_sighandler(SIGHUP);
279 ret += para_install_sighandler(SIGCHLD);
280 ret += para_install_sighandler(SIGUSR1);
281 signal(SIGPIPE, SIG_IGN);
282 if (ret != 5) {
283 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
284 exit(EXIT_FAILURE);
285 }
286 }
287
288 static void init_selector(void)
289 {
290 int i, ret;
291
292 mmd->selector_change = -1; /* no change nec., set to new num by com_chs */
293 if (!conf.selector_given)
294 goto random;
295 for (i = 0; selectors[i].name; i++) {
296 if (strcmp(selectors[i].name, conf.selector_arg))
297 continue;
298 PARA_NOTICE_LOG("initializing %s audio file selector\n",
299 selectors[i].name);
300 ret = selectors[i].init(&selectors[i]);
301 if (ret < 0) {
302 PARA_WARNING_LOG("%s", PARA_STRERROR(-ret));
303 break;
304 }
305 mmd->selector_num = i;
306 return;
307 }
308 PARA_WARNING_LOG("%s", "falling back to the random selector\n");
309 random:
310 mmd->selector_num = 0;
311 selectors[0].init(&selectors[0]); /* always successful */
312 }
313
314 static unsigned init_network(void)
315 {
316 int fd, ret = init_tcp_socket(conf.port_arg);
317
318 if (ret < 0)
319 goto err;
320 fd = ret;
321 ret = mark_fd_nonblock(fd);
322 if (ret < 0)
323 goto err;
324 return fd;
325 err:
326 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
327 exit(EXIT_FAILURE);
328 }
329
330 static void init_random_seed(void)
331 {
332 int fd, ret = -1;
333 unsigned int seed;
334 size_t len = sizeof(unsigned int);
335
336 fd = open("/dev/urandom", O_RDONLY);
337 if (fd < 0)
338 goto out;
339 ret = -2;
340 if (read(fd, &seed, len) != len)
341 goto out;
342 srandom(seed);
343 ret = 1;
344 out:
345 if (fd >= 0)
346 close(fd);
347 if (ret > 0)
348 return;
349 PARA_EMERG_LOG("can not seed pseudo random generator (ret = %d)\n",
350 ret);
351 exit(EXIT_FAILURE);
352 }
353
354 uint32_t afs_socket_cookie;
355 int afs_socket;
356 static pid_t afs_pid;
357
358 static void init_afs(void)
359 {
360 int ret, afs_server_socket[2];
361
362 ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
363 if (ret < 0)
364 exit(EXIT_FAILURE);
365 afs_socket_cookie = para_random((uint32_t)-1);
366 afs_pid = fork();
367 if (afs_pid < 0)
368 exit(EXIT_FAILURE);
369 if (!afs_pid) { /* child (afs) */
370 close(afs_server_socket[0]);
371 afs_init(afs_socket_cookie, afs_server_socket[1]);
372 }
373 close(afs_server_socket[1]);
374 afs_socket = afs_server_socket[0];
375 ret = mark_fd_nonblock(afs_socket);
376 if (ret < 0)
377 exit(EXIT_FAILURE);
378 add_close_on_fork_list(afs_socket);
379 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n", afs_socket,
380 (unsigned) afs_socket_cookie);
381 }
382
383
384 static unsigned do_inits(int argc, char **argv)
385 {
386 /* connector's address information */
387 int sockfd;
388
389 init_random_seed();
390 /* parse command line options */
391 server_cmdline_parser(argc, argv, &conf);
392 HANDLE_VERSION_FLAG("server", conf);
393 para_drop_privileges(conf.user_arg, conf.group_arg);
394 /* parse config file, open log and set defaults */
395 parse_config(0);
396 log_welcome("para_server", conf.loglevel_arg);
397 shm_init(); /* init mmd struct */
398 server_uptime(UPTIME_SET); /* reset server uptime */
399 init_user_list(user_list_file);
400 /* become daemon */
401 if (conf.daemon_given)
402 daemon_init();
403 init_selector();
404 // PARA_ERROR_LOG("num: %d\n", mmd->selector_num);
405 PARA_NOTICE_LOG("%s", "initializing virtual streaming system\n");
406 vss_init();
407 mmd->server_pid = getpid();
408 setup_signal_handling();
409 init_afs();
410 mmd_lock();
411 /* init network socket */
412 PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
413 sockfd = init_network();
414 PARA_NOTICE_LOG("%s", "init complete\n");
415 return sockfd;
416 }
417
418 static void change_selector(void)
419 {
420 int ret, old = mmd->selector_num, new = mmd->selector_change;
421
422 selectors[old].shutdown();
423 ret = selectors[new].init(&selectors[new]);
424 mmd->selector_change = -1; /* reset */
425 if (ret >= 0) {
426 mmd->selector_num = new;
427 return;
428 }
429 /* init failed */
430 PARA_ERROR_LOG("%s -- switching to the random selector\n", PARA_STRERROR(-ret));
431 selectors[0].init(&selectors[0]);
432 mmd->selector_num = 0;
433 }
434
435 /*
436 * called when server gets SIGHUP or when client invokes hup command.
437 */
438 static void handle_sighup(void)
439 {
440 PARA_NOTICE_LOG("%s", "SIGHUP\n");
441 close_log(logfile); /* gets reopened if necessary by parse_config */
442 logfile = NULL;
443 parse_config(1); /* reopens log */
444 mmd->selector_change = mmd->selector_num; /* do not change selector.. */
445 change_selector(); /* .. just reload */
446 init_user_list(user_list_file); /* reload user list */
447 if (afs_pid)
448 kill(afs_pid, SIGHUP);
449 }
450
451 static void status_refresh(void)
452 {
453 static int prev_uptime = -1, prev_events = -1;
454 int uptime = server_uptime(UPTIME_GET), ret = 1;
455
456 if (prev_events != mmd->events)
457 goto out;
458 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
459 goto out;
460 if (uptime / 60 != prev_uptime / 60)
461 goto out;
462 ret = 0;
463 out:
464 prev_uptime = uptime;
465 prev_events = mmd->events;
466 mmd->vss_status_flags = mmd->new_vss_status_flags;
467 if (ret) {
468 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
469 mmd->events, mmd->audio_format);
470 killpg(0, SIGUSR1);
471 }
472 }
473
474 /**
475 * the main function of para_server
476 *
477 * \param argc usual argument count
478 * \param argv usual argument vector
479 *
480 * \return EXIT_SUCCESS or EXIT_FAILURE
481 *
482 */
483 int main(int argc, char *argv[])
484 {
485 /* listen on sock_fd, new connection on new_fd */
486 int sockfd, new_fd;
487 struct sockaddr_in their_addr;
488 int i, max_fileno, ret;
489 pid_t chld_pid;
490 fd_set rfds, wfds;
491 struct timeval *timeout;
492
493 valid_fd_012();
494 sockfd = do_inits(argc, argv);
495 repeat:
496 FD_ZERO(&rfds);
497 FD_ZERO(&wfds);
498 max_fileno = -1;
499 /* check socket and signal pipe in any case */
500 para_fd_set(sockfd, &rfds, &max_fileno);
501 para_fd_set(signal_pipe, &rfds, &max_fileno);
502 timeout = vss_preselect(&rfds, &wfds, &max_fileno);
503 status_refresh();
504 for (i = 0; senders[i].name; i++) {
505 if (senders[i].status != SENDER_ON)
506 continue;
507 if (!senders[i].pre_select)
508 continue;
509 senders[i].pre_select(&max_fileno, &rfds, &wfds);
510 }
511 if (selectors[mmd->selector_num].pre_select) {
512 ret = selectors[mmd->selector_num].pre_select(&rfds, &wfds);
513 max_fileno = PARA_MAX(max_fileno, ret);
514 }
515 mmd_unlock();
516 ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
517 mmd_lock();
518 vss_post_select(&rfds, &wfds);
519 if (mmd->selector_change >= 0)
520 change_selector();
521 if (selectors[mmd->selector_num].post_select)
522 selectors[mmd->selector_num].post_select(&rfds, &wfds);
523 if (ret < 0)
524 goto repeat;
525 for (i = 0; senders[i].name; i++) {
526 if (senders[i].status != SENDER_ON)
527 continue;
528 if (!senders[i].post_select)
529 continue;
530 senders[i].post_select(&rfds, &wfds);
531 }
532 vss_send_chunk();
533 status_refresh();
534 if (FD_ISSET(signal_pipe, &rfds)) {
535 int sig;
536 pid_t pid;
537 sig = para_next_signal();
538 switch (sig) {
539 case SIGHUP:
540 handle_sighup();
541 break;
542 case SIGCHLD:
543 for (;;) {
544 ret = para_reap_child(&pid);
545 if (ret <= 0)
546 break;
547 if (pid != afs_pid)
548 continue;
549 PARA_EMERG_LOG("fatal: afs died\n");
550 goto genocide;
551 }
552 break;
553 /* die on sigint/sigterm. Kill all children too. */
554 case SIGINT:
555 case SIGTERM:
556 PARA_EMERG_LOG("terminating on signal %d\n", sig);
557 genocide:
558 kill(0, SIGTERM);
559 selectors[mmd->selector_num].shutdown();
560 mutex_destroy(mmd_mutex);
561 shm_detach(mmd);
562 shm_destroy(mmd_shm_id);
563
564 exit(EXIT_FAILURE);
565 }
566 }
567 if (mmd->sender_cmd_data.cmd_num >= 0) {
568 int num = mmd->sender_cmd_data.cmd_num,
569 s = mmd->sender_cmd_data.sender_num;
570
571 if (senders[s].client_cmds[num])
572 senders[s].client_cmds[num](&mmd->sender_cmd_data);
573 mmd->sender_cmd_data.cmd_num = -1;
574 }
575 if (!FD_ISSET(sockfd, &rfds))
576 goto repeat;
577
578 new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
579 if (new_fd < 0)
580 goto repeat;
581 PARA_INFO_LOG("got connection from %s, forking\n",
582 inet_ntoa(their_addr.sin_addr));
583 mmd->num_connects++;
584 mmd->active_connections++;
585 random();
586 chld_pid = fork();
587 if (chld_pid < 0) {
588 PARA_CRIT_LOG("%s", "fork failed\n");
589 goto repeat;
590 }
591 if (chld_pid) {
592 close(new_fd);
593 /* parent keeps accepting connections */
594 goto repeat;
595 }
596 alarm(ALARM_TIMEOUT);
597 close_listed_fds();
598 close(sockfd); /* child doesn't need the listener */
599 /*
600 * put info on who we are serving into argv[0] to make
601 * client ip visible in top/ps
602 */
603 for (i = argc - 1; i >= 0; i--)
604 memset(argv[i], 0, strlen(argv[i]));
605 sprintf(argv[0], "para_server (serving %s)",
606 inet_ntoa(their_addr.sin_addr));
607 return handle_connect(new_fd, &their_addr);
608 }