audioc: Get rid of the temporary socket file.
[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 "server.cmdline.h"
24 #include "afs_common.h"
25 #include "afh.h"
26 #include "server.h"
27 #include "vss.h"
28 #include "config.h"
29 #include "close_on_fork.h"
30 #include "send.h"
31 #include "error.h"
32 #include "net.h"
33 #include "daemon.h"
34 #include "string.h"
35 #include "ipc.h"
36 #include "fd.h"
37 #include "list.h"
38 #include "sched.h"
39 #include "signal.h"
40 #include "user_list.h"
41 #include "afs.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 static int afs_socket;
356 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 }
448
449 static void status_refresh(void)
450 {
451         static int prev_uptime = -1, prev_events = -1;
452         int uptime = server_uptime(UPTIME_GET), ret = 1;
453
454         if (prev_events != mmd->events)
455                 goto out;
456         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
457                 goto out;
458         if (uptime / 60 != prev_uptime / 60)
459                 goto out;
460         ret = 0;
461 out:
462         prev_uptime = uptime;
463         prev_events = mmd->events;
464         mmd->vss_status_flags = mmd->new_vss_status_flags;
465         if (ret) {
466                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
467                         mmd->events, mmd->audio_format);
468                 killpg(0, SIGUSR1);
469         }
470 }
471
472 /**
473  * the main function of para_server
474  *
475  * \param argc usual argument count
476  * \param argv usual argument vector
477  *
478  * \return EXIT_SUCCESS or EXIT_FAILURE
479  *
480  */
481 int main(int argc, char *argv[])
482 {
483         /* listen on sock_fd, new connection on new_fd */
484         int sockfd, new_fd;
485         struct sockaddr_in their_addr;
486         int i, max_fileno, ret;
487         pid_t chld_pid;
488         fd_set rfds, wfds;
489         struct timeval *timeout;
490
491         valid_fd_012();
492         sockfd = do_inits(argc, argv);
493 repeat:
494         FD_ZERO(&rfds);
495         FD_ZERO(&wfds);
496         max_fileno = -1;
497         /* check socket and signal pipe in any case */
498         para_fd_set(sockfd, &rfds, &max_fileno);
499         para_fd_set(signal_pipe, &rfds, &max_fileno);
500         timeout = vss_preselect();
501         status_refresh();
502         for (i = 0; senders[i].name; i++) {
503                 if (senders[i].status != SENDER_ON)
504                         continue;
505                 if (!senders[i].pre_select)
506                         continue;
507                 senders[i].pre_select( &max_fileno, &rfds, &wfds);
508         }
509         if (selectors[mmd->selector_num].pre_select) {
510                 ret = selectors[mmd->selector_num].pre_select(&rfds, &wfds);
511                 max_fileno = PARA_MAX(max_fileno, ret);
512         }
513         mmd_unlock();
514         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
515         mmd_lock();
516         if (mmd->selector_change >= 0)
517                 change_selector();
518         if (selectors[mmd->selector_num].post_select)
519                 selectors[mmd->selector_num].post_select(&rfds, &wfds);
520         if (ret < 0)
521                 goto repeat;
522         for (i = 0; senders[i].name; i++) {
523                 if (senders[i].status != SENDER_ON)
524                         continue;
525                 if (!senders[i].post_select)
526                         continue;
527                 senders[i].post_select(&rfds, &wfds);
528         }
529         vss_send_chunk();
530         status_refresh();
531         if (FD_ISSET(signal_pipe, &rfds)) {
532                 int sig;
533                 pid_t pid;
534                 sig = para_next_signal();
535                 switch (sig) {
536                 case SIGHUP:
537                         handle_sighup();
538                         break;
539                 case SIGCHLD:
540                         for (;;) {
541                                 pid = para_reap_child();
542                                 if (pid <= 0)
543                                         break;
544                                 if (pid != afs_pid)
545                                         continue;
546                                 PARA_EMERG_LOG("fatal: afs died\n");
547                                 goto genocide;
548                         }
549                         break;
550                 /* die on sigint/sigterm. Kill all children too. */
551                 case SIGINT:
552                 case SIGTERM:
553                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
554 genocide:
555                         kill(0, SIGTERM);
556                         selectors[mmd->selector_num].shutdown();
557                         mutex_destroy(mmd_mutex);
558                         shm_detach(mmd);
559                         shm_destroy(mmd_shm_id);
560
561                         exit(EXIT_FAILURE);
562                 }
563         }
564         if (mmd->sender_cmd_data.cmd_num >= 0) {
565                 int num = mmd->sender_cmd_data.cmd_num,
566                         s = mmd->sender_cmd_data.sender_num;
567
568                 if (senders[s].client_cmds[num])
569                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
570                 mmd->sender_cmd_data.cmd_num = -1;
571         }
572         if (!FD_ISSET(sockfd, &rfds))
573                 goto repeat;
574
575         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
576         if (new_fd < 0)
577                 goto repeat;
578         PARA_INFO_LOG("got connection from %s, forking\n",
579                 inet_ntoa(their_addr.sin_addr));
580         mmd->num_connects++;
581         mmd->active_connections++;
582         random();
583         chld_pid = fork();
584         if (chld_pid < 0) {
585                 PARA_CRIT_LOG("%s", "fork failed\n");
586                 goto repeat;
587         }
588         if (chld_pid) {
589                 close(new_fd);
590                 /* parent keeps accepting connections */
591                 goto repeat;
592         }
593         alarm(ALARM_TIMEOUT);
594         close_listed_fds();
595         close(sockfd); /* child doesn't need the listener */
596         /*
597          * put info on who we are serving into argv[0] to make
598          * client ip visible in top/ps
599          */
600         for (i = argc - 1; i >= 0; i--)
601                 memset(argv[i], 0, strlen(argv[i]));
602         sprintf(argv[0], "para_server (serving %s)",
603                 inet_ntoa(their_addr.sin_addr));
604         return handle_connect(new_fd, &their_addr);
605 }