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