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