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