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