a344b77440751a6e7017d9d7e641390a36eb157f
[paraslash.git] / server.c
1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file server.c Paraslash's main server. */
4
5 /**
6  * \mainpage Main data structures and selected APIs:
7  *
8  *      - Senders: \ref sender,
9  *      - Audio file selector: \ref afs_info, \ref afs_table,
10  *      - Audio format handler: \ref audio_format_handler, \ref afh_info
11  *      - Receivers/filters/writers: \ref receiver, \ref receiver_node,
12  *        \ref filter, \ref filter_node, \ref writer_node, \ref writer.
13  *      - Scheduling: \ref sched.h,
14  *      - Buffer trees: \ref buffer_tree.h,
15  *      - Sideband API: \ref sideband.h,
16  *      - Crypto: \ref crypt.h, \ref crypt_backend.h,
17  *      - Error subsystem: \ref error.h,
18  *      - Inter process communication: \ref ipc.h,
19  *      - Forward error correction: \ref fec.h,
20  *      - Daemons: \ref daemon.h,
21  *      - Mixer API: \ref mix.h,
22  *      - Interactive sessions: \ref interactive.h,
23  *      - File descriptors: \ref fd.h,
24  *      - Signals: \ref signal.h,
25  *      - Networking: \ref net.h,
26  *      - Time: \ref time.c,
27  *      - Doubly linked lists: \ref list.h.
28  */
29
30 #include <netinet/in.h>
31 #include <sys/socket.h>
32 #include <signal.h>
33 #include <regex.h>
34 #include <osl.h>
35 #include <sys/types.h>
36 #include <arpa/inet.h>
37 #include <sys/un.h>
38 #include <netdb.h>
39 #include <lopsub.h>
40
41 #include "server.lsg.h"
42 #include "para.h"
43 #include "error.h"
44 #include "crypt.h"
45 #include "afh.h"
46 #include "string.h"
47 #include "afs.h"
48 #include "net.h"
49 #include "server.h"
50 #include "list.h"
51 #include "send.h"
52 #include "sched.h"
53 #include "vss.h"
54 #include "config.h"
55 #include "close_on_fork.h"
56 #include "daemon.h"
57 #include "ipc.h"
58 #include "fd.h"
59 #include "signal.h"
60 #include "user_list.h"
61 #include "color.h"
62 #include "version.h"
63
64 /** Array of error strings. */
65 DEFINE_PARA_ERRLIST;
66
67 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
68
69 /** Shut down non-authorized connections after that many seconds. */
70 #define ALARM_TIMEOUT 10
71
72 /**
73  * Pointer to shared memory area for communication between para_server
74  * and its children. Exported to vss.c, command.c and to afs.
75  */
76 struct misc_meta_data *mmd;
77
78 /**
79  * The active value for all config options of para_server.
80  *
81  * It is computed by merging the parse result of the command line options with
82  * the parse result of the config file.
83  */
84 struct lls_parse_result *server_lpr = NULL;
85
86 /* Command line options (no config file options). Used in handle_sighup(). */
87 static struct lls_parse_result *cmdline_lpr;
88
89 /**
90  * A random number used to "authenticate" the afs connection.
91  *
92  * para_server picks this number by random before it forks the afs process. The
93  * command handlers know this number as well and write it to the afs socket,
94  * together with the id of the shared memory area which contains the payload of
95  * the afs command. A local process has to know this number to abuse the afs
96  * service provided by the local socket.
97  */
98 uint32_t afs_socket_cookie;
99
100 /** The mutex protecting the shared memory area containing the mmd struct. */
101 int mmd_mutex;
102
103 /* Serializes log output. */
104 static int log_mutex;
105
106 static struct sched sched;
107 static struct signal_task *signal_task;
108
109 /** The process id of the audio file selector process. */
110 pid_t afs_pid = 0;
111
112 /* The the main server process (parent of afs and the command handlers). */
113 static pid_t server_pid;
114
115 /**
116  * Tell whether the executing process is a command handler.
117  *
118  * Cleanup on exit must be performed differently for command handlers.
119  *
120  * \return True if the pid of the executing process is neither the server pid
121  * nor the afs pid.
122  */
123 bool process_is_command_handler(void)
124 {
125         pid_t pid = getpid();
126
127         return pid != afs_pid && pid != server_pid;
128 }
129
130 /** The task responsible for server command handling. */
131 struct server_command_task {
132         unsigned num_listen_fds; /* only one by default */
133         /** TCP socket(s) on which para_server listens for connections. */
134         int *listen_fds;
135         /* File descriptor for the accepted socket. */
136         int child_fd;
137         /** Copied from para_server's main function. */
138         int argc;
139         /** Argument vector passed to para_server's main function. */
140         char **argv;
141         /** The command task structure for scheduling. */
142         struct task *task;
143 };
144
145 /**
146  * Return the list of tasks for the server process.
147  *
148  * This is called from \a com_tasks(). The helper is necessary since command
149  * handlers can not access the scheduler structure directly.
150  *
151  * \return A dynamically allocated string that must be freed by the caller.
152  */
153 char *server_get_tasks(void)
154 {
155         return get_task_list(&sched);
156 }
157
158 static void pre_log_hook(void)
159 {
160         mutex_lock(log_mutex);
161 }
162
163 static void post_log_hook(void)
164 {
165         mutex_unlock(log_mutex);
166 }
167
168 /* Setup shared memory area and init mutexes */
169 static void init_ipc_or_die(void)
170 {
171         void *shm;
172         int shmid, ret = shm_new(sizeof(struct misc_meta_data));
173
174         if (ret < 0)
175                 goto err_out;
176         shmid = ret;
177         ret = shm_attach(shmid, ATTACH_RW, &shm);
178         shm_destroy(shmid);
179         if (ret < 0)
180                 goto err_out;
181         mmd = shm;
182
183         ret = mutex_new();
184         if (ret < 0)
185                 goto err_out;
186         mmd_mutex = ret;
187         ret = mutex_new();
188         if (ret < 0)
189                 goto destroy_mmd_mutex;
190         log_mutex = ret;
191
192         mmd->num_played = 0;
193         mmd->num_commands = 0;
194         mmd->events = 0;
195         mmd->num_connects = 0;
196         mmd->active_connections = 0;
197         mmd->vss_status_flags = VSS_NEXT;
198         mmd->new_vss_status_flags = VSS_NEXT;
199         return;
200 destroy_mmd_mutex:
201         mutex_destroy(mmd_mutex);
202 err_out:
203         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
204         exit(EXIT_FAILURE);
205 }
206
207 /**
208  * (Re-)read the server configuration files.
209  *
210  * \param reload Whether config file overrides command line.
211  *
212  * This function also re-opens the logfile and the user list. On SIGHUP it is
213  * called from both server and afs context.
214  */
215 void parse_config_or_die(bool reload)
216 {
217         int ret;
218         char *cf = NULL, *errctx = NULL, *user_list_file = NULL;
219         void *map;
220         size_t sz;
221         int cf_argc;
222         char **cf_argv;
223         struct lls_parse_result *cf_lpr, *merged_lpr;
224         char *home = para_homedir();
225
226         if (OPT_GIVEN(CONFIG_FILE))
227                 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
228         else
229                 cf = make_message("%s/.paraslash/server.conf", home);
230         if (!mmd || getpid() != afs_pid) {
231                 if (OPT_GIVEN(USER_LIST))
232                         user_list_file = para_strdup(OPT_STRING_VAL(USER_LIST));
233                 else
234                         user_list_file = make_message("%s/.paraslash/server.users", home);
235         }
236         free(home);
237         ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
238         if (ret < 0) {
239                 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
240                         goto free_cf;
241                 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
242                         goto free_cf;
243                 server_lpr = cmdline_lpr;
244                 goto success;
245         }
246         ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
247         para_munmap(map, sz);
248         if (ret < 0)
249                 goto free_cf;
250         cf_argc = ret;
251         ret = lls(lls_parse(cf_argc, cf_argv, CMD_PTR, &cf_lpr, &errctx));
252         lls_free_argv(cf_argv);
253         if (ret < 0)
254                 goto free_cf;
255         if (reload) /* config file overrides command line */
256                 ret = lls(lls_merge(cf_lpr, cmdline_lpr, CMD_PTR, &merged_lpr,
257                         &errctx));
258         else /* command line options override config file options */
259                 ret = lls(lls_merge(cmdline_lpr, cf_lpr, CMD_PTR, &merged_lpr,
260                         &errctx));
261         lls_free_parse_result(cf_lpr, CMD_PTR);
262         if (ret < 0)
263                 goto free_cf;
264         if (server_lpr != cmdline_lpr)
265                 lls_free_parse_result(server_lpr, CMD_PTR);
266         server_lpr = merged_lpr;
267 success:
268         daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
269         if (OPT_GIVEN(LOGFILE)) {
270                 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
271                 daemon_open_log_or_die();
272         }
273         if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
274                         COLOR_NO, OPT_GIVEN(LOGFILE))) {
275                 int i;
276                 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
277                         daemon_set_log_color_or_die(lls_string_val(i,
278                                 OPT_RESULT(LOG_COLOR)));
279         }
280         daemon_set_flag(DF_LOG_PID);
281         daemon_set_flag(DF_LOG_LL);
282         daemon_set_flag(DF_LOG_TIME);
283         if (OPT_GIVEN(LOG_TIMING))
284                 daemon_set_flag(DF_LOG_TIMING);
285         daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
286         if (user_list_file)
287                 user_list_init(user_list_file);
288         ret = 1;
289 free_cf:
290         free(cf);
291         free(user_list_file);
292         if (ret < 0) {
293                 if (errctx)
294                         PARA_ERROR_LOG("%s\n", errctx);
295                 free(errctx);
296                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
297                 exit(EXIT_FAILURE);
298         }
299 }
300
301 /*
302  * called when server gets SIGHUP or when client invokes hup command.
303  */
304 static void handle_sighup(void)
305 {
306
307         PARA_NOTICE_LOG("SIGHUP\n");
308         parse_config_or_die(true);
309         if (afs_pid != 0)
310                 kill(afs_pid, SIGHUP);
311 }
312
313 static int signal_post_select(struct sched *s, __a_unused void *context)
314 {
315         int ret, signum;
316
317         ret = task_get_notification(signal_task->task);
318         if (ret < 0)
319                 return ret;
320         signum = para_next_signal(&s->rfds);
321         switch (signum) {
322         case 0:
323                 return 0;
324         case SIGHUP:
325                 handle_sighup();
326                 break;
327         case SIGCHLD:
328                 for (;;) {
329                         pid_t pid;
330                         ret = para_reap_child(&pid);
331                         if (ret <= 0)
332                                 break;
333                         if (pid != afs_pid)
334                                 continue;
335                         PARA_EMERG_LOG("fatal: afs died\n");
336                         kill(0, SIGTERM);
337                         goto cleanup;
338                 }
339                 break;
340         /* die on sigint/sigterm. Kill all children too. */
341         case SIGINT:
342         case SIGTERM:
343                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
344                 kill(0, SIGTERM);
345                 /*
346                  * We must wait for all of our children to die. For the afs
347                  * process or a command handler might want to use the
348                  * shared memory area and the mmd mutex.  If we destroy this
349                  * mutex too early and afs tries to lock the shared memory
350                  * area, the call to mutex_lock() will fail and terminate the
351                  * afs process. This leads to dirty osl tables.
352                  */
353                 PARA_INFO_LOG("waiting for child processes to die\n");
354                 mutex_unlock(mmd_mutex);
355                 while (wait(NULL) != -1 || errno != ECHILD)
356                         ; /* still at least one child alive */
357                 mutex_lock(mmd_mutex);
358 cleanup:
359                 free(mmd->afd.afhi.chunk_table);
360                 task_notify_all(s, E_DEADLY_SIGNAL);
361                 return -E_DEADLY_SIGNAL;
362         }
363         return 0;
364 }
365
366 static void init_signal_task(void)
367 {
368         signal_task = signal_init_or_die();
369         para_install_sighandler(SIGINT);
370         para_install_sighandler(SIGTERM);
371         para_install_sighandler(SIGHUP);
372         para_install_sighandler(SIGCHLD);
373         para_sigaction(SIGPIPE, SIG_IGN);
374         add_close_on_fork_list(signal_task->fd);
375         signal_task->task = task_register(&(struct task_info) {
376                 .name = "signal",
377                 .pre_select = signal_pre_select,
378                 .post_select = signal_post_select,
379                 .context = signal_task,
380
381         }, &sched);
382 }
383
384 static void command_pre_select(struct sched *s, void *context)
385 {
386         unsigned n;
387         struct server_command_task *sct = context;
388
389         for (n = 0; n < sct->num_listen_fds; n++)
390                 para_fd_set(sct->listen_fds[n], &s->rfds, &s->max_fileno);
391 }
392
393 static int command_task_accept(unsigned listen_idx, struct sched *s,
394                 struct server_command_task *sct)
395 {
396         int new_fd, ret, i;
397         char *peer_name;
398         pid_t child_pid;
399         uint32_t *chunk_table;
400
401         ret = para_accept(sct->listen_fds[listen_idx], &s->rfds, NULL, 0, &new_fd);
402         if (ret <= 0)
403                 goto out;
404         mmd->num_connects++;
405         mmd->active_connections++;
406         /*
407          * The chunk table is a pointer located in the mmd struct that points
408          * to dynamically allocated memory, i.e. it must be freed by the parent
409          * and the child. However, as the mmd struct is in a shared memory
410          * area, there's no guarantee that after the fork this pointer is still
411          * valid in child context. As it is not used in the child anyway, we
412          * save it to a local variable before the fork and free the memory via
413          * that copy in the child directly after the fork.
414          */
415         chunk_table = mmd->afd.afhi.chunk_table;
416         child_pid = fork();
417         if (child_pid < 0) {
418                 ret = -ERRNO_TO_PARA_ERROR(errno);
419                 goto out;
420         }
421         if (child_pid) {
422                 /* avoid problems with non-fork-safe PRNGs */
423                 unsigned char buf[16];
424                 get_random_bytes_or_die(buf, sizeof(buf));
425                 close(new_fd);
426                 /* parent keeps accepting connections */
427                 return 0;
428         }
429         peer_name = remote_name(new_fd);
430         PARA_INFO_LOG("accepted connection from %s\n", peer_name);
431         /* mmd might already have changed at this point */
432         free(chunk_table);
433         sct->child_fd = new_fd;
434         /*
435          * put info on who we are serving into argv[0] to make
436          * client ip visible in top/ps
437          */
438         for (i = sct->argc - 1; i >= 0; i--)
439                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
440         i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
441         sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
442         /* ask other tasks to terminate */
443         task_notify_all(s, E_CHILD_CONTEXT);
444         /*
445          * After we return, the scheduler calls server_select() with a minimal
446          * timeout value, because the remaining tasks have a notification
447          * pending. Next it calls the ->post_select method of these tasks,
448          * which will return negative in view of the notification. This causes
449          * schedule() to return as there are no more runnable tasks.
450          *
451          * Note that semaphores are not inherited across a fork(), so we don't
452          * hold the lock at this point. Since server_select() drops the lock
453          * prior to calling para_select(), we need to acquire it here.
454          */
455         mutex_lock(mmd_mutex);
456         return -E_CHILD_CONTEXT;
457 out:
458         if (ret < 0)
459                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
460         return 0;
461 }
462
463 static int command_post_select(struct sched *s, void *context)
464 {
465         struct server_command_task *sct = context;
466         unsigned n;
467         int ret;
468
469         ret = task_get_notification(sct->task);
470         if (ret < 0)
471                 return ret;
472         for (n = 0; n < sct->num_listen_fds; n++) {
473                 ret = command_task_accept(n, s, sct);
474                 if (ret < 0) {
475                         free(sct->listen_fds);
476                         return ret;
477                 }
478         }
479         return 0;
480 }
481
482 static void init_server_command_task(struct server_command_task *sct,
483                 int argc, char **argv)
484 {
485         int ret;
486         unsigned n;
487         uint32_t port = OPT_UINT32_VAL(PORT);
488
489         PARA_NOTICE_LOG("initializing tcp command socket\n");
490         sct->child_fd = -1;
491         sct->argc = argc;
492         sct->argv = argv;
493         if (!OPT_GIVEN(LISTEN_ADDRESS)) {
494                 sct->num_listen_fds = 1;
495                 sct->listen_fds = para_malloc(sizeof(int));
496                 ret = para_listen_simple(IPPROTO_TCP, port);
497                 if (ret < 0)
498                         goto err;
499                 sct->listen_fds[0] = ret;
500         } else {
501                 sct->num_listen_fds = OPT_GIVEN(LISTEN_ADDRESS);
502                 sct->listen_fds = para_malloc(sct->num_listen_fds * sizeof(int));
503                 for (n = 0; n < OPT_GIVEN(LISTEN_ADDRESS); n++) {
504                         const char *arg;
505                         arg = lls_string_val(n, OPT_RESULT(LISTEN_ADDRESS));
506                         ret = para_listen(IPPROTO_TCP, arg, port);
507                         if (ret < 0)
508                                 goto err;
509                         sct->listen_fds[n] = ret;
510                 }
511         }
512         for (n = 0; n < sct->num_listen_fds; n++) {
513                 ret = mark_fd_nonblocking(sct->listen_fds[n]);
514                 if (ret < 0)
515                         goto err;
516                 /* child doesn't need the listener */
517                 add_close_on_fork_list(sct->listen_fds[n]);
518         }
519
520         sct->task = task_register(&(struct task_info) {
521                 .name = "server command",
522                 .pre_select = command_pre_select,
523                 .post_select = command_post_select,
524                 .context = sct,
525         }, &sched);
526         return;
527 err:
528         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
529         exit(EXIT_FAILURE);
530 }
531
532 static int init_afs(int argc, char **argv)
533 {
534         int ret, afs_server_socket[2];
535         char c;
536
537         ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
538         if (ret < 0)
539                 exit(EXIT_FAILURE);
540         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
541                 sizeof(afs_socket_cookie));
542         afs_pid = fork();
543         if (afs_pid < 0)
544                 exit(EXIT_FAILURE);
545         if (afs_pid == 0) { /* child (afs) */
546                 int i;
547
548                 afs_pid = getpid();
549                 crypt_shutdown();
550                 user_list_deplete();
551                 for (i = argc - 1; i >= 0; i--)
552                         memset(argv[i], 0, strlen(argv[i]));
553                 i = argc - lls_num_inputs(cmdline_lpr) - 1;
554                 sprintf(argv[i], "para_server (afs)");
555                 close(afs_server_socket[0]);
556                 afs_init(afs_server_socket[1]);
557         }
558         close(afs_server_socket[1]);
559         if (read(afs_server_socket[0], &c, 1) <= 0) {
560                 PARA_EMERG_LOG("early afs exit\n");
561                 exit(EXIT_FAILURE);
562         }
563         ret = mark_fd_nonblocking(afs_server_socket[0]);
564         if (ret < 0)
565                 exit(EXIT_FAILURE);
566         add_close_on_fork_list(afs_server_socket[0]);
567         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
568                 afs_server_socket[0], (unsigned) afs_socket_cookie);
569         return afs_server_socket[0];
570 }
571
572 static void handle_help_flags(void)
573 {
574         char *help;
575         bool d = OPT_GIVEN(DETAILED_HELP);
576
577         if (d)
578                 help = lls_long_help(CMD_PTR);
579         else if (OPT_GIVEN(HELP))
580                 help = lls_short_help(CMD_PTR);
581         else
582                 return;
583         printf("%s\n", help);
584         free(help);
585         exit(EXIT_SUCCESS);
586 }
587
588 static void server_init(int argc, char **argv, struct server_command_task *sct)
589 {
590         int ret, afs_socket, daemon_pipe = -1;
591         char *errctx;
592
593         valid_fd_012();
594         /* parse command line options */
595         ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
596         if (ret < 0)
597                 goto fail;
598         server_lpr = cmdline_lpr;
599         daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
600         daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
601                 OPT_STRING_VAL(GROUP));
602         version_handle_flag("server", OPT_GIVEN(VERSION));
603         handle_help_flags();
604         parse_config_or_die(false);
605         /* become daemon */
606         if (OPT_GIVEN(DAEMON))
607                 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
608         server_pid = getpid();
609         crypt_init();
610         daemon_log_welcome("server");
611         init_ipc_or_die(); /* init mmd struct, mmd and log mutex */
612         daemon_set_start_time();
613         daemon_set_hooks(pre_log_hook, post_log_hook);
614         PARA_NOTICE_LOG("initializing audio format handlers\n");
615         afh_init();
616
617         /*
618          * Although afs uses its own signal handling we must ignore SIGUSR1
619          * _before_ the afs child process gets born by init_afs() below.  It's
620          * racy to do this in the child because the parent might send SIGUSR1
621          * before the child gets a chance to ignore this signal.
622          *
623          * We also have to block SIGCHLD before the afs process is created
624          * because otherwise para_server does not notice if afs dies before the
625          * SIGCHLD handler has been installed for the parent process by
626          * init_signal_task() below.
627          */
628         para_sigaction(SIGUSR1, SIG_IGN);
629         para_block_signal(SIGCHLD);
630         PARA_NOTICE_LOG("initializing the audio file selector\n");
631         afs_socket = init_afs(argc, argv);
632         init_signal_task();
633         para_unblock_signal(SIGCHLD);
634         PARA_NOTICE_LOG("initializing virtual streaming system\n");
635         vss_init(afs_socket, &sched);
636         init_server_command_task(sct, argc, argv);
637         if (daemon_pipe >= 0) {
638                 if (write(daemon_pipe, "\0", 1) < 0) {
639                         PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
640                         exit(EXIT_FAILURE);
641                 }
642                 close(daemon_pipe);
643         }
644         PARA_NOTICE_LOG("server init complete\n");
645         return;
646 fail:
647         assert(ret < 0);
648         if (errctx)
649                 PARA_ERROR_LOG("%s\n", errctx);
650         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
651         exit(EXIT_FAILURE);
652 }
653
654 static void status_refresh(void)
655 {
656         static int prev_uptime = -1, prev_events = -1;
657         int uptime = daemon_get_uptime(now);
658
659         if (prev_events != mmd->events)
660                 goto out;
661         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
662                 goto out_inc_events;
663         if (uptime / 60 != prev_uptime / 60)
664                 goto out_inc_events;
665         return;
666 out_inc_events:
667         mmd->events++;
668 out:
669         prev_uptime = uptime;
670         prev_events = mmd->events;
671         mmd->vss_status_flags = mmd->new_vss_status_flags;
672         PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
673         killpg(0, SIGUSR1);
674 }
675
676 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
677                 struct timeval *timeout_tv)
678 {
679         int ret;
680
681         status_refresh();
682         mutex_unlock(mmd_mutex);
683         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
684         mutex_lock(mmd_mutex);
685         return ret;
686 }
687
688 /**
689  * Deallocate all lopsub parse results.
690  *
691  * The server allocates a parse result for command line options and optionally
692  * a second parse result for the effective configuration, defined by merging
693  * the command line options with the options stored in the configuration file.
694  * This function frees both structures.
695  */
696 void free_lpr(void)
697 {
698         lls_free_parse_result(server_lpr, CMD_PTR);
699         if (server_lpr != cmdline_lpr)
700                 lls_free_parse_result(cmdline_lpr, CMD_PTR);
701 }
702
703 /**
704  * The main function of para_server.
705  *
706  * \param argc Usual argument count.
707  * \param argv Usual argument vector.
708  *
709  * \return EXIT_SUCCESS or EXIT_FAILURE.
710  */
711 int main(int argc, char *argv[])
712 {
713         int ret;
714         struct server_command_task server_command_task_struct,
715                 *sct = &server_command_task_struct;
716
717         sched.default_timeout.tv_sec = 1;
718         sched.select_function = server_select;
719
720         server_init(argc, argv, sct);
721         mutex_lock(mmd_mutex);
722         ret = schedule(&sched);
723         /*
724          * We hold the mmd lock: it was re-acquired in server_select()
725          * after the select call.
726          */
727         mutex_unlock(mmd_mutex);
728         sched_shutdown(&sched);
729         crypt_shutdown();
730         signal_shutdown(signal_task);
731         if (!process_is_command_handler()) { /* parent (server) */
732                 mutex_destroy(mmd_mutex);
733                 daemon_set_hooks(NULL, NULL); /* only one process remaining */
734                 mutex_destroy(log_mutex);
735                 deplete_close_on_fork_list();
736                 if (ret < 0)
737                         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
738         } else {
739                 alarm(ALARM_TIMEOUT);
740                 close_listed_fds();
741                 ret = handle_connect(sct->child_fd);
742         }
743         vss_shutdown();
744         shm_detach(mmd);
745         user_list_deplete();
746         free_lpr();
747         exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
748 }