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