vss: Include map in the vss task struct.
[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 "list.h"
81 #include "send.h"
82 #include "net.h"
83 #include "daemon.h"
84 #include "ipc.h"
85 #include "fd.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 /* global variables for server-internal use */
114 static FILE *logfile;
115 static int mmd_mutex, mmd_shm_id;
116 static int signal_pipe;
117
118 struct server_command_task {
119         /** TCP port on which para_server listens for connections. */
120         int listen_fd;
121         /** Copied from para_server's main function. */
122         int argc;
123         /** Argument vector passed to para_server's main function. */
124         char **argv;
125         /** The command task structure for scheduling. */
126         //struct task task;
127         char dummy;
128 };
129
130 /**
131  * para_server's log function
132  *
133  * \param ll the log level
134  * \param fmt the format string describing the log message
135  */
136 void para_log(int ll, const char* fmt,...)
137 {
138         va_list argp;
139         FILE *outfd;
140         struct tm *tm;
141         time_t t1;
142         char str[MAXLINE] = "";
143         pid_t mypid;
144
145         if (ll < conf.loglevel_arg)
146                 return;
147         outfd = logfile? logfile : stderr;
148         time(&t1);
149         tm = localtime(&t1);
150         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
151         fprintf(outfd, "%s ", str);
152         if (conf.loglevel_arg <= INFO)
153                 fprintf(outfd, "%i: ", ll);
154         mypid = getpid();
155         if (conf.loglevel_arg <= INFO)
156                 fprintf(outfd, "(%d) ", (int)mypid);
157         va_start(argp, fmt);
158         vfprintf(outfd, fmt, argp);
159         va_end(argp);
160 }
161
162 /*
163  * setup shared memory area and get mutex for locking
164  */
165 static void shm_init(void)
166 {
167         void *shm;
168         int ret = shm_new(sizeof(struct misc_meta_data));
169
170         if (ret < 0)
171                 goto err_out;
172
173         ret = shm_attach(ret, ATTACH_RW, &shm);
174         if (ret < 0)
175                 goto err_out;
176         mmd = shm;
177         mmd_shm_id = ret;
178
179         ret = mutex_new();
180         if (ret < 0)
181                 goto err_out;
182         mmd_mutex = ret;
183
184         mmd->num_played = 0;
185         mmd->num_commands = 0;
186         mmd->events = 0;
187         mmd->num_connects = 0;
188         mmd->active_connections = 0;
189         mmd->vss_status_flags = VSS_NEXT;
190         mmd->new_vss_status_flags = VSS_NEXT;
191         return;
192 err_out:
193         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
194         exit(EXIT_FAILURE);
195 }
196
197 /**
198  * lock the shared memory area containing the mmd struct
199  *
200  * \sa semop(2), struct misc_meta_data.
201  */
202 void mmd_lock(void)
203 {
204         mutex_lock(mmd_mutex);
205 }
206
207 /**
208  * unlock the shared memory area containing the mmd struct
209  *
210  * \sa semop(2), struct misc_meta_data
211  */
212
213 void mmd_unlock(void)
214 {
215         mutex_unlock(mmd_mutex);
216 }
217
218 static void parse_config(int override)
219 {
220         char *home = para_homedir();
221         struct stat statbuf;
222         int ret;
223         char *cf;
224
225         if (conf.config_file_given)
226                 cf = para_strdup(conf.config_file_arg);
227         else
228                 cf = make_message("%s/.paraslash/server.conf", home);
229         free(user_list_file);
230         if (!conf.user_list_given)
231                 user_list_file = make_message("%s/.paraslash/server.users", home);
232         else
233                 user_list_file = para_strdup(conf.user_list_arg);
234         ret = stat(cf, &statbuf);
235         if (ret && conf.config_file_given) {
236                 ret = -1;
237                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
238                 goto out;
239         }
240         if (!ret) {
241                 int tmp = conf.daemon_given;
242                 struct server_cmdline_parser_params params = {
243                         .override = override,
244                         .initialize = 0,
245                         .check_required = 1,
246                         .check_ambiguity = 0,
247                         .print_errors = 1
248                 };
249                 server_cmdline_parser_config_file(cf, &conf, &params);
250                 conf.daemon_given = tmp;
251         }
252         if (conf.logfile_given)
253                 logfile = open_log(conf.logfile_arg);
254         ret = 1;
255 out:
256         free(cf);
257         free(home);
258         if (ret > 0)
259                 return;
260         free(user_list_file);
261         user_list_file = NULL;
262         exit(EXIT_FAILURE);
263 }
264
265 static void setup_signal_handling(void)
266 {
267         signal_pipe = para_signal_init(); /* always successful */
268
269         PARA_NOTICE_LOG("setting up signal handlers\n");
270         if (para_install_sighandler(SIGINT) < 0)
271                 goto err;
272         if (para_install_sighandler(SIGTERM) < 0)
273                 goto err;
274         if (para_install_sighandler(SIGHUP) < 0)
275                 goto err;
276         if (para_install_sighandler(SIGCHLD) < 0)
277                 goto err;
278         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
279                 goto err;
280         if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
281                 goto err;
282         add_close_on_fork_list(signal_pipe);
283         return;
284 err:
285         PARA_EMERG_LOG("could not install signal handlers\n");
286         exit(EXIT_FAILURE);
287 }
288
289 static void init_command_task(struct server_command_task *sct)
290 {
291         int ret;
292
293         PARA_NOTICE_LOG("initializing tcp command socket\n");
294         ret = para_listen(AF_UNSPEC, IPPROTO_TCP, conf.port_arg);
295         if (ret < 0)
296                 goto err;
297         sct->listen_fd = ret;
298         ret = mark_fd_nonblocking(sct->listen_fd);
299         if (ret < 0)
300                 goto err;
301         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
302         return;
303 err:
304         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
305         exit(EXIT_FAILURE);
306 }
307
308 static void init_random_seed(void)
309 {
310         unsigned int seed;
311         int fd, ret = para_open("/dev/urandom", O_RDONLY, 0);
312
313         if (ret < 0)
314                 goto err;
315         fd = ret;
316         ret = read(fd, &seed, sizeof(seed));
317         if (ret < 0) {
318                 ret = -ERRNO_TO_PARA_ERROR(errno);
319                 goto out;
320         }
321         if (ret != sizeof(seed)) {
322                 ret = -ERRNO_TO_PARA_ERROR(EIO);
323                 goto out;
324         }
325         srandom(seed);
326         ret = 1;
327 out:
328         close(fd);
329         if (ret >= 0)
330                 return;
331 err:
332         PARA_EMERG_LOG("can not seed pseudo random number generator: %s\n",
333                 para_strerror(-ret));
334         exit(EXIT_FAILURE);
335 }
336
337 uint32_t afs_socket_cookie;
338 int afs_socket;
339 static pid_t afs_pid;
340
341 static void init_afs(void)
342 {
343         int ret, afs_server_socket[2];
344
345         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
346         if (ret < 0)
347                 exit(EXIT_FAILURE);
348         afs_socket_cookie = para_random((uint32_t)-1);
349         afs_pid = fork();
350         if (afs_pid < 0)
351                 exit(EXIT_FAILURE);
352         if (!afs_pid) { /* child (afs) */
353                 close(afs_server_socket[0]);
354                 afs_init(afs_socket_cookie, afs_server_socket[1]);
355         }
356         close(afs_server_socket[1]);
357         afs_socket = afs_server_socket[0];
358         ret = mark_fd_nonblocking(afs_socket);
359         if (ret < 0)
360                 exit(EXIT_FAILURE);
361         add_close_on_fork_list(afs_socket);
362         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n", afs_socket,
363                 (unsigned) afs_socket_cookie);
364 }
365
366 static void server_init(int argc, char **argv)
367 {
368         /* connector's address information */
369         struct server_cmdline_parser_params params = {
370                 .override = 0,
371                 .initialize = 1,
372                 .check_required = 0,
373                 .check_ambiguity = 0,
374                 .print_errors = 1
375         };
376         init_random_seed();
377         /* parse command line options */
378         server_cmdline_parser_ext(argc, argv, &conf, &params);
379         HANDLE_VERSION_FLAG("server", conf);
380         para_drop_privileges(conf.user_arg, conf.group_arg);
381         /* parse config file, open log and set defaults */
382         parse_config(0);
383         log_welcome("para_server", conf.loglevel_arg);
384         shm_init(); /* init mmd struct */
385         server_uptime(UPTIME_SET); /* reset server uptime */
386         init_user_list(user_list_file);
387         /* become daemon */
388         if (conf.daemon_given)
389                 daemon_init();
390         PARA_NOTICE_LOG("initializing audio format handlers\n");
391         afh_init();
392         mmd->server_pid = getpid();
393         setup_signal_handling();
394         PARA_NOTICE_LOG("initializing the audio file selector\n");
395         init_afs();
396         PARA_NOTICE_LOG("initializing virtual streaming system\n");
397         vss_init();
398         mmd_lock();
399         PARA_NOTICE_LOG("server init complete\n");
400 }
401
402 /*
403  * called when server gets SIGHUP or when client invokes hup command.
404  */
405 static void handle_sighup(void)
406 {
407         PARA_NOTICE_LOG("SIGHUP\n");
408         close_log(logfile); /* gets reopened if necessary by parse_config */
409         logfile = NULL;
410         parse_config(1); /* reopens log */
411         init_user_list(user_list_file); /* reload user list */
412         if (afs_pid)
413                 kill(afs_pid, SIGHUP);
414 }
415
416 static void status_refresh(void)
417 {
418         static int prev_uptime = -1, prev_events = -1;
419         int uptime = server_uptime(UPTIME_GET), ret = 1;
420
421         if (prev_events != mmd->events)
422                 goto out;
423         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
424                 goto out;
425         if (uptime / 60 != prev_uptime / 60)
426                 goto out;
427         ret = 0;
428 out:
429         prev_uptime = uptime;
430         prev_events = mmd->events;
431         mmd->vss_status_flags = mmd->new_vss_status_flags;
432         if (ret) {
433                 PARA_DEBUG_LOG("%d events, forcing status update\n",
434                         mmd->events);
435                 killpg(0, SIGUSR1);
436         }
437 }
438
439 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
440                 struct timeval *timeout_tv)
441 {
442         int ret;
443
444         status_refresh();
445         mmd_unlock();
446         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
447         mmd_lock();
448         return ret;
449 }
450
451 static void command_pre_select(int *max_fileno, fd_set *rfds, char *dummy_ptr)
452 {
453         struct server_command_task *sct = container_of(dummy_ptr, struct server_command_task, dummy);
454         para_fd_set(sct->listen_fd, rfds, max_fileno);
455 }
456
457 static void command_post_select(fd_set *rfds, char *dummy_ptr)
458 {
459         struct server_command_task *sct = container_of(dummy_ptr, struct server_command_task, dummy);
460
461         int new_fd, ret;
462         char *peer_name;
463         pid_t child_pid;
464
465         if (!FD_ISSET(sct->listen_fd, rfds))
466                 return;
467         ret = para_accept(sct->listen_fd, NULL, 0);
468         if (ret < 0)
469                 goto out;
470         new_fd = ret;
471         peer_name = remote_name(new_fd);
472         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
473         mmd->num_connects++;
474         mmd->active_connections++;
475         random();
476         child_pid = fork();
477         if (child_pid < 0) {
478                 ret = -ERRNO_TO_PARA_ERROR(errno);
479                 goto out;
480         }
481         if (child_pid) {
482                 close(new_fd);
483                 /* parent keeps accepting connections */
484                 return;
485         }
486         alarm(ALARM_TIMEOUT);
487         close_listed_fds();
488         para_signal_shutdown();
489         /*
490          * put info on who we are serving into argv[0] to make
491          * client ip visible in top/ps
492          */
493 //      for (i = argc - 1; i >= 0; i--)
494 //              memset(argv[i], 0, strlen(argv[i]));
495 //      sprintf(argv[0], "para_server (serving %s)", peer_name);
496         return handle_connect(new_fd, peer_name);
497 out:
498         if (ret < 0)
499                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
500 }
501
502 /**
503  * the main function of para_server
504  *
505  * \param argc usual argument count
506  * \param argv usual argument vector
507  *
508  * \return EXIT_SUCCESS or EXIT_FAILURE
509  *
510  */
511 int main(int argc, char *argv[])
512 {
513         int max_fileno, ret;
514         fd_set rfds, wfds;
515         struct timeval *timeout;
516         struct server_command_task server_command_task_struct;
517
518
519         valid_fd_012();
520         server_init(argc, argv);
521         init_command_task(&server_command_task_struct);
522 repeat:
523         FD_ZERO(&rfds);
524         FD_ZERO(&wfds);
525         max_fileno = -1;
526         command_pre_select(&max_fileno, &rfds, &server_command_task_struct.dummy);
527         para_fd_set(signal_pipe, &rfds, &max_fileno);
528         timeout = vss_preselect(&rfds, &wfds, &max_fileno);
529         server_select(max_fileno + 1, &rfds, &wfds, timeout);
530         vss_post_select(&rfds, &wfds);
531         if (FD_ISSET(signal_pipe, &rfds)) {
532                 int sig;
533                 pid_t pid;
534                 sig = para_next_signal();
535                 switch (sig) {
536                 case SIGHUP:
537                         handle_sighup();
538                         break;
539                 case SIGCHLD:
540                         for (;;) {
541                                 ret = para_reap_child(&pid);
542                                 if (ret <= 0)
543                                         break;
544                                 if (pid != afs_pid)
545                                         continue;
546                                 PARA_EMERG_LOG("fatal: afs died\n");
547                                 goto genocide;
548                         }
549                         break;
550                 /* die on sigint/sigterm. Kill all children too. */
551                 case SIGINT:
552                 case SIGTERM:
553                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
554 genocide:
555                         kill(0, SIGTERM);
556                         mutex_destroy(mmd_mutex);
557                         shm_detach(mmd);
558                         shm_destroy(mmd_shm_id);
559
560                         exit(EXIT_FAILURE);
561                 }
562         }
563         command_post_select(&rfds, &server_command_task_struct.dummy);
564         goto repeat;
565 }