]> git.tuebingen.mpg.de Git - paraslash.git/blob - server.c
a6fca8b6cd5629777ad347e9a20050611aa41895
[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 <sys/mman.h> /* MAP_SHARED, PROT_READ, PROT_WRITE */
38 #include "send.h"
39 #include "error.h"
40 #include "net.h"
41 #include "daemon.h"
42 #include "string.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_semid;
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 /*
156  * setup shared memory area and get semaphore for locking
157  */
158 static void shm_init(void)
159 {
160         int fd;
161         caddr_t area;
162
163         if ((fd = open("/dev/zero", O_RDWR)) < 0) {
164                 PARA_EMERG_LOG("%s", "failed to open /dev/zero\n");
165                 exit(EXIT_FAILURE);
166         }
167         if ((area = mmap(0, sizeof(struct misc_meta_data),
168                         PROT_READ | PROT_WRITE,
169                         MAP_SHARED, fd, 0)) == (caddr_t) - 1) {
170                 PARA_EMERG_LOG("%s", "mmap error\n");
171                 exit(EXIT_FAILURE);
172         }
173         close(fd); /* we dont need /dev/zero anymore */
174         mmd = (struct misc_meta_data *)area;
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
188         mmd_semid = semget(42, 1, IPC_CREAT | 0666);
189         if (mmd_semid == -1) {
190                 PARA_EMERG_LOG("%s", "semget failed\n");
191                 exit(EXIT_FAILURE);
192         }
193 }
194
195 static void do_semop(struct sembuf *sops, int num)
196 {
197         if (semop(mmd_semid, sops, num) >= 0)
198                 return;
199         PARA_WARNING_LOG("semop failed (%s), retrying\n", strerror(errno));
200         while (semop(mmd_semid, sops, num) < 0)
201                 ; /* nothing */
202 }
203
204 /**
205  * lock the shared memory area containing the mmd struct
206  *
207  * \sa semop(2), struct misc_meta_data
208  */
209 void mmd_lock(void)
210 {
211         struct sembuf sops[2] = {
212                 {
213                         .sem_num = 0,
214                         .sem_op = 0,
215                         .sem_flg = SEM_UNDO
216                 },
217                 {
218                         .sem_num = 0,
219                         .sem_op = 1,
220                         .sem_flg = SEM_UNDO
221                 }
222         };
223         do_semop(sops, 2);
224 }
225
226 /**
227  * unlock the shared memory area containing the mmd struct
228  *
229  * \sa semop(2), struct misc_meta_data
230  */
231 void mmd_unlock(void)
232 {
233         struct sembuf sops[1] = {
234                 {
235                         .sem_num = 0,
236                         .sem_op = -1,
237                         .sem_flg = SEM_UNDO
238                 },
239         };
240         do_semop(sops, 1);
241 }
242
243 static void parse_config(int override)
244 {
245         char *home = para_homedir();
246         struct stat statbuf;
247         int ret;
248         char *cf;
249
250         if (conf.config_file_given)
251                 cf = conf.config_file_arg;
252         else
253                 cf = make_message("%s/.paraslash/server.conf", home);
254         free(user_list);
255         if (!conf.user_list_given)
256                 user_list = make_message("%s/.paraslash/server.users", home);
257         else
258                 user_list = para_strdup(conf.user_list_arg);
259         ret = stat(cf, &statbuf);
260         if (ret && conf.config_file_given) {
261                 ret = -1;
262                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
263                 goto out;
264         }
265         if (!ret) {
266                 int tmp = conf.daemon_given;
267                 cmdline_parser_configfile(cf, &conf, override, 0, 0);
268                 conf.daemon_given = tmp;
269         }
270         /* logfile */
271         if (!conf.logfile_given && conf.daemon_given) {
272                 ret = -1;
273                 PARA_EMERG_LOG("%s", "daemon, but no log file\n");
274                 goto out;
275         }
276         if (conf.logfile_given)
277                 logfile = open_log(conf.logfile_arg);
278         ret = 1;
279 out:
280         free(cf);
281         free(home);
282         if (ret > 0)
283                 return;
284         free(user_list);
285         user_list = NULL;
286         exit(EXIT_FAILURE);
287 }
288
289 static void setup_signal_handling(void)
290 {
291         int ret = 0;
292
293         signal_pipe = para_signal_init();
294 //      fcntl(signal_pipe, F_SETFL, O_NONBLOCK);
295         PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
296         ret += para_install_sighandler(SIGINT);
297         ret += para_install_sighandler(SIGTERM);
298         ret += para_install_sighandler(SIGHUP);
299         ret += para_install_sighandler(SIGCHLD);
300         ret += para_install_sighandler(SIGUSR1);
301         signal(SIGPIPE, SIG_IGN);
302         if (ret != 5) {
303                 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
304                 exit(EXIT_FAILURE);
305         }
306 }
307
308 static void init_dbtool(void)
309 {
310         int i;
311
312         mmd->dbt_change = -1; /* no change nec., set to new dbt num by com_cdt */
313         if (!dblist[1].name)
314                 goto random;
315         if (conf.dbtool_given) {
316                 for (i = 0; dblist[i].name; i++) {
317                         if (strcmp(dblist[i].name, conf.dbtool_arg))
318                                 continue;
319                         PARA_NOTICE_LOG("initializing %s database tool\n",
320                                 dblist[i].name);
321                         if (dblist[i].init(&dblist[i]) < 0) {
322                                 PARA_WARNING_LOG("init %s failed",
323                                         dblist[i].name);
324                                 goto random;
325                         }
326                         mmd->dbt_num = i;
327                         return;
328                 }
329                 PARA_WARNING_LOG("%s", "no such dbtool, switching to random\n");
330                 goto random;
331         }
332         /* use the first dbtool that works
333          * (assuming that random always works)
334          */
335         for (i = 1; dblist[i].name; i++) {
336                 int ret = dblist[i].init(&dblist[i]);
337                 if (ret >= 0) {
338                         PARA_INFO_LOG("initialized %s\n", dblist[i].name);
339                         mmd->dbt_num = i;
340                         return;
341                 }
342                 PARA_CRIT_LOG("%s init failed: %s\n", dblist[i].name,
343                         PARA_STRERROR(-ret));
344         }
345 random:
346         mmd->dbt_num = 0;
347         dblist[0].init(&dblist[0]); /* always successful */
348 }
349
350 static unsigned init_network(void)
351 {
352         int sockfd = init_tcp_socket(conf.port_arg);
353
354         if (sockfd < 0)
355                 exit(EXIT_FAILURE);
356         return sockfd;
357 }
358
359 static void init_random_seed(void)
360 {
361         int fd, ret = -1, len = sizeof(unsigned int);
362         unsigned int seed;
363
364         fd = open("/dev/random", O_RDONLY);
365         if (fd < 0)
366                 goto out;
367         ret = -2;
368         if (read(fd, &seed, len) != len)
369                 goto out;
370         srandom(seed);
371         ret = 1;
372 out:
373         if (fd >= 0)
374                 close(fd);
375         if (ret > 0)
376                 return;
377         PARA_EMERG_LOG("can not seed pseudo random generator (ret = %d)\n",
378                 ret);
379         exit(EXIT_FAILURE);
380 }
381
382 static unsigned do_inits(int argc, char **argv)
383 {
384         /* connector's address information */
385         int sockfd;
386
387         init_random_seed();
388         /* parse command line options */
389         cmdline_parser(argc, argv, &conf);
390         para_drop_privileges(conf.user_arg);
391         /* parse config file, open log and set defaults */
392         parse_config(0);
393         log_welcome("para_server", conf.loglevel_arg);
394         shm_init(); /* init mmd struct */
395         server_uptime(UPTIME_SET); /* reset server uptime */
396         /* become daemon */
397         if (conf.daemon_given)
398                 daemon_init();
399         init_dbtool();
400         PARA_NOTICE_LOG("%s", "initializing audio file sender\n");
401         /* audio file sender */
402         afs_init();
403         mmd->server_pid = getpid();
404         setup_signal_handling();
405         mmd_lock();
406         /* init network socket */
407         PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
408         sockfd = init_network();
409         if (conf.autoplay_given) {
410                 mmd->afs_status_flags |= AFS_PLAYING;
411                 mmd->new_afs_status_flags |= AFS_PLAYING;
412         }
413         PARA_NOTICE_LOG("%s", "init complete\n");
414         return sockfd;
415 }
416
417 static void handle_dbt_change(void)
418 {
419         int ret, old = mmd->dbt_num, new = mmd->dbt_change;
420
421         dblist[old].shutdown();
422         ret = dblist[new].init(&dblist[new]);
423         mmd->dbt_change = -1; /* reset */
424         if (ret >= 0) {
425                 mmd->dbt_num = new;
426                 return;
427         }
428         /* init failed */
429         PARA_ERROR_LOG("%s -- switching to the random dbtool\n", PARA_STRERROR(-ret));
430         dblist[0].init(&dblist[0]);
431         mmd->dbt_num = 0;
432 }
433
434 /*
435  * called when server gets SIGHUP or when client invokes hup command.
436  */
437 static void handle_sighup(void)
438 {
439         PARA_NOTICE_LOG("%s", "SIGHUP\n");
440         close_log(logfile); /* gets reopened if necessary by parse_config */
441         logfile = NULL;
442         parse_config(1); /* reopens log */
443         mmd->dbt_change = mmd->dbt_num; /* do not change dbtool */
444         handle_dbt_change(); /* force reloading dbtool */
445 }
446
447 static void status_refresh(void)
448 {
449         static int prev_uptime = -1, prev_events = -1;
450         int uptime = server_uptime(UPTIME_GET), ret = 1;
451
452         if (prev_events != mmd->events)
453                 goto out;
454         if (mmd->new_afs_status_flags != mmd->afs_status_flags)
455                 goto out;
456         if (uptime / 60 != prev_uptime / 60)
457                 goto out;
458         ret = 0;
459 out:
460         prev_uptime = uptime;
461         prev_events = mmd->events;
462         mmd->afs_status_flags = mmd->new_afs_status_flags;
463         if (ret) {
464                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
465                         mmd->events, mmd->audio_format);
466                 killpg(0, SIGUSR1);
467         }
468 }
469
470 /*
471  * MAIN
472  */
473 int main(int argc, char *argv[])
474 {
475         /* listen on sock_fd, new connection on new_fd */
476         int sockfd, new_fd;
477         struct sockaddr_in their_addr;
478         int err, i, max_fileno, ret;
479         pid_t chld_pid;
480         fd_set rfds, wfds;
481         struct timeval *timeout;
482
483         valid_fd_012();
484         sockfd = do_inits(argc, argv);
485 repeat:
486         /* check socket and signal pipe in any case */
487         FD_ZERO(&rfds);
488         FD_ZERO(&wfds);
489         FD_SET(sockfd, &rfds);
490         max_fileno = sockfd;
491         FD_SET(signal_pipe, &rfds);
492         max_fileno = MAX(max_fileno, signal_pipe);
493
494         timeout = afs_preselect();
495         status_refresh();
496         for (i = 0; senders[i].name; i++) {
497                 if (senders[i].status != SENDER_ON)
498                         continue;
499                 if (!senders[i].pre_select)
500                         continue;
501                 senders[i].pre_select(mmd->audio_format >= 0?
502                         &afl[mmd->audio_format] : NULL,
503                         &max_fileno,
504                         &rfds, &wfds);
505         }
506         if (dblist[mmd->dbt_num].pre_select) {
507                 ret = dblist[mmd->dbt_num].pre_select(&rfds, &wfds);
508                 max_fileno = MAX(max_fileno, ret);
509         }
510         mmd_unlock();
511 //      PARA_DEBUG_LOG("%s: select (max = %i)\n", __func__, max_fileno);
512         ret = select(max_fileno + 1, &rfds, &wfds, NULL, timeout);
513         err = errno;
514         //PARA_DEBUG_LOG("%s: select returned  %i\n", __func__, ret);
515         mmd_lock();
516         if (mmd->dbt_change >= 0)
517                 handle_dbt_change();
518         if (dblist[mmd->dbt_num].post_select)
519                 dblist[mmd->dbt_num].post_select(&rfds, &wfds);
520         if (ret < 0 && err == EINTR)
521                 goto repeat;
522         if (ret < 0) {
523                 PARA_CRIT_LOG("select error (%s)\n", strerror(err));
524                 goto repeat;
525         }
526         for (i = 0; senders[i].name; i++) {
527                 if (senders[i].status != SENDER_ON)
528                         continue;
529                 if (!senders[i].post_select)
530                         continue;
531                 senders[i].post_select(mmd->audio_format >= 0?
532                         &afl[mmd->audio_format] : NULL,
533                         &rfds, &wfds);
534         }
535         if (!ret) {
536                 afs_send_chunk();
537                 status_refresh();
538         }
539         if (FD_ISSET(signal_pipe, &rfds)) {
540                 int sig;
541                 sig = para_next_signal();
542                 switch (sig) {
543                 case SIGHUP:
544                         handle_sighup();
545                         break;
546                 case SIGCHLD:
547                         para_reap_children();
548                         break;
549                 /* die on sigint/sigterm. Kill all children too. */
550                 case SIGINT:
551                 case SIGTERM:
552                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
553                         kill(0, SIGTERM);
554                         exit(EXIT_FAILURE);
555                 }
556         }
557         if (mmd->sender_cmd_data.cmd_num >= 0) {
558                 int num = mmd->sender_cmd_data.cmd_num,
559                         s = mmd->sender_cmd_data.sender_num;
560
561                 if (senders[s].client_cmds[num])
562                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
563                 mmd->sender_cmd_data.cmd_num = -1;
564         }
565         if (!FD_ISSET(sockfd, &rfds))
566                 goto repeat;
567
568         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
569         if (new_fd < 0)
570                 goto repeat;
571         PARA_INFO_LOG("got connection from %s, forking\n",
572                 inet_ntoa(their_addr.sin_addr));
573         mmd->num_connects++;
574         mmd->active_connections++;
575         random();
576         chld_pid = fork();
577         if (chld_pid < 0) {
578                 PARA_CRIT_LOG("%s", "fork failed\n");
579                 goto repeat;
580         }
581         if (chld_pid) {
582                 close(new_fd);
583                 /* parent keeps accepting connections */
584                 goto repeat;
585         }
586         alarm(ALARM_TIMEOUT);
587         close_listed_fds();
588         close(sockfd); /* child doesn't need the listener */
589         /*
590          * put info on who we are serving into argv[0] to make
591          * client ip visible in top/ps
592          */
593         for (i = argc - 1; i >= 0; i--)
594                 memset(argv[i], 0, strlen(argv[i]));
595         sprintf(argv[0], "para_server (serving %s)",
596                 inet_ntoa(their_addr.sin_addr));
597         return handle_connect(new_fd, &their_addr);
598 }