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