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