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