]> git.tuebingen.mpg.de Git - paraslash.git/blob - server.c
c46966ea8e2343f38366b14f34d360dce6d67026
[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 dbtool, \ref sender,
25  *  \ref receiver, \ref receiver_node, \ref filter, \ref filter_node.
26  *
27  */
28
29
30
31 #include "server.cmdline.h"
32 #include "db.h"
33 #include "server.h"
34 #include "afs.h"
35 #include "config.h"
36 #include "close_on_fork.h"
37 #include "send.h"
38 #include "error.h"
39 #include "net.h"
40 #include "daemon.h"
41 #include "string.h"
42 #include "ipc.h"
43
44 /** define the array of error lists needed by para_server */
45 INIT_SERVER_ERRLISTS;
46
47 /** shut down non-authorized connections after that many seconds */
48 #define ALARM_TIMEOUT 10
49
50 /* these are exported to afs/command/dbtool */
51 struct misc_meta_data *mmd;
52 /** the configuration of para_server
53  *
54  * It also contains the options for all database tools and all supported
55  * senders.
56 */
57 struct gengetopt_args_info conf;
58 char *user_list = NULL;
59 extern void http_send_init(struct sender *);
60 extern void ortp_send_init(struct sender *);
61 extern struct audio_format afl[];
62
63 /** the list of supported database tools */
64 struct dbtool dblist[] = {
65         {
66                 .name = "random",
67                 .init = random_dbtool_init,
68                 .update_audio_file = NULL,
69         },
70         {
71                 .name = "plm",
72                 .init = plm_dbtool_init,
73                 .update_audio_file = NULL,
74                 .pre_select = NULL,
75                 .post_select = NULL,
76         },
77 #ifdef HAVE_MYSQL
78         {
79                 .name = "mysql",
80                 .init = mysql_dbtool_init,
81                 .update_audio_file = NULL,
82                 .pre_select = NULL,
83                 .post_select = NULL,
84         },
85 #endif
86         {
87                 .name = NULL,
88         }
89 };
90
91 /** the list of supported senders */
92 struct sender senders[] = {
93         {
94                 .name = "http",
95                 .init = http_send_init,
96         },
97 #ifdef HAVE_ORTP
98         {
99                 .name = "ortp",
100                 .init = ortp_send_init,
101         },
102 #endif
103         {
104                 .name = NULL,
105         }
106 };
107
108
109 /* global variables for server-internal use */
110 static FILE *logfile;
111 static int mmd_mutex, mmd_shm_id;
112 static int signal_pipe;
113
114 /**
115  * para_server's log function
116  *
117  * \param ll the log level
118  * \param fmt the format string describing the log message
119  */
120 void para_log(int ll, char* fmt,...)
121 {
122         va_list argp;
123         FILE *outfd;
124         struct tm *tm;
125         time_t t1;
126         char str[MAXLINE] = "";
127         pid_t mypid;
128
129         if (ll < conf.loglevel_arg)
130                 return;
131         if (!logfile) {
132                 if (ll < WARNING)
133                         outfd = stdout;
134                 else
135                         outfd = stderr;
136         } else
137                 outfd = logfile;
138         if (conf.daemon_given && !logfile)
139                 return;
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->dbt_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 //      fcntl(signal_pipe, F_SETFL, O_NONBLOCK);
266         PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
267         ret += para_install_sighandler(SIGINT);
268         ret += para_install_sighandler(SIGTERM);
269         ret += para_install_sighandler(SIGHUP);
270         ret += para_install_sighandler(SIGCHLD);
271         ret += para_install_sighandler(SIGUSR1);
272         signal(SIGPIPE, SIG_IGN);
273         if (ret != 5) {
274                 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
275                 exit(EXIT_FAILURE);
276         }
277 }
278
279 static void init_dbtool(void)
280 {
281         int i;
282
283         mmd->dbt_change = -1; /* no change nec., set to new dbt num by com_cdt */
284         if (!dblist[1].name)
285                 goto random;
286         if (conf.dbtool_given) {
287                 for (i = 0; dblist[i].name; i++) {
288                         if (strcmp(dblist[i].name, conf.dbtool_arg))
289                                 continue;
290                         PARA_NOTICE_LOG("initializing %s database tool\n",
291                                 dblist[i].name);
292                         if (dblist[i].init(&dblist[i]) < 0) {
293                                 PARA_WARNING_LOG("init %s failed",
294                                         dblist[i].name);
295                                 goto random;
296                         }
297                         mmd->dbt_num = i;
298                         return;
299                 }
300                 PARA_WARNING_LOG("%s", "no such dbtool, switching to random\n");
301                 goto random;
302         }
303         /* use the first dbtool that works
304          * (assuming that random always works)
305          */
306         for (i = 1; dblist[i].name; i++) {
307                 int ret = dblist[i].init(&dblist[i]);
308                 if (ret >= 0) {
309                         PARA_INFO_LOG("initialized %s\n", dblist[i].name);
310                         mmd->dbt_num = i;
311                         return;
312                 }
313                 PARA_CRIT_LOG("%s init failed: %s\n", dblist[i].name,
314                         PARA_STRERROR(-ret));
315         }
316 random:
317         mmd->dbt_num = 0;
318         dblist[0].init(&dblist[0]); /* always successful */
319 }
320
321 static unsigned init_network(void)
322 {
323         int sockfd = init_tcp_socket(conf.port_arg);
324
325         if (sockfd < 0)
326                 exit(EXIT_FAILURE);
327         return sockfd;
328 }
329
330 static void init_random_seed(void)
331 {
332         int fd, ret = -1, len = sizeof(unsigned int);
333         unsigned int seed;
334
335         fd = open("/dev/random", O_RDONLY);
336         if (fd < 0)
337                 goto out;
338         ret = -2;
339         if (read(fd, &seed, len) != len)
340                 goto out;
341         srandom(seed);
342         ret = 1;
343 out:
344         if (fd >= 0)
345                 close(fd);
346         if (ret > 0)
347                 return;
348         PARA_EMERG_LOG("can not seed pseudo random generator (ret = %d)\n",
349                 ret);
350         exit(EXIT_FAILURE);
351 }
352
353 static unsigned do_inits(int argc, char **argv)
354 {
355         /* connector's address information */
356         int sockfd;
357
358         init_random_seed();
359         /* parse command line options */
360         cmdline_parser(argc, argv, &conf);
361         para_drop_privileges(conf.user_arg);
362         /* parse config file, open log and set defaults */
363         parse_config(0);
364         log_welcome("para_server", conf.loglevel_arg);
365         shm_init(); /* init mmd struct */
366         server_uptime(UPTIME_SET); /* reset server uptime */
367         /* become daemon */
368         if (conf.daemon_given)
369                 daemon_init();
370         init_dbtool();
371         PARA_NOTICE_LOG("%s", "initializing audio file sender\n");
372         /* audio file sender */
373         afs_init();
374         mmd->server_pid = getpid();
375         setup_signal_handling();
376         mmd_lock();
377         /* init network socket */
378         PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
379         sockfd = init_network();
380         if (conf.autoplay_given) {
381                 mmd->afs_status_flags |= AFS_PLAYING;
382                 mmd->new_afs_status_flags |= AFS_PLAYING;
383         }
384         PARA_NOTICE_LOG("%s", "init complete\n");
385         return sockfd;
386 }
387
388 static void handle_dbt_change(void)
389 {
390         int ret, old = mmd->dbt_num, new = mmd->dbt_change;
391
392         dblist[old].shutdown();
393         ret = dblist[new].init(&dblist[new]);
394         mmd->dbt_change = -1; /* reset */
395         if (ret >= 0) {
396                 mmd->dbt_num = new;
397                 return;
398         }
399         /* init failed */
400         PARA_ERROR_LOG("%s -- switching to the random dbtool\n", PARA_STRERROR(-ret));
401         dblist[0].init(&dblist[0]);
402         mmd->dbt_num = 0;
403 }
404
405 /*
406  * called when server gets SIGHUP or when client invokes hup command.
407  */
408 static void handle_sighup(void)
409 {
410         PARA_NOTICE_LOG("%s", "SIGHUP\n");
411         close_log(logfile); /* gets reopened if necessary by parse_config */
412         logfile = NULL;
413         parse_config(1); /* reopens log */
414         mmd->dbt_change = mmd->dbt_num; /* do not change dbtool */
415         handle_dbt_change(); /* force reloading dbtool */
416 }
417
418 static void status_refresh(void)
419 {
420         static int prev_uptime = -1, prev_events = -1;
421         int uptime = server_uptime(UPTIME_GET), ret = 1;
422
423         if (prev_events != mmd->events)
424                 goto out;
425         if (mmd->new_afs_status_flags != mmd->afs_status_flags)
426                 goto out;
427         if (uptime / 60 != prev_uptime / 60)
428                 goto out;
429         ret = 0;
430 out:
431         prev_uptime = uptime;
432         prev_events = mmd->events;
433         mmd->afs_status_flags = mmd->new_afs_status_flags;
434         if (ret) {
435                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
436                         mmd->events, mmd->audio_format);
437                 killpg(0, SIGUSR1);
438         }
439 }
440
441 /*
442  * MAIN
443  */
444 int main(int argc, char *argv[])
445 {
446         /* listen on sock_fd, new connection on new_fd */
447         int sockfd, new_fd;
448         struct sockaddr_in their_addr;
449         int err, i, max_fileno, ret;
450         pid_t chld_pid;
451         fd_set rfds, wfds;
452         struct timeval *timeout;
453
454         valid_fd_012();
455         sockfd = do_inits(argc, argv);
456 repeat:
457         /* check socket and signal pipe in any case */
458         FD_ZERO(&rfds);
459         FD_ZERO(&wfds);
460         FD_SET(sockfd, &rfds);
461         max_fileno = sockfd;
462         FD_SET(signal_pipe, &rfds);
463         max_fileno = MAX(max_fileno, signal_pipe);
464
465         timeout = afs_preselect();
466         status_refresh();
467         for (i = 0; senders[i].name; i++) {
468                 if (senders[i].status != SENDER_ON)
469                         continue;
470                 if (!senders[i].pre_select)
471                         continue;
472                 senders[i].pre_select(mmd->audio_format >= 0?
473                         &afl[mmd->audio_format] : NULL,
474                         &max_fileno,
475                         &rfds, &wfds);
476         }
477         if (dblist[mmd->dbt_num].pre_select) {
478                 ret = dblist[mmd->dbt_num].pre_select(&rfds, &wfds);
479                 max_fileno = MAX(max_fileno, ret);
480         }
481         mmd_unlock();
482 //      PARA_DEBUG_LOG("%s: select (max = %i)\n", __func__, max_fileno);
483         ret = select(max_fileno + 1, &rfds, &wfds, NULL, timeout);
484         err = errno;
485         //PARA_DEBUG_LOG("%s: select returned  %i\n", __func__, ret);
486         mmd_lock();
487         if (mmd->dbt_change >= 0)
488                 handle_dbt_change();
489         if (dblist[mmd->dbt_num].post_select)
490                 dblist[mmd->dbt_num].post_select(&rfds, &wfds);
491         if (ret < 0 && err == EINTR)
492                 goto repeat;
493         if (ret < 0) {
494                 PARA_CRIT_LOG("select error (%s)\n", strerror(err));
495                 goto repeat;
496         }
497         for (i = 0; senders[i].name; i++) {
498                 if (senders[i].status != SENDER_ON)
499                         continue;
500                 if (!senders[i].post_select)
501                         continue;
502                 senders[i].post_select(mmd->audio_format >= 0?
503                         &afl[mmd->audio_format] : NULL,
504                         &rfds, &wfds);
505         }
506         if (!ret) {
507                 afs_send_chunk();
508                 status_refresh();
509         }
510         if (FD_ISSET(signal_pipe, &rfds)) {
511                 int sig;
512                 sig = para_next_signal();
513                 switch (sig) {
514                 case SIGHUP:
515                         handle_sighup();
516                         break;
517                 case SIGCHLD:
518                         para_reap_children();
519                         break;
520                 /* die on sigint/sigterm. Kill all children too. */
521                 case SIGINT:
522                 case SIGTERM:
523                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
524                         kill(0, SIGTERM);
525                         dblist[mmd->dbt_num].shutdown();
526                         mutex_destroy(mmd_mutex);
527                         shm_detach(mmd);
528                         shm_destroy(mmd_shm_id);
529                         exit(EXIT_FAILURE);
530                 }
531         }
532         if (mmd->sender_cmd_data.cmd_num >= 0) {
533                 int num = mmd->sender_cmd_data.cmd_num,
534                         s = mmd->sender_cmd_data.sender_num;
535
536                 if (senders[s].client_cmds[num])
537                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
538                 mmd->sender_cmd_data.cmd_num = -1;
539         }
540         if (!FD_ISSET(sockfd, &rfds))
541                 goto repeat;
542
543         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
544         if (new_fd < 0)
545                 goto repeat;
546         PARA_INFO_LOG("got connection from %s, forking\n",
547                 inet_ntoa(their_addr.sin_addr));
548         mmd->num_connects++;
549         mmd->active_connections++;
550         random();
551         chld_pid = fork();
552         if (chld_pid < 0) {
553                 PARA_CRIT_LOG("%s", "fork failed\n");
554                 goto repeat;
555         }
556         if (chld_pid) {
557                 close(new_fd);
558                 /* parent keeps accepting connections */
559                 goto repeat;
560         }
561         alarm(ALARM_TIMEOUT);
562         close_listed_fds();
563         close(sockfd); /* child doesn't need the listener */
564         /*
565          * put info on who we are serving into argv[0] to make
566          * client ip visible in top/ps
567          */
568         for (i = argc - 1; i >= 0; i--)
569                 memset(argv[i], 0, strlen(argv[i]));
570         sprintf(argv[0], "para_server (serving %s)",
571                 inet_ntoa(their_addr.sin_addr));
572         return handle_connect(new_fd, &their_addr);
573 }