Rename instances of struct afh_info from "afi" to "afhi".
[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 /**
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 \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  *
55  * Low-level data structures:
56  *
57  *      - Doubly linked lists: \ref list.h,
58  *      - Red-black trees: \ref rbtree.h, \ref rbtree.c,
59  *      - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
60  *      - Hashing: \ref hash.h, \ref sha1.h, \ref sha1.c,
61  *      - Crypto: \ref crypt.c.
62  *
63  */
64
65 #include <signal.h>
66 #include <sys/types.h>
67 #include <dirent.h>
68
69 #include "para.h"
70 #include "error.h"
71 #include "server.cmdline.h"
72 #include "afh.h"
73 #include "string.h"
74 #include "afs.h"
75 #include "server.h"
76 #include "vss.h"
77 #include "config.h"
78 #include "close_on_fork.h"
79 #include "send.h"
80 #include "net.h"
81 #include "daemon.h"
82 #include "ipc.h"
83 #include "fd.h"
84 #include "list.h"
85 #include "sched.h"
86 #include "signal.h"
87 #include "user_list.h"
88
89 /** define the array of error lists needed by para_server */
90 INIT_SERVER_ERRLISTS;
91
92 /** shut down non-authorized connections after that many seconds */
93 #define ALARM_TIMEOUT 10
94
95 /**
96  * Pointer to shared memory area for communication between para_server
97  * and its children. Exported to vss.c. command.c and to afs.
98  */
99 struct misc_meta_data *mmd;
100
101 /**
102  * the configuration of para_server
103  *
104  * It also contains the options for the audio file selector, audio format
105  * handler and all supported senders.
106  */
107 struct server_args_info conf;
108
109 /** the file containing user information (public key, permissions) */
110 char *user_list_file = NULL;
111
112 extern void dccp_send_init(struct sender *);
113 extern void http_send_init(struct sender *);
114 extern void ortp_send_init(struct sender *);
115
116 /** the list of supported senders */
117 struct sender senders[] = {
118         {
119                 .name = "http",
120                 .init = http_send_init,
121         },
122         {
123                 .name = "dccp",
124                 .init = dccp_send_init,
125         },
126 #ifdef HAVE_ORTP
127         {
128                 .name = "ortp",
129                 .init = ortp_send_init,
130         },
131 #endif
132         {
133                 .name = NULL,
134         }
135 };
136
137
138 /* global variables for server-internal use */
139 static FILE *logfile;
140 static int mmd_mutex, mmd_shm_id;
141 static int signal_pipe;
142
143 /**
144  * para_server's log function
145  *
146  * \param ll the log level
147  * \param fmt the format string describing the log message
148  */
149 void para_log(int ll, const char* fmt,...)
150 {
151         va_list argp;
152         FILE *outfd;
153         struct tm *tm;
154         time_t t1;
155         char str[MAXLINE] = "";
156         pid_t mypid;
157
158         if (ll < conf.loglevel_arg)
159                 return;
160         outfd = logfile? logfile : stderr;
161         time(&t1);
162         tm = localtime(&t1);
163         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
164         fprintf(outfd, "%s ", str);
165         if (conf.loglevel_arg <= INFO)
166                 fprintf(outfd, "%i: ", ll);
167         mypid = getpid();
168         if (conf.loglevel_arg <= INFO)
169                 fprintf(outfd, "(%d) ", mypid);
170         va_start(argp, fmt);
171         vfprintf(outfd, fmt, argp);
172         va_end(argp);
173 }
174
175 /*
176  * setup shared memory area and get mutex for locking
177  */
178 static void shm_init(void)
179 {
180         void *shm;
181         int ret = shm_new(sizeof(struct misc_meta_data));
182
183         if (ret < 0)
184                 goto err_out;
185
186         ret = shm_attach(ret, ATTACH_RW, &shm);
187         if (ret < 0)
188                 goto err_out;
189         mmd = shm;
190         mmd_shm_id = ret;
191
192         ret = mutex_new();
193         if (ret < 0)
194                 goto err_out;
195         mmd_mutex = ret;
196
197         mmd->num_played = 0;
198         mmd->num_commands = 0;
199         mmd->events = 0;
200         mmd->num_connects = 0;
201         mmd->active_connections = 0;
202         strcpy(mmd->afd.path, "(none)");
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         int ret = 0;
288
289         signal_pipe = para_signal_init();
290         PARA_NOTICE_LOG("%s", "setting up signal handlers\n");
291         ret += para_install_sighandler(SIGINT);
292         ret += para_install_sighandler(SIGTERM);
293         ret += para_install_sighandler(SIGHUP);
294         ret += para_install_sighandler(SIGCHLD);
295         ret += para_install_sighandler(SIGUSR1);
296         signal(SIGPIPE, SIG_IGN);
297         if (ret != 5) {
298                 PARA_EMERG_LOG("%s", "could not install signal handlers\n");
299                 exit(EXIT_FAILURE);
300         }
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;
322         unsigned int seed;
323         size_t len = sizeof(unsigned int);
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 uint32_t afs_socket_cookie;
344 int afs_socket;
345 static pid_t afs_pid;
346
347 static void init_afs(void)
348 {
349         int ret, afs_server_socket[2];
350
351         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
352         if (ret < 0)
353                 exit(EXIT_FAILURE);
354         afs_socket_cookie = para_random((uint32_t)-1);
355         afs_pid = fork();
356         if (afs_pid < 0)
357                 exit(EXIT_FAILURE);
358         if (!afs_pid) { /* child (afs) */
359                 close(afs_server_socket[0]);
360                 afs_init(afs_socket_cookie, afs_server_socket[1]);
361         }
362         close(afs_server_socket[1]);
363         afs_socket = afs_server_socket[0];
364         ret = mark_fd_nonblock(afs_socket);
365         if (ret < 0)
366                 exit(EXIT_FAILURE);
367         add_close_on_fork_list(afs_socket);
368         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n", afs_socket,
369                 (unsigned) afs_socket_cookie);
370 }
371
372
373 static unsigned server_init(int argc, char **argv)
374 {
375         /* connector's address information */
376         int sockfd;
377
378         init_random_seed();
379         /* parse command line options */
380         server_cmdline_parser(argc, argv, &conf);
381         HANDLE_VERSION_FLAG("server", conf);
382         para_drop_privileges(conf.user_arg, conf.group_arg);
383         /* parse config file, open log and set defaults */
384         parse_config(0);
385         log_welcome("para_server", conf.loglevel_arg);
386         shm_init(); /* init mmd struct */
387         server_uptime(UPTIME_SET); /* reset server uptime */
388         init_user_list(user_list_file);
389         /* become daemon */
390         if (conf.daemon_given)
391                 daemon_init();
392         PARA_NOTICE_LOG("initializing audio format handlers\n");
393         afh_init();
394         PARA_NOTICE_LOG("initializing virtual streaming system\n");
395         vss_init();
396         mmd->server_pid = getpid();
397         setup_signal_handling();
398         PARA_NOTICE_LOG("initializing the audio file selector\n");
399         init_afs();
400         mmd_lock();
401         /* init network socket */
402         PARA_NOTICE_LOG("initializing tcp command socket\n");
403         sockfd = init_network();
404         PARA_NOTICE_LOG("server init complete\n");
405         return sockfd;
406 }
407
408 /*
409  * called when server gets SIGHUP or when client invokes hup command.
410  */
411 static void handle_sighup(void)
412 {
413         PARA_NOTICE_LOG("%s", "SIGHUP\n");
414         close_log(logfile); /* gets reopened if necessary by parse_config */
415         logfile = NULL;
416         parse_config(1); /* reopens log */
417         init_user_list(user_list_file); /* reload user list */
418         if (afs_pid)
419                 kill(afs_pid, SIGHUP);
420 }
421
422 static void status_refresh(void)
423 {
424         static int prev_uptime = -1, prev_events = -1;
425         int uptime = server_uptime(UPTIME_GET), ret = 1;
426
427         if (prev_events != mmd->events)
428                 goto out;
429         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
430                 goto out;
431         if (uptime / 60 != prev_uptime / 60)
432                 goto out;
433         ret = 0;
434 out:
435         prev_uptime = uptime;
436         prev_events = mmd->events;
437         mmd->vss_status_flags = mmd->new_vss_status_flags;
438         if (ret) {
439                 PARA_DEBUG_LOG("%d events, forcing status update\n",
440                         mmd->events);
441                 killpg(0, SIGUSR1);
442         }
443 }
444
445 /**
446  * the main function of para_server
447  *
448  * \param argc usual argument count
449  * \param argv usual argument vector
450  *
451  * \return EXIT_SUCCESS or EXIT_FAILURE
452  *
453  */
454 int main(int argc, char *argv[])
455 {
456         /* listen on sock_fd, new connection on new_fd */
457         int sockfd, new_fd;
458         struct sockaddr_in their_addr;
459         int i, max_fileno, ret;
460         pid_t chld_pid;
461         fd_set rfds, wfds;
462         struct timeval *timeout;
463
464         valid_fd_012();
465         sockfd = server_init(argc, argv);
466 repeat:
467         FD_ZERO(&rfds);
468         FD_ZERO(&wfds);
469         max_fileno = -1;
470         /* check socket and signal pipe in any case */
471         para_fd_set(sockfd, &rfds, &max_fileno);
472         para_fd_set(signal_pipe, &rfds, &max_fileno);
473         timeout = vss_preselect(&rfds, &wfds, &max_fileno);
474         status_refresh();
475         for (i = 0; senders[i].name; i++) {
476                 if (senders[i].status != SENDER_ON)
477                         continue;
478                 if (!senders[i].pre_select)
479                         continue;
480                 senders[i].pre_select(&max_fileno, &rfds, &wfds);
481         }
482         mmd_unlock();
483         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
484         mmd_lock();
485         vss_post_select(&rfds, &wfds);
486         if (ret < 0)
487                 goto repeat;
488         for (i = 0; senders[i].name; i++) {
489                 if (senders[i].status != SENDER_ON)
490                         continue;
491                 if (!senders[i].post_select)
492                         continue;
493                 senders[i].post_select(&rfds, &wfds);
494         }
495         vss_send_chunk();
496         status_refresh();
497         if (FD_ISSET(signal_pipe, &rfds)) {
498                 int sig;
499                 pid_t pid;
500                 sig = para_next_signal();
501                 switch (sig) {
502                 case SIGHUP:
503                         handle_sighup();
504                         break;
505                 case SIGCHLD:
506                         for (;;) {
507                                 ret = para_reap_child(&pid);
508                                 if (ret <= 0)
509                                         break;
510                                 if (pid != afs_pid)
511                                         continue;
512                                 PARA_EMERG_LOG("fatal: afs died\n");
513                                 goto genocide;
514                         }
515                         break;
516                 /* die on sigint/sigterm. Kill all children too. */
517                 case SIGINT:
518                 case SIGTERM:
519                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
520 genocide:
521                         kill(0, SIGTERM);
522                         mutex_destroy(mmd_mutex);
523                         shm_detach(mmd);
524                         shm_destroy(mmd_shm_id);
525
526                         exit(EXIT_FAILURE);
527                 }
528         }
529         if (mmd->sender_cmd_data.cmd_num >= 0) {
530                 int num = mmd->sender_cmd_data.cmd_num,
531                         s = mmd->sender_cmd_data.sender_num;
532
533                 if (senders[s].client_cmds[num])
534                         senders[s].client_cmds[num](&mmd->sender_cmd_data);
535                 mmd->sender_cmd_data.cmd_num = -1;
536         }
537         if (!FD_ISSET(sockfd, &rfds))
538                 goto repeat;
539
540         new_fd = para_accept(sockfd, &their_addr, sizeof(struct sockaddr_in));
541         if (new_fd < 0)
542                 goto repeat;
543         PARA_INFO_LOG("got connection from %s, forking\n",
544                 inet_ntoa(their_addr.sin_addr));
545         mmd->num_connects++;
546         mmd->active_connections++;
547         random();
548         chld_pid = fork();
549         if (chld_pid < 0) {
550                 PARA_CRIT_LOG("%s", "fork failed\n");
551                 goto repeat;
552         }
553         if (chld_pid) {
554                 close(new_fd);
555                 /* parent keeps accepting connections */
556                 goto repeat;
557         }
558         alarm(ALARM_TIMEOUT);
559         close_listed_fds();
560         close(sockfd); /* child doesn't need the listener */
561         /*
562          * put info on who we are serving into argv[0] to make
563          * client ip visible in top/ps
564          */
565         for (i = argc - 1; i >= 0; i--)
566                 memset(argv[i], 0, strlen(argv[i]));
567         sprintf(argv[0], "para_server (serving %s)",
568                 inet_ntoa(their_addr.sin_addr));
569         return handle_connect(new_fd, &their_addr);
570 }