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