introduce para_select()
[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 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 "db.h"
34 #include "server.h"
35 #include "afs.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
46 /** define the array of error lists needed by para_server */
47 INIT_SERVER_ERRLISTS;
48
49 /** shut down non-authorized connections after that many seconds */
50 #define ALARM_TIMEOUT 10
51
52 /* these are exported to afs.c. command.c and to all selectors */
53 struct misc_meta_data *mmd;
54 /** the configuration of para_server
55 *
56 * It also contains the options for all audio file selectors and all supported
57 * senders.
58 */
59 struct gengetopt_args_info conf;
60 char *user_list = NULL;
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 extern struct audio_format afl[];
65
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 if (!logfile) {
139 if (ll < WARNING)
140 outfd = stdout;
141 else
142 outfd = stderr;
143 } else
144 outfd = logfile;
145 if (conf.daemon_given && !logfile)
146 return;
147 time(&t1);
148 tm = localtime(&t1);
149 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
150 fprintf(outfd, "%s ", str);
151 if (conf.loglevel_arg <= INFO)
152 fprintf(outfd, "%i: ", ll);
153 mypid = getpid();
154 if (conf.loglevel_arg <= INFO)
155 fprintf(outfd, "(%d) ", mypid);
156 va_start(argp, fmt);
157 vfprintf(outfd, fmt, argp);
158 va_end(argp);
159 }
160
161 /*
162 * setup shared memory area and get mutex for locking
163 */
164 static void shm_init(void)
165 {
166 void *shm;
167 int ret = shm_new(sizeof(struct misc_meta_data));
168
169 if (ret < 0)
170 goto err_out;
171
172 ret = shm_attach(ret, ATTACH_RW, &shm);
173 if (ret < 0)
174 goto err_out;
175 mmd = shm;
176 mmd_shm_id = ret;
177
178 ret = mutex_new();
179 if (ret < 0)
180 goto err_out;
181 mmd_mutex = ret;
182
183 mmd->selector_num = 0;
184 mmd->num_played = 0;
185 mmd->num_commands = 0;
186 mmd->events = 0;
187 mmd->num_connects = 0;
188 mmd->active_connections = 0;
189 strcpy(mmd->filename, "(none)");
190 mmd->audio_format = -1;
191 mmd->afs_status_flags = AFS_NEXT;
192 mmd->new_afs_status_flags = AFS_NEXT;
193 mmd->sender_cmd_data.cmd_num = -1;
194 return;
195 err_out:
196 PARA_EMERG_LOG("%s", PARA_STRERROR(-ret));
197 exit(EXIT_FAILURE);
198 }
199
200 /**
201 * lock the shared memory area containing the mmd struct
202 *
203 * \sa semop(2), struct misc_meta_data
204 */
205 void mmd_lock(void)
206 {
207 mutex_lock(mmd_mutex);
208 }
209
210 /**
211 * unlock the shared memory area containing the mmd struct
212 *
213 * \sa semop(2), struct misc_meta_data
214 */
215
216 void mmd_unlock(void)
217 {
218 mutex_unlock(mmd_mutex);
219 }
220
221 static void parse_config(int override)
222 {
223 char *home = para_homedir();
224 struct stat statbuf;
225 int ret;
226 char *cf;
227
228 if (conf.config_file_given)
229 cf = conf.config_file_arg;
230 else
231 cf = make_message("%s/.paraslash/server.conf", home);
232 free(user_list);
233 if (!conf.user_list_given)
234 user_list = make_message("%s/.paraslash/server.users", home);
235 else
236 user_list = para_strdup(conf.user_list_arg);
237 ret = stat(cf, &statbuf);
238 if (ret && conf.config_file_given) {
239 ret = -1;
240 PARA_EMERG_LOG("can not stat config file %s\n", cf);
241 goto out;
242 }
243 if (!ret) {
244 int tmp = conf.daemon_given;
245 cmdline_parser_configfile(cf, &conf, override, 0, 0);
246 conf.daemon_given = tmp;
247 }
248 /* logfile */
249 if (!conf.logfile_given && conf.daemon_given) {
250 ret = -1;
251 PARA_EMERG_LOG("%s", "daemon, but no log file\n");
252 goto out;
253 }
254 if (conf.logfile_given)
255 logfile = open_log(conf.logfile_arg);
256 ret = 1;
257 out:
258 free(cf);
259 free(home);
260 if (ret > 0)
261 return;
262 free(user_list);
263 user_list = NULL;
264 exit(EXIT_FAILURE);
265 }
266
267 static void setup_signal_handling(void)
268 {
269 int ret = 0;
270
271 signal_pipe = para_signal_init();
272 // fcntl(signal_pipe, F_SETFL, O_NONBLOCK);
273 PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
274 ret += para_install_sighandler(SIGINT);
275 ret += para_install_sighandler(SIGTERM);
276 ret += para_install_sighandler(SIGHUP);
277 ret += para_install_sighandler(SIGCHLD);
278 ret += para_install_sighandler(SIGUSR1);
279 signal(SIGPIPE, SIG_IGN);
280 if (ret != 5) {
281 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
282 exit(EXIT_FAILURE);
283 }
284 }
285
286 static void init_selector(void)
287 {
288 int i, ret;
289
290 mmd->selector_change = -1; /* no change nec., set to new num by com_chs */
291 if (!conf.selector_given)
292 goto random;
293 for (i = 0; selectors[i].name; i++) {
294 if (strcmp(selectors[i].name, conf.selector_arg))
295 continue;
296 PARA_NOTICE_LOG("initializing %s audio file selector\n",
297 selectors[i].name);
298 ret = selectors[i].init(&selectors[i]);
299 if (ret < 0) {
300 PARA_WARNING_LOG("%s", PARA_STRERROR(-ret));
301 break;
302 }
303 mmd->selector_num = i;
304 return;
305 }
306 PARA_WARNING_LOG("%s", "falling back to the random selector\n");
307 random:
308 mmd->selector_num = 0;
309 selectors[0].init(&selectors[0]); /* always successful */
310 }
311
312 static unsigned init_network(void)
313 {
314 int sockfd = init_tcp_socket(conf.port_arg);
315
316 if (sockfd < 0)
317 exit(EXIT_FAILURE);
318 return sockfd;
319 }
320
321 static void init_random_seed(void)
322 {
323 int fd, ret = -1, len = sizeof(unsigned int);
324 unsigned int seed;
325
326 fd = open("/dev/urandom", O_RDONLY);
327 if (fd < 0)
328 goto out;
329 ret = -2;
330 if (read(fd, &seed, len) != len)
331 goto out;
332 srandom(seed);
333 ret = 1;
334 out:
335 if (fd >= 0)
336 close(fd);
337 if (ret > 0)
338 return;
339 PARA_EMERG_LOG("can not seed pseudo random generator (ret = %d)\n",
340 ret);
341 exit(EXIT_FAILURE);
342 }
343
344 static unsigned do_inits(int argc, char **argv)
345 {
346 /* connector's address information */
347 int sockfd;
348
349 init_random_seed();
350 /* parse command line options */
351 cmdline_parser(argc, argv, &conf);
352 para_drop_privileges(conf.user_arg);
353 /* parse config file, open log and set defaults */
354 parse_config(0);
355 log_welcome("para_server", conf.loglevel_arg);
356 shm_init(); /* init mmd struct */
357 server_uptime(UPTIME_SET); /* reset server uptime */
358 /* become daemon */
359 if (conf.daemon_given)
360 daemon_init();
361 init_selector();
362 PARA_NOTICE_LOG("%s", "initializing audio file sender\n");
363 /* audio file sender */
364 afs_init();
365 mmd->server_pid = getpid();
366 setup_signal_handling();
367 mmd_lock();
368 /* init network socket */
369 PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
370 sockfd = init_network();
371 if (conf.autoplay_given) {
372 mmd->afs_status_flags |= AFS_PLAYING;
373 mmd->new_afs_status_flags |= AFS_PLAYING;
374 }
375 PARA_NOTICE_LOG("%s", "init complete\n");
376 return sockfd;
377 }
378
379 static void change_selector(void)
380 {
381 int ret, old = mmd->selector_num, new = mmd->selector_change;
382
383 selectors[old].shutdown();
384 ret = selectors[new].init(&selectors[new]);
385 mmd->selector_change = -1; /* reset */
386 if (ret >= 0) {
387 mmd->selector_num = new;
388 return;
389 }
390 /* init failed */
391 PARA_ERROR_LOG("%s -- switching to the random selector\n", PARA_STRERROR(-ret));
392 selectors[0].init(&selectors[0]);
393 mmd->selector_num = 0;
394 }
395
396 /*
397 * called when server gets SIGHUP or when client invokes hup command.
398 */
399 static void handle_sighup(void)
400 {
401 PARA_NOTICE_LOG("%s", "SIGHUP\n");
402 close_log(logfile); /* gets reopened if necessary by parse_config */
403 logfile = NULL;
404 parse_config(1); /* reopens log */
405 mmd->selector_change = mmd->selector_num; /* do not change selector.. */
406 change_selector(); /* .. just reload */
407 }
408
409 static void status_refresh(void)
410 {
411 static int prev_uptime = -1, prev_events = -1;
412 int uptime = server_uptime(UPTIME_GET), ret = 1;
413
414 if (prev_events != mmd->events)
415 goto out;
416 if (mmd->new_afs_status_flags != mmd->afs_status_flags)
417 goto out;
418 if (uptime / 60 != prev_uptime / 60)
419 goto out;
420 ret = 0;
421 out:
422 prev_uptime = uptime;
423 prev_events = mmd->events;
424 mmd->afs_status_flags = mmd->new_afs_status_flags;
425 if (ret) {
426 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
427 mmd->events, mmd->audio_format);
428 killpg(0, SIGUSR1);
429 }
430 }
431
432 /*
433 * MAIN
434 */
435 int main(int argc, char *argv[])
436 {
437 /* listen on sock_fd, new connection on new_fd */
438 int sockfd, new_fd;
439 struct sockaddr_in their_addr;
440 int i, max_fileno, ret;
441 pid_t chld_pid;
442 fd_set rfds, wfds;
443 struct timeval *timeout;
444
445 valid_fd_012();
446 sockfd = do_inits(argc, argv);
447 repeat:
448 /* check socket and signal pipe in any case */
449 FD_ZERO(&rfds);
450 FD_ZERO(&wfds);
451 FD_SET(sockfd, &rfds);
452 max_fileno = sockfd;
453 FD_SET(signal_pipe, &rfds);
454 max_fileno = MAX(max_fileno, signal_pipe);
455
456 timeout = afs_preselect();
457 status_refresh();
458 for (i = 0; senders[i].name; i++) {
459 if (senders[i].status != SENDER_ON)
460 continue;
461 if (!senders[i].pre_select)
462 continue;
463 senders[i].pre_select(mmd->audio_format >= 0?
464 &afl[mmd->audio_format] : NULL,
465 &max_fileno,
466 &rfds, &wfds);
467 }
468 if (selectors[mmd->selector_num].pre_select) {
469 ret = selectors[mmd->selector_num].pre_select(&rfds, &wfds);
470 max_fileno = MAX(max_fileno, ret);
471 }
472 mmd_unlock();
473 ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
474 mmd_lock();
475 if (mmd->selector_change >= 0)
476 change_selector();
477 if (selectors[mmd->selector_num].post_select)
478 selectors[mmd->selector_num].post_select(&rfds, &wfds);
479 if (ret < 0)
480 goto repeat;
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 selectors[mmd->selector_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 }