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