]> git.tuebingen.mpg.de Git - paraslash.git/blob - server.c
the paraslash-0.2.14 release tarball
[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 audio_file_selector,
25  *  \ref sender, \ref receiver, \ref receiver_node, \ref filter, \ref
26  *  filter_node.
27  *
28  */
29
30
31
32 #include "server.cmdline.h"
33 #include "db.h"
34 #include "server.h"
35 #include "afs.h"
36 #include "config.h"
37 #include "close_on_fork.h"
38 #include "send.h"
39 #include "error.h"
40 #include "net.h"
41 #include "daemon.h"
42 #include "string.h"
43 #include "ipc.h"
44 #include "fd.h"
45
46 /** define the array of error lists needed by para_server */
47 INIT_SERVER_ERRLISTS;
48
49 /** shut down non-authorized connections after that many seconds */
50 #define ALARM_TIMEOUT 10
51
52 /* these are exported to afs.c. command.c and to all selectors */
53 struct misc_meta_data *mmd;
54 /** the configuration of para_server
55  *
56  * It also contains the options for all audio file selectors and all supported
57  * senders.
58 */
59 struct server_args_info conf;
60 char *user_list = NULL;
61 extern void dccp_send_init(struct sender *);
62 extern void http_send_init(struct sender *);
63 extern void ortp_send_init(struct sender *);
64
65 /* TODO: This is better handled by autoconf */
66 /** the list of supported audio file selectors */
67 struct audio_file_selector selectors[] = {
68         {
69                 .name = "random",
70                 .init = random_selector_init,
71                 .update_audio_file = NULL,
72         },
73         {
74                 .name = "playlist",
75                 .init = playlist_selector_init,
76                 .update_audio_file = NULL,
77                 .pre_select = NULL,
78                 .post_select = NULL,
79         },
80 #ifdef HAVE_MYSQL
81         {
82                 .name = "mysql",
83                 .init = mysql_selector_init,
84                 .update_audio_file = NULL,
85                 .pre_select = NULL,
86                 .post_select = NULL,
87         },
88 #endif
89         {
90                 .name = NULL,
91         }
92 };
93
94 /** the list of supported senders */
95 struct sender senders[] = {
96         {
97                 .name = "http",
98                 .init = http_send_init,
99         },
100         {
101                 .name = "dccp",
102                 .init = dccp_send_init,
103         },
104 #ifdef HAVE_ORTP
105         {
106                 .name = "ortp",
107                 .init = ortp_send_init,
108         },
109 #endif
110         {
111                 .name = NULL,
112         }
113 };
114
115
116 /* global variables for server-internal use */
117 static FILE *logfile;
118 static int mmd_mutex, mmd_shm_id;
119 static int signal_pipe;
120
121 /**
122  * para_server's log function
123  *
124  * \param ll the log level
125  * \param fmt the format string describing the log message
126  */
127 void para_log(int ll, const char* fmt,...)
128 {
129         va_list argp;
130         FILE *outfd;
131         struct tm *tm;
132         time_t t1;
133         char str[MAXLINE] = "";
134         pid_t mypid;
135
136         if (ll < conf.loglevel_arg)
137                 return;
138         outfd = logfile? logfile : stderr;
139         time(&t1);
140         tm = localtime(&t1);
141         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
142         fprintf(outfd, "%s ", str);
143         if (conf.loglevel_arg <= INFO)
144                 fprintf(outfd, "%i: ", ll);
145         mypid = getpid();
146         if (conf.loglevel_arg <= INFO)
147                 fprintf(outfd, "(%d) ", mypid);
148         va_start(argp, fmt);
149         vfprintf(outfd, fmt, argp);
150         va_end(argp);
151 }
152
153 /*
154  * setup shared memory area and get mutex for locking
155  */
156 static void shm_init(void)
157 {
158         void *shm;
159         int ret = shm_new(sizeof(struct misc_meta_data));
160
161         if (ret < 0)
162                 goto err_out;
163
164         ret = shm_attach(ret, ATTACH_RW, &shm);
165         if (ret < 0)
166                 goto err_out;
167         mmd = shm;
168         mmd_shm_id = ret;
169
170         ret = mutex_new();
171         if (ret < 0)
172                 goto err_out;
173         mmd_mutex = ret;
174
175         mmd->selector_num = 0;
176         mmd->num_played = 0;
177         mmd->num_commands = 0;
178         mmd->events = 0;
179         mmd->num_connects = 0;
180         mmd->active_connections = 0;
181         strcpy(mmd->filename, "(none)");
182         mmd->audio_format = -1;
183         mmd->afs_status_flags = AFS_NEXT;
184         mmd->new_afs_status_flags = AFS_NEXT;
185         mmd->sender_cmd_data.cmd_num = -1;
186         return;
187 err_out:
188         PARA_EMERG_LOG("%s", PARA_STRERROR(-ret));
189         exit(EXIT_FAILURE);
190 }
191
192 /**
193  * lock the shared memory area containing the mmd struct
194  *
195  * \sa semop(2), struct misc_meta_data
196  */
197 void mmd_lock(void)
198 {
199         mutex_lock(mmd_mutex);
200 }
201
202 /**
203  * unlock the shared memory area containing the mmd struct
204  *
205  * \sa semop(2), struct misc_meta_data
206  */
207
208 void mmd_unlock(void)
209 {
210         mutex_unlock(mmd_mutex);
211 }
212
213 static void parse_config(int override)
214 {
215         char *home = para_homedir();
216         struct stat statbuf;
217         int ret;
218         char *cf;
219
220         if (conf.config_file_given)
221                 cf = conf.config_file_arg;
222         else
223                 cf = make_message("%s/.paraslash/server.conf", home);
224         free(user_list);
225         if (!conf.user_list_given)
226                 user_list = make_message("%s/.paraslash/server.users", home);
227         else
228                 user_list = para_strdup(conf.user_list_arg);
229         ret = stat(cf, &statbuf);
230         if (ret && conf.config_file_given) {
231                 ret = -1;
232                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
233                 goto out;
234         }
235         if (!ret) {
236                 int tmp = conf.daemon_given;
237                 server_cmdline_parser_configfile(cf, &conf, override, 0, 0);
238                 conf.daemon_given = tmp;
239         }
240         /* logfile */
241         if (!conf.logfile_given && conf.daemon_given) {
242                 ret = -1;
243                 PARA_EMERG_LOG("%s", "daemon, but no log file\n");
244                 goto out;
245         }
246         if (conf.logfile_given)
247                 logfile = open_log(conf.logfile_arg);
248         ret = 1;
249 out:
250         free(cf);
251         free(home);
252         if (ret > 0)
253                 return;
254         free(user_list);
255         user_list = NULL;
256         exit(EXIT_FAILURE);
257 }
258
259 static void setup_signal_handling(void)
260 {
261         int ret = 0;
262
263         signal_pipe = para_signal_init();
264         PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
265         ret += para_install_sighandler(SIGINT);
266         ret += para_install_sighandler(SIGTERM);
267         ret += para_install_sighandler(SIGHUP);
268         ret += para_install_sighandler(SIGCHLD);
269         ret += para_install_sighandler(SIGUSR1);
270         signal(SIGPIPE, SIG_IGN);
271         if (ret != 5) {
272                 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
273                 exit(EXIT_FAILURE);
274         }
275 }
276
277 static void init_selector(void)
278 {
279         int i, ret;
280
281         mmd->selector_change = -1; /* no change nec., set to new num by com_chs */
282         if (!conf.selector_given)
283                 goto random;
284         for (i = 0; selectors[i].name; i++) {
285                 if (strcmp(selectors[i].name, conf.selector_arg))
286                         continue;
287                 PARA_NOTICE_LOG("initializing %s audio file selector\n",
288                         selectors[i].name);
289                 ret = selectors[i].init(&selectors[i]);
290                 if (ret < 0) {
291                         PARA_WARNING_LOG("%s", PARA_STRERROR(-ret));
292                         break;
293                 }
294                 mmd->selector_num = i;
295                 return;
296         }
297         PARA_WARNING_LOG("%s", "falling back to the random selector\n");
298 random:
299         mmd->selector_num = 0;
300         selectors[0].init(&selectors[0]); /* always successful */
301 }
302
303 static unsigned init_network(void)
304 {
305         int fd, ret = init_tcp_socket(conf.port_arg);
306
307         if (ret < 0)
308                 goto err;
309         fd = ret;
310         ret = mark_fd_nonblock(fd);
311         if (ret < 0)
312                 goto err;
313         return fd;
314 err:
315         PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
316         exit(EXIT_FAILURE);
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         server_cmdline_parser(argc, argv, &conf);
350         para_drop_privileges(conf.user_arg, conf.group_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_selector();
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         PARA_NOTICE_LOG("%s", "init complete\n");
370         return sockfd;
371 }
372
373 static void change_selector(void)
374 {
375         int ret, old = mmd->selector_num, new = mmd->selector_change;
376
377         selectors[old].shutdown();
378         ret = selectors[new].init(&selectors[new]);
379         mmd->selector_change = -1; /* reset */
380         if (ret >= 0) {
381                 mmd->selector_num = new;
382                 return;
383         }
384         /* init failed */
385         PARA_ERROR_LOG("%s -- switching to the random selector\n", PARA_STRERROR(-ret));
386         selectors[0].init(&selectors[0]);
387         mmd->selector_num = 0;
388 }
389
390 /*
391  * called when server gets SIGHUP or when client invokes hup command.
392  */
393 static void handle_sighup(void)
394 {
395         PARA_NOTICE_LOG("%s", "SIGHUP\n");
396         close_log(logfile); /* gets reopened if necessary by parse_config */
397         logfile = NULL;
398         parse_config(1); /* reopens log */
399         mmd->selector_change = mmd->selector_num; /* do not change selector.. */
400         change_selector(); /* .. just reload */
401 }
402
403 static void status_refresh(void)
404 {
405         static int prev_uptime = -1, prev_events = -1;
406         int uptime = server_uptime(UPTIME_GET), ret = 1;
407
408         if (prev_events != mmd->events)
409                 goto out;
410         if (mmd->new_afs_status_flags != mmd->afs_status_flags)
411                 goto out;
412         if (uptime / 60 != prev_uptime / 60)
413                 goto out;
414         ret = 0;
415 out:
416         prev_uptime = uptime;
417         prev_events = mmd->events;
418         mmd->afs_status_flags = mmd->new_afs_status_flags;
419         if (ret) {
420                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
421                         mmd->events, mmd->audio_format);
422                 killpg(0, SIGUSR1);
423         }
424 }
425
426 /*
427  * MAIN
428  */
429 int main(int argc, char *argv[])
430 {
431         /* listen on sock_fd, new connection on new_fd */
432         int sockfd, new_fd;
433         struct sockaddr_in their_addr;
434         int i, max_fileno, ret;
435         pid_t chld_pid;
436         fd_set rfds, wfds;
437         struct timeval *timeout;
438
439         valid_fd_012();
440         sockfd = do_inits(argc, argv);
441 repeat:
442         FD_ZERO(&rfds);
443         FD_ZERO(&wfds);
444         max_fileno = -1;
445         /* check socket and signal pipe in any case */
446         para_fd_set(sockfd, &rfds, &max_fileno);
447         para_fd_set(signal_pipe, &rfds, &max_fileno);
448         timeout = afs_preselect();
449         status_refresh();
450         for (i = 0; senders[i].name; i++) {
451                 if (senders[i].status != SENDER_ON)
452                         continue;
453                 if (!senders[i].pre_select)
454                         continue;
455                 senders[i].pre_select( &max_fileno, &rfds, &wfds);
456         }
457         if (selectors[mmd->selector_num].pre_select) {
458                 ret = selectors[mmd->selector_num].pre_select(&rfds, &wfds);
459                 max_fileno = PARA_MAX(max_fileno, ret);
460         }
461         mmd_unlock();
462         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
463         mmd_lock();
464         if (mmd->selector_change >= 0)
465                 change_selector();
466         if (selectors[mmd->selector_num].post_select)
467                 selectors[mmd->selector_num].post_select(&rfds, &wfds);
468         if (ret < 0)
469                 goto repeat;
470         for (i = 0; senders[i].name; i++) {
471                 if (senders[i].status != SENDER_ON)
472                         continue;
473                 if (!senders[i].post_select)
474                         continue;
475                 senders[i].post_select(&rfds, &wfds);
476         }
477         afs_send_chunk();
478         status_refresh();
479         if (FD_ISSET(signal_pipe, &rfds)) {
480                 int sig;
481                 sig = para_next_signal();
482                 switch (sig) {
483                 case SIGHUP:
484                         handle_sighup();
485                         break;
486                 case SIGCHLD:
487                         para_reap_children();
488                         break;
489                 /* die on sigint/sigterm. Kill all children too. */
490                 case SIGINT:
491                 case SIGTERM:
492                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
493                         kill(0, SIGTERM);
494                         selectors[mmd->selector_num].shutdown();
495                         mutex_destroy(mmd_mutex);
496                         shm_detach(mmd);
497                         shm_destroy(mmd_shm_id);
498                         exit(EXIT_FAILURE);
499                 }
500         }
501         if (mmd->sender_cmd_data.cmd_num >= 0) {
502                 int num = mmd->sender_cmd_data.cmd_num,
503                         s = mmd->sender_cmd_data.sender_num;
504
505                 if (senders[s].client_cmds[num])
506                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
507                 mmd->sender_cmd_data.cmd_num = -1;
508         }
509         if (!FD_ISSET(sockfd, &rfds))
510                 goto repeat;
511
512         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
513         if (new_fd < 0)
514                 goto repeat;
515         PARA_INFO_LOG("got connection from %s, forking\n",
516                 inet_ntoa(their_addr.sin_addr));
517         mmd->num_connects++;
518         mmd->active_connections++;
519         random();
520         chld_pid = fork();
521         if (chld_pid < 0) {
522                 PARA_CRIT_LOG("%s", "fork failed\n");
523                 goto repeat;
524         }
525         if (chld_pid) {
526                 close(new_fd);
527                 /* parent keeps accepting connections */
528                 goto repeat;
529         }
530         alarm(ALARM_TIMEOUT);
531         close_listed_fds();
532         close(sockfd); /* child doesn't need the listener */
533         /*
534          * put info on who we are serving into argv[0] to make
535          * client ip visible in top/ps
536          */
537         for (i = argc - 1; i >= 0; i--)
538                 memset(argv[i], 0, strlen(argv[i]));
539         sprintf(argv[0], "para_server (serving %s)",
540                 inet_ntoa(their_addr.sin_addr));
541         return handle_connect(new_fd, &their_addr);
542 }