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