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