Add a .gitignore 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
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                 afs_init(afs_socket_cookie, afs_server_socket[1]);
368         close(afs_server_socket[1]);
369         afs_socket = afs_server_socket[0];
370         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n", afs_socket,
371                 (unsigned) afs_socket_cookie);
372 }
373
374
375 static unsigned do_inits(int argc, char **argv)
376 {
377         /* connector's address information */
378         int sockfd;
379
380         init_random_seed();
381         /* parse command line options */
382         server_cmdline_parser(argc, argv, &conf);
383         HANDLE_VERSION_FLAG("server", conf);
384         para_drop_privileges(conf.user_arg, conf.group_arg);
385         /* parse config file, open log and set defaults */
386         parse_config(0);
387         log_welcome("para_server", conf.loglevel_arg);
388         shm_init(); /* init mmd struct */
389         server_uptime(UPTIME_SET); /* reset server uptime */
390         init_user_list(user_list_file);
391         /* become daemon */
392         if (conf.daemon_given)
393                 daemon_init();
394         init_selector();
395 //      PARA_ERROR_LOG("num: %d\n", mmd->selector_num);
396         PARA_NOTICE_LOG("%s", "initializing virtual streaming system\n");
397         vss_init();
398         mmd->server_pid = getpid();
399         setup_signal_handling();
400         init_afs();
401         mmd_lock();
402         /* init network socket */
403         PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
404         sockfd = init_network();
405         PARA_NOTICE_LOG("%s", "init complete\n");
406         return sockfd;
407 }
408
409 static void change_selector(void)
410 {
411         int ret, old = mmd->selector_num, new = mmd->selector_change;
412
413         selectors[old].shutdown();
414         ret = selectors[new].init(&selectors[new]);
415         mmd->selector_change = -1; /* reset */
416         if (ret >= 0) {
417                 mmd->selector_num = new;
418                 return;
419         }
420         /* init failed */
421         PARA_ERROR_LOG("%s -- switching to the random selector\n", PARA_STRERROR(-ret));
422         selectors[0].init(&selectors[0]);
423         mmd->selector_num = 0;
424 }
425
426 /*
427  * called when server gets SIGHUP or when client invokes hup command.
428  */
429 static void handle_sighup(void)
430 {
431         PARA_NOTICE_LOG("%s", "SIGHUP\n");
432         close_log(logfile); /* gets reopened if necessary by parse_config */
433         logfile = NULL;
434         parse_config(1); /* reopens log */
435         mmd->selector_change = mmd->selector_num; /* do not change selector.. */
436         change_selector(); /* .. just reload */
437         init_user_list(user_list_file); /* reload user list */
438 }
439
440 static void status_refresh(void)
441 {
442         static int prev_uptime = -1, prev_events = -1;
443         int uptime = server_uptime(UPTIME_GET), ret = 1;
444
445         if (prev_events != mmd->events)
446                 goto out;
447         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
448                 goto out;
449         if (uptime / 60 != prev_uptime / 60)
450                 goto out;
451         ret = 0;
452 out:
453         prev_uptime = uptime;
454         prev_events = mmd->events;
455         mmd->vss_status_flags = mmd->new_vss_status_flags;
456         if (ret) {
457                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
458                         mmd->events, mmd->audio_format);
459                 killpg(0, SIGUSR1);
460         }
461 }
462
463 /**
464  * the main function of para_server
465  *
466  * \param argc usual argument count
467  * \param argv usual argument vector
468  *
469  * \return EXIT_SUCCESS or EXIT_FAILURE
470  *
471  */
472 int main(int argc, char *argv[])
473 {
474         /* listen on sock_fd, new connection on new_fd */
475         int sockfd, new_fd;
476         struct sockaddr_in their_addr;
477         int i, max_fileno, ret;
478         pid_t chld_pid;
479         fd_set rfds, wfds;
480         struct timeval *timeout;
481
482         valid_fd_012();
483         sockfd = do_inits(argc, argv);
484 repeat:
485         FD_ZERO(&rfds);
486         FD_ZERO(&wfds);
487         max_fileno = -1;
488         /* check socket and signal pipe in any case */
489         para_fd_set(sockfd, &rfds, &max_fileno);
490         para_fd_set(signal_pipe, &rfds, &max_fileno);
491         timeout = vss_preselect();
492         status_refresh();
493         for (i = 0; senders[i].name; i++) {
494                 if (senders[i].status != SENDER_ON)
495                         continue;
496                 if (!senders[i].pre_select)
497                         continue;
498                 senders[i].pre_select( &max_fileno, &rfds, &wfds);
499         }
500         if (selectors[mmd->selector_num].pre_select) {
501                 ret = selectors[mmd->selector_num].pre_select(&rfds, &wfds);
502                 max_fileno = PARA_MAX(max_fileno, ret);
503         }
504         mmd_unlock();
505         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
506         mmd_lock();
507         if (mmd->selector_change >= 0)
508                 change_selector();
509         if (selectors[mmd->selector_num].post_select)
510                 selectors[mmd->selector_num].post_select(&rfds, &wfds);
511         if (ret < 0)
512                 goto repeat;
513         for (i = 0; senders[i].name; i++) {
514                 if (senders[i].status != SENDER_ON)
515                         continue;
516                 if (!senders[i].post_select)
517                         continue;
518                 senders[i].post_select(&rfds, &wfds);
519         }
520         vss_send_chunk();
521         status_refresh();
522         if (FD_ISSET(signal_pipe, &rfds)) {
523                 int sig;
524                 pid_t pid;
525                 sig = para_next_signal();
526                 switch (sig) {
527                 case SIGHUP:
528                         handle_sighup();
529                         break;
530                 case SIGCHLD:
531                         for (;;) {
532                                 pid = para_reap_child();
533                                 if (pid <= 0)
534                                         break;
535                                 if (pid != afs_pid)
536                                         continue;
537                                 PARA_EMERG_LOG("fatal: afs died\n");
538                                 goto genocide;
539                         }
540                         break;
541                 /* die on sigint/sigterm. Kill all children too. */
542                 case SIGINT:
543                 case SIGTERM:
544                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
545 genocide:
546                         kill(0, SIGTERM);
547                         selectors[mmd->selector_num].shutdown();
548                         mutex_destroy(mmd_mutex);
549                         shm_detach(mmd);
550                         shm_destroy(mmd_shm_id);
551
552                         exit(EXIT_FAILURE);
553                 }
554         }
555         if (mmd->sender_cmd_data.cmd_num >= 0) {
556                 int num = mmd->sender_cmd_data.cmd_num,
557                         s = mmd->sender_cmd_data.sender_num;
558
559                 if (senders[s].client_cmds[num])
560                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
561                 mmd->sender_cmd_data.cmd_num = -1;
562         }
563         if (!FD_ISSET(sockfd, &rfds))
564                 goto repeat;
565
566         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
567         if (new_fd < 0)
568                 goto repeat;
569         PARA_INFO_LOG("got connection from %s, forking\n",
570                 inet_ntoa(their_addr.sin_addr));
571         mmd->num_connects++;
572         mmd->active_connections++;
573         random();
574         chld_pid = fork();
575         if (chld_pid < 0) {
576                 PARA_CRIT_LOG("%s", "fork failed\n");
577                 goto repeat;
578         }
579         if (chld_pid) {
580                 close(new_fd);
581                 /* parent keeps accepting connections */
582                 goto repeat;
583         }
584         alarm(ALARM_TIMEOUT);
585         close_listed_fds();
586         close(sockfd); /* child doesn't need the listener */
587         /*
588          * put info on who we are serving into argv[0] to make
589          * client ip visible in top/ps
590          */
591         for (i = argc - 1; i >= 0; i--)
592                 memset(argv[i], 0, strlen(argv[i]));
593         sprintf(argv[0], "para_server (serving %s)",
594                 inet_ntoa(their_addr.sin_addr));
595         return handle_connect(new_fd, &their_addr);
596 }