remove README.mysql.
[paraslash.git] / server.c
1 /*
2  * Copyright (C) 1997-2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file server.c Paraslash's main server */
8
9
10 /** \mainpage Paraslash API Reference
11  *
12  *  Good starting points for reading are probably \ref audio_file_selector,
13  *  \ref sender, \ref receiver, \ref receiver_node, \ref filter, \ref
14  *  filter_node.
15  *
16  */
17
18 #include <signal.h>
19 #include <sys/types.h>
20 #include <dirent.h>
21
22 #include "para.h"
23 #include "error.h"
24 #include "server.cmdline.h"
25 #include "afh.h"
26 #include "string.h"
27 #include "afs.h"
28 #include "server.h"
29 #include "vss.h"
30 #include "config.h"
31 #include "close_on_fork.h"
32 #include "send.h"
33 #include "net.h"
34 #include "daemon.h"
35 #include "ipc.h"
36 #include "fd.h"
37 #include "list.h"
38 #include "sched.h"
39 #include "signal.h"
40 #include "user_list.h"
41
42 /** define the array of error lists needed by para_server */
43 INIT_SERVER_ERRLISTS;
44
45 /** shut down non-authorized connections after that many seconds */
46 #define ALARM_TIMEOUT 10
47
48 /**
49  * pointer to shared memory area for communication between para_server
50  * and its children. exported to vss.c. command.c and to all selectors.
51  */
52 struct misc_meta_data *mmd;
53
54 /**
55  * the configuration of para_server
56  *
57  * It also contains the options for all audio file selectors, audio format handler
58  * and all supported senders.
59  */
60 struct server_args_info conf;
61
62 /** the file containing user information (public key, permissions) */
63 char *user_list_file = NULL;
64
65 extern void dccp_send_init(struct sender *);
66 extern void http_send_init(struct sender *);
67 extern void ortp_send_init(struct sender *);
68
69 /** the list of supported senders */
70 struct sender senders[] = {
71         {
72                 .name = "http",
73                 .init = http_send_init,
74         },
75         {
76                 .name = "dccp",
77                 .init = dccp_send_init,
78         },
79 #ifdef HAVE_ORTP
80         {
81                 .name = "ortp",
82                 .init = ortp_send_init,
83         },
84 #endif
85         {
86                 .name = NULL,
87         }
88 };
89
90
91 /* global variables for server-internal use */
92 static FILE *logfile;
93 static int mmd_mutex, mmd_shm_id;
94 static int signal_pipe;
95
96 /**
97  * para_server's log function
98  *
99  * \param ll the log level
100  * \param fmt the format string describing the log message
101  */
102 void para_log(int ll, const char* fmt,...)
103 {
104         va_list argp;
105         FILE *outfd;
106         struct tm *tm;
107         time_t t1;
108         char str[MAXLINE] = "";
109         pid_t mypid;
110
111         if (ll < conf.loglevel_arg)
112                 return;
113         outfd = logfile? logfile : stderr;
114         time(&t1);
115         tm = localtime(&t1);
116         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
117         fprintf(outfd, "%s ", str);
118         if (conf.loglevel_arg <= INFO)
119                 fprintf(outfd, "%i: ", ll);
120         mypid = getpid();
121         if (conf.loglevel_arg <= INFO)
122                 fprintf(outfd, "(%d) ", mypid);
123         va_start(argp, fmt);
124         vfprintf(outfd, fmt, argp);
125         va_end(argp);
126 }
127
128 /*
129  * setup shared memory area and get mutex for locking
130  */
131 static void shm_init(void)
132 {
133         void *shm;
134         int ret = shm_new(sizeof(struct misc_meta_data));
135
136         if (ret < 0)
137                 goto err_out;
138
139         ret = shm_attach(ret, ATTACH_RW, &shm);
140         if (ret < 0)
141                 goto err_out;
142         mmd = shm;
143         mmd_shm_id = ret;
144
145         ret = mutex_new();
146         if (ret < 0)
147                 goto err_out;
148         mmd_mutex = ret;
149
150         mmd->num_played = 0;
151         mmd->num_commands = 0;
152         mmd->events = 0;
153         mmd->num_connects = 0;
154         mmd->active_connections = 0;
155         strcpy(mmd->filename, "(none)");
156         mmd->audio_format = -1;
157         mmd->vss_status_flags = VSS_NEXT;
158         mmd->new_vss_status_flags = VSS_NEXT;
159         mmd->sender_cmd_data.cmd_num = -1;
160         return;
161 err_out:
162         PARA_EMERG_LOG("%s", PARA_STRERROR(-ret));
163         exit(EXIT_FAILURE);
164 }
165
166 /**
167  * lock the shared memory area containing the mmd struct
168  *
169  * \sa semop(2), struct misc_meta_data
170  */
171 void mmd_lock(void)
172 {
173         mutex_lock(mmd_mutex);
174 }
175
176 /**
177  * unlock the shared memory area containing the mmd struct
178  *
179  * \sa semop(2), struct misc_meta_data
180  */
181
182 void mmd_unlock(void)
183 {
184         mutex_unlock(mmd_mutex);
185 }
186
187 static void parse_config(int override)
188 {
189         char *home = para_homedir();
190         struct stat statbuf;
191         int ret;
192         char *cf;
193
194         if (conf.config_file_given)
195                 cf = conf.config_file_arg;
196         else
197                 cf = make_message("%s/.paraslash/server.conf", home);
198         free(user_list_file);
199         if (!conf.user_list_given)
200                 user_list_file = make_message("%s/.paraslash/server.users", home);
201         else
202                 user_list_file = para_strdup(conf.user_list_arg);
203         ret = stat(cf, &statbuf);
204         if (ret && conf.config_file_given) {
205                 ret = -1;
206                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
207                 goto out;
208         }
209         if (!ret) {
210                 int tmp = conf.daemon_given;
211                 struct server_cmdline_parser_params params = {
212                         .override = override,
213                         .initialize = 0,
214                         .check_required = 0,
215                         .check_ambiguity = 0
216                 };
217                 server_cmdline_parser_config_file(cf, &conf, &params);
218                 conf.daemon_given = tmp;
219         }
220         /* logfile */
221         if (!conf.logfile_given && conf.daemon_given) {
222                 ret = -1;
223                 PARA_EMERG_LOG("%s", "daemon, but no log file\n");
224                 goto out;
225         }
226         if (conf.logfile_given)
227                 logfile = open_log(conf.logfile_arg);
228         ret = 1;
229 out:
230         free(cf);
231         free(home);
232         if (ret > 0)
233                 return;
234         free(user_list_file);
235         user_list_file = NULL;
236         exit(EXIT_FAILURE);
237 }
238
239 static void setup_signal_handling(void)
240 {
241         int ret = 0;
242
243         signal_pipe = para_signal_init();
244         PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
245         ret += para_install_sighandler(SIGINT);
246         ret += para_install_sighandler(SIGTERM);
247         ret += para_install_sighandler(SIGHUP);
248         ret += para_install_sighandler(SIGCHLD);
249         ret += para_install_sighandler(SIGUSR1);
250         signal(SIGPIPE, SIG_IGN);
251         if (ret != 5) {
252                 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
253                 exit(EXIT_FAILURE);
254         }
255 }
256
257 static unsigned init_network(void)
258 {
259         int fd, ret = init_tcp_socket(conf.port_arg);
260
261         if (ret < 0)
262                 goto err;
263         fd = ret;
264         ret = mark_fd_nonblock(fd);
265         if (ret < 0)
266                 goto err;
267         return fd;
268 err:
269         PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
270         exit(EXIT_FAILURE);
271 }
272
273 static void init_random_seed(void)
274 {
275         int fd, ret = -1;
276         unsigned int seed;
277         size_t len = sizeof(unsigned int);
278
279         fd = open("/dev/urandom", O_RDONLY);
280         if (fd < 0)
281                 goto out;
282         ret = -2;
283         if (read(fd, &seed, len) != len)
284                 goto out;
285         srandom(seed);
286         ret = 1;
287 out:
288         if (fd >= 0)
289                 close(fd);
290         if (ret > 0)
291                 return;
292         PARA_EMERG_LOG("can not seed pseudo random generator (ret = %d)\n",
293                 ret);
294         exit(EXIT_FAILURE);
295 }
296
297 uint32_t afs_socket_cookie;
298 int afs_socket;
299 static pid_t afs_pid;
300
301 static void init_afs(void)
302 {
303         int ret, afs_server_socket[2];
304
305         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
306         if (ret < 0)
307                 exit(EXIT_FAILURE);
308         afs_socket_cookie = para_random((uint32_t)-1);
309         afs_pid = fork();
310         if (afs_pid < 0)
311                 exit(EXIT_FAILURE);
312         if (!afs_pid) { /* child (afs) */
313                 close(afs_server_socket[0]);
314                 afs_init(afs_socket_cookie, afs_server_socket[1]);
315         }
316         close(afs_server_socket[1]);
317         afs_socket = afs_server_socket[0];
318         ret = mark_fd_nonblock(afs_socket);
319         if (ret < 0)
320                 exit(EXIT_FAILURE);
321         add_close_on_fork_list(afs_socket);
322         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n", afs_socket,
323                 (unsigned) afs_socket_cookie);
324 }
325
326
327 static unsigned do_inits(int argc, char **argv)
328 {
329         /* connector's address information */
330         int sockfd;
331
332         init_random_seed();
333         /* parse command line options */
334         server_cmdline_parser(argc, argv, &conf);
335         HANDLE_VERSION_FLAG("server", conf);
336         para_drop_privileges(conf.user_arg, conf.group_arg);
337         /* parse config file, open log and set defaults */
338         parse_config(0);
339         log_welcome("para_server", conf.loglevel_arg);
340         shm_init(); /* init mmd struct */
341         server_uptime(UPTIME_SET); /* reset server uptime */
342         init_user_list(user_list_file);
343         /* become daemon */
344         if (conf.daemon_given)
345                 daemon_init();
346         PARA_NOTICE_LOG("%s", "initializing virtual streaming system\n");
347         afh_init();
348         vss_init();
349         mmd->server_pid = getpid();
350         setup_signal_handling();
351         init_afs();
352         mmd_lock();
353         /* init network socket */
354         PARA_NOTICE_LOG("%s", "initializing tcp command socket\n");
355         sockfd = init_network();
356         PARA_NOTICE_LOG("%s", "init complete\n");
357         return sockfd;
358 }
359
360 /*
361  * called when server gets SIGHUP or when client invokes hup command.
362  */
363 static void handle_sighup(void)
364 {
365         PARA_NOTICE_LOG("%s", "SIGHUP\n");
366         close_log(logfile); /* gets reopened if necessary by parse_config */
367         logfile = NULL;
368         parse_config(1); /* reopens log */
369         init_user_list(user_list_file); /* reload user list */
370         if (afs_pid)
371                 kill(afs_pid, SIGHUP);
372 }
373
374 static void status_refresh(void)
375 {
376         static int prev_uptime = -1, prev_events = -1;
377         int uptime = server_uptime(UPTIME_GET), ret = 1;
378
379         if (prev_events != mmd->events)
380                 goto out;
381         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
382                 goto out;
383         if (uptime / 60 != prev_uptime / 60)
384                 goto out;
385         ret = 0;
386 out:
387         prev_uptime = uptime;
388         prev_events = mmd->events;
389         mmd->vss_status_flags = mmd->new_vss_status_flags;
390         if (ret) {
391                 PARA_DEBUG_LOG("%d events, forcing status update, af = %d\n",
392                         mmd->events, mmd->audio_format);
393                 killpg(0, SIGUSR1);
394         }
395 }
396
397 /**
398  * the main function of para_server
399  *
400  * \param argc usual argument count
401  * \param argv usual argument vector
402  *
403  * \return EXIT_SUCCESS or EXIT_FAILURE
404  *
405  */
406 int main(int argc, char *argv[])
407 {
408         /* listen on sock_fd, new connection on new_fd */
409         int sockfd, new_fd;
410         struct sockaddr_in their_addr;
411         int i, max_fileno, ret;
412         pid_t chld_pid;
413         fd_set rfds, wfds;
414         struct timeval *timeout;
415
416         valid_fd_012();
417         sockfd = do_inits(argc, argv);
418 repeat:
419         FD_ZERO(&rfds);
420         FD_ZERO(&wfds);
421         max_fileno = -1;
422         /* check socket and signal pipe in any case */
423         para_fd_set(sockfd, &rfds, &max_fileno);
424         para_fd_set(signal_pipe, &rfds, &max_fileno);
425         timeout = vss_preselect(&rfds, &wfds, &max_fileno);
426         status_refresh();
427         for (i = 0; senders[i].name; i++) {
428                 if (senders[i].status != SENDER_ON)
429                         continue;
430                 if (!senders[i].pre_select)
431                         continue;
432                 senders[i].pre_select(&max_fileno, &rfds, &wfds);
433         }
434         mmd_unlock();
435         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
436         mmd_lock();
437         vss_post_select(&rfds, &wfds);
438         if (ret < 0)
439                 goto repeat;
440         for (i = 0; senders[i].name; i++) {
441                 if (senders[i].status != SENDER_ON)
442                         continue;
443                 if (!senders[i].post_select)
444                         continue;
445                 senders[i].post_select(&rfds, &wfds);
446         }
447         vss_send_chunk();
448         status_refresh();
449         if (FD_ISSET(signal_pipe, &rfds)) {
450                 int sig;
451                 pid_t pid;
452                 sig = para_next_signal();
453                 switch (sig) {
454                 case SIGHUP:
455                         handle_sighup();
456                         break;
457                 case SIGCHLD:
458                         for (;;) {
459                                 ret = para_reap_child(&pid);
460                                 if (ret <= 0)
461                                         break;
462                                 if (pid != afs_pid)
463                                         continue;
464                                 PARA_EMERG_LOG("fatal: afs died\n");
465                                 goto genocide;
466                         }
467                         break;
468                 /* die on sigint/sigterm. Kill all children too. */
469                 case SIGINT:
470                 case SIGTERM:
471                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
472 genocide:
473                         kill(0, SIGTERM);
474                         mutex_destroy(mmd_mutex);
475                         shm_detach(mmd);
476                         shm_destroy(mmd_shm_id);
477
478                         exit(EXIT_FAILURE);
479                 }
480         }
481         if (mmd->sender_cmd_data.cmd_num >= 0) {
482                 int num = mmd->sender_cmd_data.cmd_num,
483                         s = mmd->sender_cmd_data.sender_num;
484
485                 if (senders[s].client_cmds[num])
486                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
487                 mmd->sender_cmd_data.cmd_num = -1;
488         }
489         if (!FD_ISSET(sockfd, &rfds))
490                 goto repeat;
491
492         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
493         if (new_fd < 0)
494                 goto repeat;
495         PARA_INFO_LOG("got connection from %s, forking\n",
496                 inet_ntoa(their_addr.sin_addr));
497         mmd->num_connects++;
498         mmd->active_connections++;
499         random();
500         chld_pid = fork();
501         if (chld_pid < 0) {
502                 PARA_CRIT_LOG("%s", "fork failed\n");
503                 goto repeat;
504         }
505         if (chld_pid) {
506                 close(new_fd);
507                 /* parent keeps accepting connections */
508                 goto repeat;
509         }
510         alarm(ALARM_TIMEOUT);
511         close_listed_fds();
512         close(sockfd); /* child doesn't need the listener */
513         /*
514          * put info on who we are serving into argv[0] to make
515          * client ip visible in top/ps
516          */
517         for (i = argc - 1; i >= 0; i--)
518                 memset(argv[i], 0, strlen(argv[i]));
519         sprintf(argv[0], "para_server (serving %s)",
520                 inet_ntoa(their_addr.sin_addr));
521         return handle_connect(new_fd, &their_addr);
522 }