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