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