dccp_send.c: Minor cleanups.
[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                 struct server_cmdline_parser_params params = {
236                         .override = override,
237                         .initialize = 0,
238                         .check_required = 0,
239                         .check_ambiguity = 0
240                 };
241                 server_cmdline_parser_config_file(cf, &conf, &params);
242                 conf.daemon_given = tmp;
243         }
244         /* logfile */
245         if (!conf.logfile_given && conf.daemon_given) {
246                 ret = -1;
247                 PARA_EMERG_LOG("%s", "daemon, but no log file\n");
248                 goto out;
249         }
250         if (conf.logfile_given)
251                 logfile = open_log(conf.logfile_arg);
252         ret = 1;
253 out:
254         free(cf);
255         free(home);
256         if (ret > 0)
257                 return;
258         free(user_list_file);
259         user_list_file = NULL;
260         exit(EXIT_FAILURE);
261 }
262
263 static void setup_signal_handling(void)
264 {
265         int ret = 0;
266
267         signal_pipe = para_signal_init();
268         PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
269         ret += para_install_sighandler(SIGINT);
270         ret += para_install_sighandler(SIGTERM);
271         ret += para_install_sighandler(SIGHUP);
272         ret += para_install_sighandler(SIGCHLD);
273         ret += para_install_sighandler(SIGUSR1);
274         signal(SIGPIPE, SIG_IGN);
275         if (ret != 5) {
276                 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
277                 exit(EXIT_FAILURE);
278         }
279 }
280
281 static void init_selector(void)
282 {
283         int i, ret;
284
285         mmd->selector_change = -1; /* no change nec., set to new num by com_chs */
286         if (!conf.selector_given)
287                 goto random;
288         for (i = 0; selectors[i].name; i++) {
289                 if (strcmp(selectors[i].name, conf.selector_arg))
290                         continue;
291                 PARA_NOTICE_LOG("initializing %s audio file selector\n",
292                         selectors[i].name);
293                 ret = selectors[i].init(&selectors[i]);
294                 if (ret < 0) {
295                         PARA_WARNING_LOG("%s", PARA_STRERROR(-ret));
296                         break;
297                 }
298                 mmd->selector_num = i;
299                 return;
300         }
301         PARA_WARNING_LOG("%s", "falling back to the random selector\n");
302 random:
303         mmd->selector_num = 0;
304         selectors[0].init(&selectors[0]); /* always successful */
305 }
306
307 static unsigned init_network(void)
308 {
309         int fd, ret = init_tcp_socket(conf.port_arg);
310
311         if (ret < 0)
312                 goto err;
313         fd = ret;
314         ret = mark_fd_nonblock(fd);
315         if (ret < 0)
316                 goto err;
317         return fd;
318 err:
319         PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
320         exit(EXIT_FAILURE);
321 }
322
323 static void init_random_seed(void)
324 {
325         int fd, ret = -1;
326         unsigned int seed;
327         size_t len = sizeof(unsigned int);
328
329         fd = open("/dev/urandom", O_RDONLY);
330         if (fd < 0)
331                 goto out;
332         ret = -2;
333         if (read(fd, &seed, len) != len)
334                 goto out;
335         srandom(seed);
336         ret = 1;
337 out:
338         if (fd >= 0)
339                 close(fd);
340         if (ret > 0)
341                 return;
342         PARA_EMERG_LOG("can not seed pseudo random generator (ret = %d)\n",
343                 ret);
344         exit(EXIT_FAILURE);
345 }
346
347 static unsigned do_inits(int argc, char **argv)
348 {
349         /* connector's address information */
350         int sockfd;
351
352         init_random_seed();
353         /* parse command line options */
354         server_cmdline_parser(argc, argv, &conf);
355         HANDLE_VERSION_FLAG("server", conf);
356         para_drop_privileges(conf.user_arg, conf.group_arg);
357         /* parse config file, open log and set defaults */
358         parse_config(0);
359         log_welcome("para_server", conf.loglevel_arg);
360         shm_init(); /* init mmd struct */
361         server_uptime(UPTIME_SET); /* reset server uptime */
362         init_user_list(user_list_file);
363         /* become daemon */
364         if (conf.daemon_given)
365                 daemon_init();
366         init_selector();
367 //      PARA_ERROR_LOG("num: %d\n", mmd->selector_num);
368         PARA_NOTICE_LOG("%s", "initializing virtual streaming system\n");
369         vss_init();
370         mmd->server_pid = getpid();
371         setup_signal_handling();
372         mmd_lock();
373         /* init network socket */
374         PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
375         sockfd = init_network();
376         PARA_NOTICE_LOG("%s", "init complete\n");
377         return sockfd;
378 }
379
380 static void change_selector(void)
381 {
382         int ret, old = mmd->selector_num, new = mmd->selector_change;
383
384         selectors[old].shutdown();
385         ret = selectors[new].init(&selectors[new]);
386         mmd->selector_change = -1; /* reset */
387         if (ret >= 0) {
388                 mmd->selector_num = new;
389                 return;
390         }
391         /* init failed */
392         PARA_ERROR_LOG("%s -- switching to the random selector\n", PARA_STRERROR(-ret));
393         selectors[0].init(&selectors[0]);
394         mmd->selector_num = 0;
395 }
396
397 /*
398  * called when server gets SIGHUP or when client invokes hup command.
399  */
400 static void handle_sighup(void)
401 {
402         PARA_NOTICE_LOG("%s", "SIGHUP\n");
403         close_log(logfile); /* gets reopened if necessary by parse_config */
404         logfile = NULL;
405         parse_config(1); /* reopens log */
406         mmd->selector_change = mmd->selector_num; /* do not change selector.. */
407         change_selector(); /* .. just reload */
408         init_user_list(user_list_file); /* reload user list */
409 }
410
411 static void status_refresh(void)
412 {
413         static int prev_uptime = -1, prev_events = -1;
414         int uptime = server_uptime(UPTIME_GET), ret = 1;
415
416         if (prev_events != mmd->events)
417                 goto out;
418         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
419                 goto out;
420         if (uptime / 60 != prev_uptime / 60)
421                 goto out;
422         ret = 0;
423 out:
424         prev_uptime = uptime;
425         prev_events = mmd->events;
426         mmd->vss_status_flags = mmd->new_vss_status_flags;
427         if (ret) {
428                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
429                         mmd->events, mmd->audio_format);
430                 killpg(0, SIGUSR1);
431         }
432 }
433
434 /**
435  * the main function of para_server
436  *
437  * \param argc usual argument count
438  * \param argv usual argument vector
439  *
440  * \return EXIT_SUCCESS or EXIT_FAILURE
441  *
442  */
443 int main(int argc, char *argv[])
444 {
445         /* listen on sock_fd, new connection on new_fd */
446         int sockfd, new_fd;
447         struct sockaddr_in their_addr;
448         int i, max_fileno, ret;
449         pid_t chld_pid;
450         fd_set rfds, wfds;
451         struct timeval *timeout;
452
453         valid_fd_012();
454         sockfd = do_inits(argc, argv);
455 repeat:
456         FD_ZERO(&rfds);
457         FD_ZERO(&wfds);
458         max_fileno = -1;
459         /* check socket and signal pipe in any case */
460         para_fd_set(sockfd, &rfds, &max_fileno);
461         para_fd_set(signal_pipe, &rfds, &max_fileno);
462         timeout = vss_preselect();
463         status_refresh();
464         for (i = 0; senders[i].name; i++) {
465                 if (senders[i].status != SENDER_ON)
466                         continue;
467                 if (!senders[i].pre_select)
468                         continue;
469                 senders[i].pre_select( &max_fileno, &rfds, &wfds);
470         }
471         if (selectors[mmd->selector_num].pre_select) {
472                 ret = selectors[mmd->selector_num].pre_select(&rfds, &wfds);
473                 max_fileno = PARA_MAX(max_fileno, ret);
474         }
475         mmd_unlock();
476         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
477         mmd_lock();
478         if (mmd->selector_change >= 0)
479                 change_selector();
480         if (selectors[mmd->selector_num].post_select)
481                 selectors[mmd->selector_num].post_select(&rfds, &wfds);
482         if (ret < 0)
483                 goto repeat;
484         for (i = 0; senders[i].name; i++) {
485                 if (senders[i].status != SENDER_ON)
486                         continue;
487                 if (!senders[i].post_select)
488                         continue;
489                 senders[i].post_select(&rfds, &wfds);
490         }
491         vss_send_chunk();
492         status_refresh();
493         if (FD_ISSET(signal_pipe, &rfds)) {
494                 int sig;
495                 sig = para_next_signal();
496                 switch (sig) {
497                 case SIGHUP:
498                         handle_sighup();
499                         break;
500                 case SIGCHLD:
501                         para_reap_children();
502                         break;
503                 /* die on sigint/sigterm. Kill all children too. */
504                 case SIGINT:
505                 case SIGTERM:
506                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
507                         kill(0, SIGTERM);
508                         selectors[mmd->selector_num].shutdown();
509                         mutex_destroy(mmd_mutex);
510                         shm_detach(mmd);
511                         shm_destroy(mmd_shm_id);
512                         exit(EXIT_FAILURE);
513                 }
514         }
515         if (mmd->sender_cmd_data.cmd_num >= 0) {
516                 int num = mmd->sender_cmd_data.cmd_num,
517                         s = mmd->sender_cmd_data.sender_num;
518
519                 if (senders[s].client_cmds[num])
520                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
521                 mmd->sender_cmd_data.cmd_num = -1;
522         }
523         if (!FD_ISSET(sockfd, &rfds))
524                 goto repeat;
525
526         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
527         if (new_fd < 0)
528                 goto repeat;
529         PARA_INFO_LOG("got connection from %s, forking\n",
530                 inet_ntoa(their_addr.sin_addr));
531         mmd->num_connects++;
532         mmd->active_connections++;
533         random();
534         chld_pid = fork();
535         if (chld_pid < 0) {
536                 PARA_CRIT_LOG("%s", "fork failed\n");
537                 goto repeat;
538         }
539         if (chld_pid) {
540                 close(new_fd);
541                 /* parent keeps accepting connections */
542                 goto repeat;
543         }
544         alarm(ALARM_TIMEOUT);
545         close_listed_fds();
546         close(sockfd); /* child doesn't need the listener */
547         /*
548          * put info on who we are serving into argv[0] to make
549          * client ip visible in top/ps
550          */
551         for (i = argc - 1; i >= 0; i--)
552                 memset(argv[i], 0, strlen(argv[i]));
553         sprintf(argv[0], "para_server (serving %s)",
554                 inet_ntoa(their_addr.sin_addr));
555         return handle_connect(new_fd, &their_addr);
556 }