]> git.tuebingen.mpg.de Git - paraslash.git/blob - server.c
Init mmd->sender_cmd_data.cmd_num in vss_init().
[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 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         return;
206 err_out:
207         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
208         exit(EXIT_FAILURE);
209 }
210
211 /**
212  * lock the shared memory area containing the mmd struct
213  *
214  * \sa semop(2), struct misc_meta_data.
215  */
216 void mmd_lock(void)
217 {
218         mutex_lock(mmd_mutex);
219 }
220
221 /**
222  * unlock the shared memory area containing the mmd struct
223  *
224  * \sa semop(2), struct misc_meta_data
225  */
226
227 void mmd_unlock(void)
228 {
229         mutex_unlock(mmd_mutex);
230 }
231
232 static void parse_config(int override)
233 {
234         char *home = para_homedir();
235         struct stat statbuf;
236         int ret;
237         char *cf;
238
239         if (conf.config_file_given)
240                 cf = para_strdup(conf.config_file_arg);
241         else
242                 cf = make_message("%s/.paraslash/server.conf", home);
243         free(user_list_file);
244         if (!conf.user_list_given)
245                 user_list_file = make_message("%s/.paraslash/server.users", home);
246         else
247                 user_list_file = para_strdup(conf.user_list_arg);
248         ret = stat(cf, &statbuf);
249         if (ret && conf.config_file_given) {
250                 ret = -1;
251                 PARA_EMERG_LOG("can not stat config file %s\n", cf);
252                 goto out;
253         }
254         if (!ret) {
255                 int tmp = conf.daemon_given;
256                 struct server_cmdline_parser_params params = {
257                         .override = override,
258                         .initialize = 0,
259                         .check_required = 1,
260                         .check_ambiguity = 0,
261                         .print_errors = 1
262                 };
263                 server_cmdline_parser_config_file(cf, &conf, &params);
264                 conf.daemon_given = tmp;
265         }
266         if (conf.logfile_given)
267                 logfile = open_log(conf.logfile_arg);
268         ret = 1;
269 out:
270         free(cf);
271         free(home);
272         if (ret > 0)
273                 return;
274         free(user_list_file);
275         user_list_file = NULL;
276         exit(EXIT_FAILURE);
277 }
278
279 static void setup_signal_handling(void)
280 {
281         signal_pipe = para_signal_init(); /* always successful */
282
283         PARA_NOTICE_LOG("setting up signal handlers\n");
284         if (para_install_sighandler(SIGINT) < 0)
285                 goto err;
286         if (para_install_sighandler(SIGTERM) < 0)
287                 goto err;
288         if (para_install_sighandler(SIGHUP) < 0)
289                 goto err;
290         if (para_install_sighandler(SIGCHLD) < 0)
291                 goto err;
292         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
293                 goto err;
294         if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
295                 goto err;
296         add_close_on_fork_list(signal_pipe);
297         return;
298 err:
299         PARA_EMERG_LOG("could not install signal handlers\n");
300         exit(EXIT_FAILURE);
301 }
302
303 static unsigned init_network(void)
304 {
305         int fd, ret = para_listen(AF_UNSPEC, IPPROTO_TCP, conf.port_arg);
306
307         if (ret < 0)
308                 goto err;
309         fd = ret;
310         ret = mark_fd_nonblocking(fd);
311         if (ret < 0)
312                 goto err;
313         add_close_on_fork_list(fd); /* child doesn't need the listener */
314         return fd;
315 err:
316         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
317         exit(EXIT_FAILURE);
318 }
319
320 static void init_random_seed(void)
321 {
322         unsigned int seed;
323         int fd, ret = para_open("/dev/urandom", O_RDONLY, 0);
324
325         if (ret < 0)
326                 goto err;
327         fd = ret;
328         ret = read(fd, &seed, sizeof(seed));
329         if (ret < 0) {
330                 ret = -ERRNO_TO_PARA_ERROR(errno);
331                 goto out;
332         }
333         if (ret != sizeof(seed)) {
334                 ret = -ERRNO_TO_PARA_ERROR(EIO);
335                 goto out;
336         }
337         srandom(seed);
338         ret = 1;
339 out:
340         close(fd);
341         if (ret >= 0)
342                 return;
343 err:
344         PARA_EMERG_LOG("can not seed pseudo random number generator: %s\n",
345                 para_strerror(-ret));
346         exit(EXIT_FAILURE);
347 }
348
349 uint32_t afs_socket_cookie;
350 int afs_socket;
351 static pid_t afs_pid;
352
353 static void init_afs(void)
354 {
355         int ret, afs_server_socket[2];
356
357         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
358         if (ret < 0)
359                 exit(EXIT_FAILURE);
360         afs_socket_cookie = para_random((uint32_t)-1);
361         afs_pid = fork();
362         if (afs_pid < 0)
363                 exit(EXIT_FAILURE);
364         if (!afs_pid) { /* child (afs) */
365                 close(afs_server_socket[0]);
366                 afs_init(afs_socket_cookie, afs_server_socket[1]);
367         }
368         close(afs_server_socket[1]);
369         afs_socket = afs_server_socket[0];
370         ret = mark_fd_nonblocking(afs_socket);
371         if (ret < 0)
372                 exit(EXIT_FAILURE);
373         add_close_on_fork_list(afs_socket);
374         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n", afs_socket,
375                 (unsigned) afs_socket_cookie);
376 }
377
378 static unsigned server_init(int argc, char **argv)
379 {
380         /* connector's address information */
381         int sockfd;
382         struct server_cmdline_parser_params params = {
383                 .override = 0,
384                 .initialize = 1,
385                 .check_required = 0,
386                 .check_ambiguity = 0,
387                 .print_errors = 1
388         };
389         init_random_seed();
390         /* parse command line options */
391         server_cmdline_parser_ext(argc, argv, &conf, &params);
392         HANDLE_VERSION_FLAG("server", conf);
393         para_drop_privileges(conf.user_arg, conf.group_arg);
394         /* parse config file, open log and set defaults */
395         parse_config(0);
396         log_welcome("para_server", conf.loglevel_arg);
397         shm_init(); /* init mmd struct */
398         server_uptime(UPTIME_SET); /* reset server uptime */
399         init_user_list(user_list_file);
400         /* become daemon */
401         if (conf.daemon_given)
402                 daemon_init();
403         PARA_NOTICE_LOG("initializing audio format handlers\n");
404         afh_init();
405         PARA_NOTICE_LOG("initializing virtual streaming system\n");
406         mmd->server_pid = getpid();
407         setup_signal_handling();
408         PARA_NOTICE_LOG("initializing the audio file selector\n");
409         init_afs();
410         vss_init();
411         mmd_lock();
412         /* init network socket */
413         PARA_NOTICE_LOG("initializing tcp command socket\n");
414         sockfd = init_network();
415         PARA_NOTICE_LOG("server init complete\n");
416         return sockfd;
417 }
418
419 /*
420  * called when server gets SIGHUP or when client invokes hup command.
421  */
422 static void handle_sighup(void)
423 {
424         PARA_NOTICE_LOG("SIGHUP\n");
425         close_log(logfile); /* gets reopened if necessary by parse_config */
426         logfile = NULL;
427         parse_config(1); /* reopens log */
428         init_user_list(user_list_file); /* reload user list */
429         if (afs_pid)
430                 kill(afs_pid, SIGHUP);
431 }
432
433 static void status_refresh(void)
434 {
435         static int prev_uptime = -1, prev_events = -1;
436         int uptime = server_uptime(UPTIME_GET), ret = 1;
437
438         if (prev_events != mmd->events)
439                 goto out;
440         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
441                 goto out;
442         if (uptime / 60 != prev_uptime / 60)
443                 goto out;
444         ret = 0;
445 out:
446         prev_uptime = uptime;
447         prev_events = mmd->events;
448         mmd->vss_status_flags = mmd->new_vss_status_flags;
449         if (ret) {
450                 PARA_DEBUG_LOG("%d events, forcing status update\n",
451                         mmd->events);
452                 killpg(0, SIGUSR1);
453         }
454 }
455
456 /**
457  * the main function of para_server
458  *
459  * \param argc usual argument count
460  * \param argv usual argument vector
461  *
462  * \return EXIT_SUCCESS or EXIT_FAILURE
463  *
464  */
465 int main(int argc, char *argv[])
466 {
467         /* listen on sock_fd, new connection on new_fd */
468         int sockfd, new_fd;
469         char *peer_name;
470         int i, max_fileno, ret;
471         pid_t chld_pid;
472         fd_set rfds, wfds;
473         struct timeval *timeout;
474
475         valid_fd_012();
476         sockfd = server_init(argc, argv);
477 repeat:
478         FD_ZERO(&rfds);
479         FD_ZERO(&wfds);
480         max_fileno = -1;
481         /* check socket and signal pipe in any case */
482         para_fd_set(sockfd, &rfds, &max_fileno);
483         para_fd_set(signal_pipe, &rfds, &max_fileno);
484         timeout = vss_preselect(&rfds, &wfds, &max_fileno);
485         status_refresh();
486         mmd_unlock();
487         ret = para_select(max_fileno + 1, &rfds, &wfds, timeout);
488         mmd_lock();
489         if (ret < 0)
490                 goto repeat;
491         vss_post_select(&rfds, &wfds);
492         status_refresh();
493         if (FD_ISSET(signal_pipe, &rfds)) {
494                 int sig;
495                 pid_t pid;
496                 sig = para_next_signal();
497                 switch (sig) {
498                 case SIGHUP:
499                         handle_sighup();
500                         break;
501                 case SIGCHLD:
502                         for (;;) {
503                                 ret = para_reap_child(&pid);
504                                 if (ret <= 0)
505                                         break;
506                                 if (pid != afs_pid)
507                                         continue;
508                                 PARA_EMERG_LOG("fatal: afs died\n");
509                                 goto genocide;
510                         }
511                         break;
512                 /* die on sigint/sigterm. Kill all children too. */
513                 case SIGINT:
514                 case SIGTERM:
515                         PARA_EMERG_LOG("terminating on signal %d\n", sig);
516 genocide:
517                         kill(0, SIGTERM);
518                         mutex_destroy(mmd_mutex);
519                         shm_detach(mmd);
520                         shm_destroy(mmd_shm_id);
521
522                         exit(EXIT_FAILURE);
523                 }
524         }
525         if (!FD_ISSET(sockfd, &rfds))
526                 goto repeat;
527
528         new_fd = para_accept(sockfd, NULL, 0);
529         if (new_fd < 0)
530                 goto repeat;
531         peer_name = remote_name(new_fd);
532         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
533         mmd->num_connects++;
534         mmd->active_connections++;
535         random();
536         chld_pid = fork();
537         if (chld_pid < 0) {
538                 PARA_CRIT_LOG("fork failed\n");
539                 goto repeat;
540         }
541         if (chld_pid) {
542                 close(new_fd);
543                 /* parent keeps accepting connections */
544                 goto repeat;
545         }
546         alarm(ALARM_TIMEOUT);
547         close_listed_fds();
548         para_signal_shutdown();
549         /*
550          * put info on who we are serving into argv[0] to make
551          * client ip visible in top/ps
552          */
553         for (i = argc - 1; i >= 0; i--)
554                 memset(argv[i], 0, strlen(argv[i]));
555         sprintf(argv[0], "para_server (serving %s)", peer_name);
556         return handle_connect(new_fd, peer_name);
557 }