b7334fc52c434a5c9cc69eb3f6fa3dcf8769e18c
[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 "crypt.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 = NULL;
62 struct list_head _user_list;
63 extern void dccp_send_init(struct sender *);
64 extern void http_send_init(struct sender *);
65 extern void ortp_send_init(struct sender *);
66
67 /* TODO: This is better handled by autoconf */
68 /** the list of supported audio file selectors */
69 struct audio_file_selector selectors[] = {
70         {
71                 .name = "random",
72                 .init = random_selector_init,
73                 .update_audio_file = NULL,
74         },
75         {
76                 .name = "playlist",
77                 .init = playlist_selector_init,
78                 .update_audio_file = NULL,
79                 .pre_select = NULL,
80                 .post_select = NULL,
81         },
82 #ifdef HAVE_MYSQL
83         {
84                 .name = "mysql",
85                 .init = mysql_selector_init,
86                 .update_audio_file = NULL,
87                 .pre_select = NULL,
88                 .post_select = NULL,
89         },
90 #endif
91         {
92                 .name = NULL,
93         }
94 };
95
96 /** the list of supported senders */
97 struct sender senders[] = {
98         {
99                 .name = "http",
100                 .init = http_send_init,
101         },
102         {
103                 .name = "dccp",
104                 .init = dccp_send_init,
105         },
106 #ifdef HAVE_ORTP
107         {
108                 .name = "ortp",
109                 .init = ortp_send_init,
110         },
111 #endif
112         {
113                 .name = NULL,
114         }
115 };
116
117
118 /* global variables for server-internal use */
119 static FILE *logfile;
120 static int mmd_mutex, mmd_shm_id;
121 static int signal_pipe;
122
123 /**
124  * para_server's log function
125  *
126  * \param ll the log level
127  * \param fmt the format string describing the log message
128  */
129 void para_log(int ll, const char* fmt,...)
130 {
131         va_list argp;
132         FILE *outfd;
133         struct tm *tm;
134         time_t t1;
135         char str[MAXLINE] = "";
136         pid_t mypid;
137
138         if (ll < conf.loglevel_arg)
139                 return;
140         outfd = logfile? logfile : stderr;
141         time(&t1);
142         tm = localtime(&t1);
143         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
144         fprintf(outfd, "%s ", str);
145         if (conf.loglevel_arg <= INFO)
146                 fprintf(outfd, "%i: ", ll);
147         mypid = getpid();
148         if (conf.loglevel_arg <= INFO)
149                 fprintf(outfd, "(%d) ", mypid);
150         va_start(argp, fmt);
151         vfprintf(outfd, fmt, argp);
152         va_end(argp);
153 }
154
155 /*
156  * setup shared memory area and get mutex for locking
157  */
158 static void shm_init(void)
159 {
160         void *shm;
161         int ret = shm_new(sizeof(struct misc_meta_data));
162
163         if (ret < 0)
164                 goto err_out;
165
166         ret = shm_attach(ret, ATTACH_RW, &shm);
167         if (ret < 0)
168                 goto err_out;
169         mmd = shm;
170         mmd_shm_id = ret;
171
172         ret = mutex_new();
173         if (ret < 0)
174                 goto err_out;
175         mmd_mutex = ret;
176
177         mmd->selector_num = 0;
178         mmd->num_played = 0;
179         mmd->num_commands = 0;
180         mmd->events = 0;
181         mmd->num_connects = 0;
182         mmd->active_connections = 0;
183         strcpy(mmd->filename, "(none)");
184         mmd->audio_format = -1;
185         mmd->afs_status_flags = AFS_NEXT;
186         mmd->new_afs_status_flags = AFS_NEXT;
187         mmd->sender_cmd_data.cmd_num = -1;
188         return;
189 err_out:
190         PARA_EMERG_LOG("%s", PARA_STRERROR(-ret));
191         exit(EXIT_FAILURE);
192 }
193
194 /**
195  * lock the shared memory area containing the mmd struct
196  *
197  * \sa semop(2), struct misc_meta_data
198  */
199 void mmd_lock(void)
200 {
201         mutex_lock(mmd_mutex);
202 }
203
204 /**
205  * unlock the shared memory area containing the mmd struct
206  *
207  * \sa semop(2), struct misc_meta_data
208  */
209
210 void mmd_unlock(void)
211 {
212         mutex_unlock(mmd_mutex);
213 }
214
215 static void parse_config(int override)
216 {
217         char *home = para_homedir();
218         struct stat statbuf;
219         int ret;
220         char *cf;
221
222         if (conf.config_file_given)
223                 cf = conf.config_file_arg;
224         else
225                 cf = make_message("%s/.paraslash/server.conf", home);
226         free(user_list);
227         if (!conf.user_list_given)
228                 user_list = make_message("%s/.paraslash/server.users", home);
229         else
230                 user_list = para_strdup(conf.user_list_arg);
231         ret = stat(cf, &statbuf);
232         if (ret && conf.config_file_given) {
233                 ret = -1;
234                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
235                 goto out;
236         }
237         if (!ret) {
238                 int tmp = conf.daemon_given;
239                 server_cmdline_parser_configfile(cf, &conf, override, 0, 0);
240                 conf.daemon_given = tmp;
241         }
242         /* logfile */
243         if (!conf.logfile_given && conf.daemon_given) {
244                 ret = -1;
245                 PARA_EMERG_LOG("%s", "daemon, but no log file\n");
246                 goto out;
247         }
248         if (conf.logfile_given)
249                 logfile = open_log(conf.logfile_arg);
250         ret = 1;
251 out:
252         free(cf);
253         free(home);
254         if (ret > 0)
255                 return;
256         free(user_list);
257         user_list = NULL;
258         exit(EXIT_FAILURE);
259 }
260
261 static void setup_signal_handling(void)
262 {
263         int ret = 0;
264
265         signal_pipe = para_signal_init();
266         PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
267         ret += para_install_sighandler(SIGINT);
268         ret += para_install_sighandler(SIGTERM);
269         ret += para_install_sighandler(SIGHUP);
270         ret += para_install_sighandler(SIGCHLD);
271         ret += para_install_sighandler(SIGUSR1);
272         signal(SIGPIPE, SIG_IGN);
273         if (ret != 5) {
274                 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
275                 exit(EXIT_FAILURE);
276         }
277 }
278
279 /*
280  * lookup user in user_list file. Fills in a user struct containing
281  * filename of the user's public key as well as the permissions of that user.
282  * Returns 1 on success, 0 if user does not exist and < 0 on errors.
283  */
284 static void populate_user_list(void) {
285         FILE *file_ptr = NULL;
286         char *char_ptr;
287         char line[MAXLINE];
288         /* keyword, user, key, perms */
289         char w[MAXLINE], n[MAXLINE], k[MAXLINE], p[MAXLINE], tmp[4][MAXLINE];
290         int num, ret;
291
292         file_ptr = fopen(user_list, "r");
293         ret = -E_USERLIST;
294         if (!file_ptr)
295                 goto out;
296         for (;;) {
297                 struct _user *u;
298                 ret = para_fgets(line, MAXLINE, file_ptr);
299                 if (ret < 0)
300                         PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
301                 if (ret <= 0)
302                         break;
303                 if (sscanf(line,"%200s %200s %200s %200s", w, n, k, p) < 3)
304                         continue;
305                 if (strcmp(w, "user"))
306                         continue;
307                 PARA_DEBUG_LOG("found entry for %s\n", n);
308                 u = para_malloc(sizeof(struct _user));
309                 u->name = para_strdup(n);
310                 u->rsa = para_malloc(sizeof(RSA));
311                 ret = get_rsa_key(k, &u->rsa, 0 /* public */);
312                 if (ret < 0)
313                         break;
314                 u->perms = 0;
315                 char_ptr = p;
316                 num = sscanf(char_ptr, "%200[A-Z_],%200[A-Z_],%200[A-Z_],%200[A-Z_]",
317                         tmp[0], tmp[1], tmp[2], tmp[3]);
318                 PARA_DEBUG_LOG("found %i perm entries\n", num);
319                 u->perms = 0;
320                 while (num > 0) {
321                         num--;
322                         if (!strcmp(tmp[num], "AFS_READ"))
323                                 u->perms |= AFS_READ;
324                         else if (!strcmp(tmp[num], "AFS_WRITE"))
325                                 u->perms |= AFS_WRITE;
326                         else if (!strcmp(tmp[num], "DB_READ"))
327                                 u->perms |= DB_READ;
328                         else if (!strcmp(tmp[num], "DB_WRITE"))
329                                 u->perms |= DB_WRITE;
330                         else /* unknown permission */
331                                 PARA_WARNING_LOG("unknown permission: %s\n",
332                                         tmp[num]);
333                 }
334                 para_list_add(&u->node, &_user_list);
335         }
336 out:
337         if (file_ptr)
338                 fclose(file_ptr);
339         if (ret >= 0)
340                 return;
341         PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
342         exit(EXIT_FAILURE);
343 }
344
345 static void init_user_list(void)
346 {
347         struct _user *u, *tmp;
348         static int initialized;
349
350         if (initialized) {
351                 list_for_each_entry_safe(u, tmp, &_user_list, node) {
352                         list_del(&u->node);
353                         free(u->name);
354                         free(u->rsa);
355                         free(u);
356                 }
357         } else
358                 INIT_LIST_HEAD(&_user_list);
359         initialized = 1;
360         populate_user_list();
361 }
362
363 /**
364  * lookup user in user_list.
365  *
366  * \param user: must initially contain the name of the user and is filled
367  * in by this function on success.
368  *
369  * \return 1 on success and < 0 on errors.
370  */
371 int _get_user(struct _user *user)
372 {
373         struct _user *u;
374         list_for_each_entry(u, &_user_list, node) {
375                 if (strcmp(u->name, user->name))
376                         continue;
377                 *user = *u;
378                 return 1;
379         }
380         return -E_BAD_USER;
381 }
382
383 static void init_selector(void)
384 {
385         int i, ret;
386
387         mmd->selector_change = -1; /* no change nec., set to new num by com_chs */
388         if (!conf.selector_given)
389                 goto random;
390         for (i = 0; selectors[i].name; i++) {
391                 if (strcmp(selectors[i].name, conf.selector_arg))
392                         continue;
393                 PARA_NOTICE_LOG("initializing %s audio file selector\n",
394                         selectors[i].name);
395                 ret = selectors[i].init(&selectors[i]);
396                 if (ret < 0) {
397                         PARA_WARNING_LOG("%s", PARA_STRERROR(-ret));
398                         break;
399                 }
400                 mmd->selector_num = i;
401                 return;
402         }
403         PARA_WARNING_LOG("%s", "falling back to the random selector\n");
404 random:
405         mmd->selector_num = 0;
406         selectors[0].init(&selectors[0]); /* always successful */
407 }
408
409 static unsigned init_network(void)
410 {
411         int fd, ret = init_tcp_socket(conf.port_arg);
412
413         if (ret < 0)
414                 goto err;
415         fd = ret;
416         ret = mark_fd_nonblock(fd);
417         if (ret < 0)
418                 goto err;
419         return fd;
420 err:
421         PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
422         exit(EXIT_FAILURE);
423 }
424
425 static void init_random_seed(void)
426 {
427         int fd, ret = -1, len = sizeof(unsigned int);
428         unsigned int seed;
429
430         fd = open("/dev/urandom", O_RDONLY);
431         if (fd < 0)
432                 goto out;
433         ret = -2;
434         if (read(fd, &seed, len) != len)
435                 goto out;
436         srandom(seed);
437         ret = 1;
438 out:
439         if (fd >= 0)
440                 close(fd);
441         if (ret > 0)
442                 return;
443         PARA_EMERG_LOG("can not seed pseudo random generator (ret = %d)\n",
444                 ret);
445         exit(EXIT_FAILURE);
446 }
447
448 static unsigned do_inits(int argc, char **argv)
449 {
450         /* connector's address information */
451         int sockfd;
452
453         init_random_seed();
454         /* parse command line options */
455         server_cmdline_parser(argc, argv, &conf);
456         para_drop_privileges(conf.user_arg, conf.group_arg);
457         /* parse config file, open log and set defaults */
458         parse_config(0);
459         log_welcome("para_server", conf.loglevel_arg);
460         shm_init(); /* init mmd struct */
461         server_uptime(UPTIME_SET); /* reset server uptime */
462         init_user_list();
463         /* become daemon */
464         if (conf.daemon_given)
465                 daemon_init();
466         init_selector();
467         PARA_NOTICE_LOG("%s", "initializing audio file sender\n");
468         /* audio file sender */
469         afs_init();
470         mmd->server_pid = getpid();
471         setup_signal_handling();
472         mmd_lock();
473         /* init network socket */
474         PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
475         sockfd = init_network();
476         PARA_NOTICE_LOG("%s", "init complete\n");
477         return sockfd;
478 }
479
480 static void change_selector(void)
481 {
482         int ret, old = mmd->selector_num, new = mmd->selector_change;
483
484         selectors[old].shutdown();
485         ret = selectors[new].init(&selectors[new]);
486         mmd->selector_change = -1; /* reset */
487         if (ret >= 0) {
488                 mmd->selector_num = new;
489                 return;
490         }
491         /* init failed */
492         PARA_ERROR_LOG("%s -- switching to the random selector\n", PARA_STRERROR(-ret));
493         selectors[0].init(&selectors[0]);
494         mmd->selector_num = 0;
495 }
496
497 /*
498  * called when server gets SIGHUP or when client invokes hup command.
499  */
500 static void handle_sighup(void)
501 {
502         PARA_NOTICE_LOG("%s", "SIGHUP\n");
503         close_log(logfile); /* gets reopened if necessary by parse_config */
504         logfile = NULL;
505         parse_config(1); /* reopens log */
506         mmd->selector_change = mmd->selector_num; /* do not change selector.. */
507         change_selector(); /* .. just reload */
508 }
509
510 static void status_refresh(void)
511 {
512         static int prev_uptime = -1, prev_events = -1;
513         int uptime = server_uptime(UPTIME_GET), ret = 1;
514
515         if (prev_events != mmd->events)
516                 goto out;
517         if (mmd->new_afs_status_flags != mmd->afs_status_flags)
518                 goto out;
519         if (uptime / 60 != prev_uptime / 60)
520                 goto out;
521         ret = 0;
522 out:
523         prev_uptime = uptime;
524         prev_events = mmd->events;
525         mmd->afs_status_flags = mmd->new_afs_status_flags;
526         if (ret) {
527                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
528                         mmd->events, mmd->audio_format);
529                 killpg(0, SIGUSR1);
530         }
531 }
532
533 /*
534  * MAIN
535  */
536 int main(int argc, char *argv[])
537 {
538         /* listen on sock_fd, new connection on new_fd */
539         int sockfd, new_fd;
540         struct sockaddr_in their_addr;
541         int i, max_fileno, ret;
542         pid_t chld_pid;
543         fd_set rfds, wfds;
544         struct timeval *timeout;
545
546         valid_fd_012();
547         sockfd = do_inits(argc, argv);
548 repeat:
549         FD_ZERO(&rfds);
550         FD_ZERO(&wfds);
551         max_fileno = -1;
552         /* check socket and signal pipe in any case */
553         para_fd_set(sockfd, &rfds, &max_fileno);
554         para_fd_set(signal_pipe, &rfds, &max_fileno);
555         timeout = afs_preselect();
556         status_refresh();
557         for (i = 0; senders[i].name; i++) {
558                 if (senders[i].status != SENDER_ON)
559                         continue;
560                 if (!senders[i].pre_select)
561                         continue;
562                 senders[i].pre_select( &max_fileno, &rfds, &wfds);
563         }
564         if (selectors[mmd->selector_num].pre_select) {
565                 ret = selectors[mmd->selector_num].pre_select(&rfds, &wfds);
566                 max_fileno = PARA_MAX(max_fileno, ret);
567         }
568         mmd_unlock();
569         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
570         mmd_lock();
571         if (mmd->selector_change >= 0)
572                 change_selector();
573         if (selectors[mmd->selector_num].post_select)
574                 selectors[mmd->selector_num].post_select(&rfds, &wfds);
575         if (ret < 0)
576                 goto repeat;
577         for (i = 0; senders[i].name; i++) {
578                 if (senders[i].status != SENDER_ON)
579                         continue;
580                 if (!senders[i].post_select)
581                         continue;
582                 senders[i].post_select(&rfds, &wfds);
583         }
584         afs_send_chunk();
585         status_refresh();
586         if (FD_ISSET(signal_pipe, &rfds)) {
587                 int sig;
588                 sig = para_next_signal();
589                 switch (sig) {
590                 case SIGHUP:
591                         handle_sighup();
592                         break;
593                 case SIGCHLD:
594                         para_reap_children();
595                         break;
596                 /* die on sigint/sigterm. Kill all children too. */
597                 case SIGINT:
598                 case SIGTERM:
599                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
600                         kill(0, SIGTERM);
601                         selectors[mmd->selector_num].shutdown();
602                         mutex_destroy(mmd_mutex);
603                         shm_detach(mmd);
604                         shm_destroy(mmd_shm_id);
605                         exit(EXIT_FAILURE);
606                 }
607         }
608         if (mmd->sender_cmd_data.cmd_num >= 0) {
609                 int num = mmd->sender_cmd_data.cmd_num,
610                         s = mmd->sender_cmd_data.sender_num;
611
612                 if (senders[s].client_cmds[num])
613                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
614                 mmd->sender_cmd_data.cmd_num = -1;
615         }
616         if (!FD_ISSET(sockfd, &rfds))
617                 goto repeat;
618
619         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
620         if (new_fd < 0)
621                 goto repeat;
622         PARA_INFO_LOG("got connection from %s, forking\n",
623                 inet_ntoa(their_addr.sin_addr));
624         mmd->num_connects++;
625         mmd->active_connections++;
626         random();
627         chld_pid = fork();
628         if (chld_pid < 0) {
629                 PARA_CRIT_LOG("%s", "fork failed\n");
630                 goto repeat;
631         }
632         if (chld_pid) {
633                 close(new_fd);
634                 /* parent keeps accepting connections */
635                 goto repeat;
636         }
637         alarm(ALARM_TIMEOUT);
638         close_listed_fds();
639         close(sockfd); /* child doesn't need the listener */
640         /*
641          * put info on who we are serving into argv[0] to make
642          * client ip visible in top/ps
643          */
644         for (i = argc - 1; i >= 0; i--)
645                 memset(argv[i], 0, strlen(argv[i]));
646         sprintf(argv[0], "para_server (serving %s)",
647                 inet_ntoa(their_addr.sin_addr));
648         return handle_connect(new_fd, &their_addr);
649 }