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