]> git.tuebingen.mpg.de Git - paraslash.git/blob - afs.c
net.c: Fix a typo and improve send_bin_buffer() docu.
[paraslash.git] / afs.c
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file afs.c Paraslash's audio file selector. */
8
9 #include "server.cmdline.h"
10 #include "para.h"
11 #include "afh.h"
12 #include "server.h"
13 #include "error.h"
14 #include <dirent.h> /* readdir() */
15 #include <sys/mman.h>
16 #include <sys/time.h>
17 #include "net.h"
18 #include "afs.h"
19 #include "ipc.h"
20 #include "string.h"
21 #include "list.h"
22 #include "sched.h"
23 #include "signal.h"
24 #include "fd.h"
25
26 /** The osl tables used by afs. \sa blob.c. */
27 enum afs_table_num {
28         /** Contains audio file information. See aft.c. */
29         TBLNUM_AUDIO_FILES,
30         /** The table for the paraslash attributes. See attribute.c. */
31         TBLNUM_ATTRIBUTES,
32         /**
33          * Paraslash's scoring system is based on Gaussian normal
34          * distributions, and the relevant data is stored in the rbtrees of an
35          * osl table containing only volatile columns.  See score.c for
36          * details.
37          */
38         TBLNUM_SCORES,
39         /**
40          * A standard blob table containing the mood definitions. For details
41          * see mood.c.
42          */
43         TBLNUM_MOODS,
44         /** A blob table containing lyrics on a per-song basis. */
45         TBLNUM_LYRICS,
46         /** Another blob table for images (for example album cover art). */
47         TBLNUM_IMAGES,
48         /** Yet another blob table for storing standard playlists. */
49         TBLNUM_PLAYLIST,
50         /** How many tables are in use? */
51         NUM_AFS_TABLES
52 };
53
54 static struct table_info afs_tables[NUM_AFS_TABLES];
55
56 struct command_task {
57         /** The file descriptor for the local socket. */
58         int fd;
59         /**
60          * Value sent by the command handlers to identify themselves as
61          * children of the running para_server.
62          */
63         uint32_t cookie;
64         /** The associated task structure. */
65         struct task task;
66 };
67
68 /**
69  * A random number used to "authenticate" the connection.
70  *
71  * para_server picks this number by random before forking the afs process.  The
72  * command handlers write this number together with the id of the shared memory
73  * area containing the query. This way, a malicious local user has to know this
74  * number to be able to cause the afs process to crash by sending fake queries.
75  */
76 extern uint32_t afs_socket_cookie;
77
78 /**
79  * Struct to let command handlers execute a callback in afs context.
80  *
81  * Commands that need to change the state of afs can't change the relevant data
82  * structures directly because commands are executed in a child process, i.e.
83  * they get their own virtual address space.
84  *
85  * This structure is used by \p send_callback_request() (executed from handler
86  * context) in order to let the afs process call the specified function. An
87  * instance of that structure is written to a shared memory area together with
88  * the arguments to the callback function. The identifier of the shared memory
89  * area is written to the command socket.
90  *
91  * The afs process accepts connections on the command socket and reads the
92  * shared memory id, attaches the corresponing area, calls the given handler to
93  * perform the desired action and to optionally compute a result.
94  *
95  * The result and a \p callback_result structure is then written to another
96  * shared memory area. The identifier for that area is written to the handler's
97  * command socket, so that the handler process can read the id, attach the
98  * shared memory area and use the result.
99  *
100  * \sa struct callback_result.
101  */
102 struct callback_query {
103         /** The function to be called. */
104         callback_function *handler;
105         /** The number of bytes of the query */
106         size_t query_size;
107 };
108
109 /**
110  * Structure embedded in the result of a callback.
111  *
112  * If the callback produced a result, an instance of that structure is embeeded
113  * into the shared memory area holding the result, mainly to let the command
114  * handler know the size of the result.
115  *
116  * \sa struct callback_query.
117  */
118 struct callback_result {
119         /** The number of bytes of the result. */
120         size_t result_size;
121 };
122
123 /**
124  * Ask the parent process to call a given function.
125  *
126  * \param f The function to be called.
127  * \param query Pointer to arbitrary data for the callback.
128  * \param result Callback result will be stored here.
129  *
130  * This function creates a shared memory area, copies the buffer pointed to by
131  * \a buf to that area and notifies the afs process that \a f should be
132  * called ASAP.
133  *
134  * \return Negative, on errors, the return value of the callback function
135  * otherwise.
136  *
137  * \sa send_option_arg_callback_request(), send_standard_callback_request().
138  */
139 int send_callback_request(callback_function *f, struct osl_object *query,
140                 struct osl_object *result)
141 {
142         struct callback_query *cq;
143         struct callback_result *cr;
144         int ret, fd = -1, query_shmid, result_shmid;
145         void *query_shm, *result_shm;
146         char buf[sizeof(afs_socket_cookie) + sizeof(int)];
147 //      char *tmpsocket_name;
148         struct sockaddr_un unix_addr;
149
150         assert(query->data && query->size);
151         ret = shm_new(query->size + sizeof(*cq));
152         if (ret < 0)
153                 return ret;
154         query_shmid = ret;
155         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
156         if (ret < 0)
157                 goto out;
158         cq = query_shm;
159         cq->handler = f;
160         cq->query_size = query->size;
161
162         memcpy(query_shm + sizeof(*cq), query->data, query->size);
163         ret = shm_detach(query_shm);
164         if (ret < 0)
165                 goto out;
166
167         *(uint32_t *) buf = afs_socket_cookie;
168         *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
169
170         ret = get_stream_socket(PF_UNIX);
171         if (ret < 0)
172                 goto out;
173         fd = ret;
174         ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
175         if (ret < 0)
176                 goto out;
177         ret = PARA_CONNECT(fd, &unix_addr);
178         if (ret < 0)
179                 goto out;
180         ret = send_bin_buffer(fd, buf, sizeof(buf));
181         if (ret < 0)
182                 goto out;
183         ret = recv_bin_buffer(fd, buf, sizeof(buf));
184         if (ret < 0)
185                 goto out;
186         if (ret != sizeof(int)) {
187                 ret = -E_RECV;
188                 goto out;
189         }
190         ret = *(int *) buf;
191         if (ret <= 0)
192                 goto out;
193         result_shmid = ret;
194         ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
195         if (ret >= 0) {
196                 assert(result);
197                 cr = result_shm;
198                 result->size = cr->result_size;
199                 result->data = para_malloc(result->size);
200                 memcpy(result->data, result_shm + sizeof(*cr), result->size);
201                 ret = shm_detach(result_shm);
202                 if (ret < 0)
203                         PARA_ERROR_LOG("can not detach result\n");
204         } else
205                 PARA_ERROR_LOG("attach result failed: %d\n", ret);
206         if (shm_destroy(result_shmid) < 0)
207                 PARA_ERROR_LOG("destroy result failed\n");
208         ret = 1;
209 out:
210         if (shm_destroy(query_shmid) < 0)
211                 PARA_ERROR_LOG("%s\n", "shm destroy error");
212         if (fd >= 0)
213                 close(fd);
214 //      PARA_DEBUG_LOG("callback_ret: %d\n", ret);
215         return ret;
216 }
217
218 /**
219  * Send a callback request passing an options structure and an argument vector.
220  *
221  * \param options pointer to an arbitrary data structure.
222  * \param argc Argument count.
223  * \param argv Standard argument vector.
224  * \param f The callback function.
225  * \param result The result of the query is stored here.
226  *
227  * Some commands have a couple of options that are parsed in child context for
228  * syntactic correctness and are stored in a special options structure for that
229  * command. This function allows to pass such a structure together with a list
230  * of further arguments (often a list of audio files) to the parent process.
231  *
232  * \sa send_standard_callback_request(), send_callback_request().
233  */
234 int send_option_arg_callback_request(struct osl_object *options,
235                 int argc,  char * const * const argv, callback_function *f,
236                 struct osl_object *result)
237 {
238         char *p;
239         int i, ret;
240         struct osl_object query = {.size = options? options->size : 0};
241
242         for (i = 0; i < argc; i++)
243                 query.size += strlen(argv[i]) + 1;
244         query.data = para_malloc(query.size);
245         p = query.data;
246         if (options) {
247                 memcpy(query.data, options->data, options->size);
248                 p += options->size;
249         }
250         for (i = 0; i < argc; i++) {
251                 strcpy(p, argv[i]); /* OK */
252                 p += strlen(argv[i]) + 1;
253         }
254         ret = send_callback_request(f, &query, result);
255         free(query.data);
256         return ret;
257 }
258
259 /**
260  * Send a callback request with an argument vector only.
261  *
262  * \param argc The same meaning as in send_option_arg_callback_request().
263  * \param argv The same meaning as in send_option_arg_callback_request().
264  * \param f The same meaning as in send_option_arg_callback_request().
265  * \param result The same meaning as in send_option_arg_callback_request().
266  *
267  * This is similar to send_option_arg_callback_request(), but no options buffer
268  * is passed to the parent process.
269  *
270  * \return The return value of the underlying call to
271  * send_option_arg_callback_request().
272  */
273 int send_standard_callback_request(int argc,  char * const * const argv,
274                 callback_function *f, struct osl_object *result)
275 {
276         return send_option_arg_callback_request(NULL, argc, argv, f, result);
277 }
278
279 /**
280  * Compare two osl objects of string type.
281  *
282  * \param obj1 Pointer to the first object.
283  * \param obj2 Pointer to the second object.
284  *
285  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
286  * are taken into account.
287  *
288  * \return It returns an integer less than, equal to, or greater than zero if
289  * \a obj1 is found, respectively, to be less than, to match, or be greater than
290  * obj2.
291  *
292  * \sa strcmp(3), strncmp(3), osl_compare_func.
293  */
294 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
295 {
296         const char *str1 = (const char *)obj1->data;
297         const char *str2 = (const char *)obj2->data;
298         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
299 }
300
301 /**
302  * A wrapper for strtol(3).
303  *
304  * \param str The string to be converted to a long integer.
305  * \param result The converted value is stored here.
306  *
307  * \return Positive on success, -E_ATOL on errors.
308  *
309  * \sa strtol(3), atoi(3).
310  */
311 int para_atol(const char *str, long *result)
312 {
313         char *endptr;
314         long val;
315         int ret, base = 10;
316
317         errno = 0; /* To distinguish success/failure after call */
318         val = strtol(str, &endptr, base);
319         ret = -E_ATOL;
320         if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
321                 goto out; /* overflow */
322         if (errno != 0 && val == 0)
323                 goto out; /* other error */
324         if (endptr == str)
325                 goto out; /* No digits were found */
326         if (*endptr != '\0')
327                 goto out; /* Further characters after number */
328         *result = val;
329         ret = 1;
330 out:
331         return ret;
332 }
333
334
335 /*
336  * write input from fd to dynamically allocated buffer,
337  * but maximal max_size byte.
338  */
339 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
340 {
341         const size_t chunk_size = 1024;
342         size_t size = 2048, received = 0;
343         int ret;
344         char *buf = para_malloc(size);
345
346         for (;;) {
347                 ret = recv_bin_buffer(fd, buf + received, chunk_size);
348                 if (ret <= 0)
349                         break;
350                 received += ret;
351                 if (received + chunk_size >= size) {
352                         size *= 2;
353                         ret = -E_INPUT_TOO_LARGE;
354                         if (size > max_size)
355                                 break;
356                         buf = para_realloc(buf, size);
357                 }
358         }
359         obj->data = buf;
360         obj->size = received;
361         if (ret < 0)
362                 free(buf);
363         return ret;
364 }
365
366 /**
367  * Read from stdin, and send the result to the parent process.
368  *
369  * \param arg_obj Pointer to the arguments to \a f.
370  * \param f The callback function.
371  * \param max_len Don't read more than that many bytes from stdin.
372  * \param result The result of the query is stored here.
373  *
374  * This function is used by commands that wish to let para_server store
375  * arbitrary data specified by the user (for instance the add_blob family of
376  * commands). First, at most \a max_len bytes are read from stdin, the result
377  * is concatenated with the buffer given by \a arg_obj, and the combined buffer
378  * is made available to the parent process via shared memory.
379  *
380  * \return Negative on errors, the return value of the underlying call to
381  * send_callback_request() otherwise.
382  */
383 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
384                 unsigned max_len, struct osl_object *result)
385 {
386         struct osl_object query, stdin_obj;
387         int ret;
388
389         ret = send_buffer(fd, AWAITING_DATA_MSG);
390         if (ret < 0)
391                 return ret;
392         ret = fd2buf(fd, max_len, &stdin_obj);
393         if (ret < 0)
394                 return ret;
395         query.size = arg_obj->size + stdin_obj.size;
396         query.data = para_malloc(query.size);
397         memcpy(query.data, arg_obj->data, arg_obj->size);
398         memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
399         free(stdin_obj.data);
400         ret = send_callback_request(f, &query, result);
401         free(query.data);
402         return ret;
403 }
404
405 /**
406  * Open the audio file with highest score.
407  *
408  * \param afd Audio file data is returned here.
409  *
410  * This stores all information for streaming the "best" audio file
411  * in the \a afd structure.
412  *
413  * \return Positive on success, negative on errors.
414  *
415  * \sa close_audio_file(), open_and_update_audio_file().
416  */
417 int open_next_audio_file(struct audio_file_data *afd)
418 {
419         struct osl_row *aft_row;
420         int ret;
421         for (;;) {
422                 ret = score_get_best(&aft_row, &afd->score);
423                 if (ret < 0)
424                         return ret;
425                 ret = open_and_update_audio_file(aft_row, afd);
426                 if (ret >= 0)
427                         return ret;
428         }
429 }
430
431 /**
432  * Free all resources which were allocated by open_next_audio_file().
433  *
434  * \param afd The structure previously filled in by open_next_audio_file().
435  *
436  * \return The return value of the underlying call to para_munmap().
437  *
438  * \sa open_next_audio_file().
439  */
440 int close_audio_file(struct audio_file_data *afd)
441 {
442         free(afd->afhi.chunk_table);
443         return para_munmap(afd->map.data, afd->map.size);
444 }
445
446 #if 0
447 static void play_loop(enum play_mode current_play_mode)
448 {
449         int i, ret;
450         struct audio_file_data afd;
451
452         afd.current_play_mode = current_play_mode;
453         for (i = 0; i < 0; i++) {
454                 ret = open_next_audio_file(&afd);
455                 if (ret < 0) {
456                         PARA_ERROR_LOG("failed to open next audio file: %d\n", ret);
457                         return;
458                 }
459                 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd.path, afd.score);
460                 sleep(1);
461                 close_audio_file(&afd);
462         }
463 }
464 #endif
465
466
467 static enum play_mode init_admissible_files(void)
468 {
469         int ret;
470         char *given_mood, *given_playlist;
471
472         given_mood = "mood_that_was_given_at_the_command_line";
473         given_playlist = "given_playlist";
474
475         if (given_mood) {
476                 ret = mood_open(given_mood);
477                 if (ret >= 0) {
478                         if (given_playlist)
479                                 PARA_WARNING_LOG("ignoring playlist %s\n",
480                                         given_playlist);
481                         return PLAY_MODE_MOOD;
482                 }
483         }
484         if (given_playlist) {
485                 ret = playlist_open(given_playlist);
486                 if (ret >= 0)
487                         return PLAY_MODE_PLAYLIST;
488         }
489         ret = mood_open(NULL); /* open first available mood */
490         if (ret >= 0)
491                 return PLAY_MODE_MOOD;
492         mood_open(""); /* open dummy mood, always successful */
493         return PLAY_MODE_MOOD;
494 }
495
496 static int setup_command_socket_or_die(void)
497 {
498         int ret;
499         char *socket_name = conf.afs_socket_arg;
500         struct sockaddr_un unix_addr;
501
502         unlink(socket_name);
503         ret = create_local_socket(socket_name, &unix_addr,
504                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
505         if (ret < 0) {
506                 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
507                 exit(EXIT_FAILURE);
508         }
509         if (listen(ret , 5) < 0) {
510                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
511                 exit(EXIT_FAILURE);
512         }
513         PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
514                 ret);
515         return ret;
516 }
517
518 static int server_socket;
519 static struct command_task command_task_struct;
520 static struct signal_task signal_task_struct;
521
522 static void unregister_tasks(void)
523 {
524         unregister_task(&command_task_struct.task);
525         unregister_task(&signal_task_struct.task);
526 }
527
528 static void close_afs_tables(enum osl_close_flags flags)
529 {
530         PARA_NOTICE_LOG("closing afs_tables\n");
531         score_shutdown(flags);
532         attribute_shutdown(flags);
533         mood_close();
534         playlist_close();
535         moods_shutdown(flags);
536         playlists_shutdown(flags);
537         lyrics_shutdown(flags);
538         images_shutdown(flags);
539         aft_shutdown(flags);
540 }
541
542 static void signal_pre_select(struct sched *s, struct task *t)
543 {
544         struct signal_task *st = t->private_data;
545         t->ret = 1;
546         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
547 }
548
549 static void signal_post_select(struct sched *s, struct task *t)
550 {
551         struct signal_task *st = t->private_data;
552         t->ret = 1;
553         if (!FD_ISSET(st->fd, &s->rfds))
554                 return;
555         st->signum = para_next_signal();
556         PARA_NOTICE_LOG("caught signal %d\n", st->signum);
557         t->ret = 1;
558         if (st->signum == SIGUSR1)
559                 return; /* ignore SIGUSR1 */
560         t->ret = -E_SIGNAL_CAUGHT;
561         unregister_tasks();
562 }
563
564 static void register_signal_task(void)
565 {
566         struct signal_task *st = &signal_task_struct;
567         st->fd = para_signal_init();
568         PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
569         para_install_sighandler(SIGINT);
570         para_install_sighandler(SIGTERM);
571         para_install_sighandler(SIGPIPE);
572
573         st->task.pre_select = signal_pre_select;
574         st->task.post_select = signal_post_select;
575         st->task.private_data = st;
576         sprintf(st->task.status, "signal task");
577         register_task(&st->task);
578 }
579
580 static void command_pre_select(struct sched *s, struct task *t)
581 {
582         struct command_task *ct = t->private_data;
583         t->ret = 1;
584         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
585 }
586
587 /*
588  * On errors, negative value is written to fd.
589  * On success: If query produced a result, the result_shmid is written to fd.
590  * Otherwise, zero is written.
591  */
592 static int call_callback(int fd, int query_shmid)
593 {
594         void *query_shm, *result_shm;
595         struct callback_query *cq;
596         struct callback_result *cr;
597         struct osl_object query, result = {.data = NULL};
598         int result_shmid = -1, ret, ret2;
599
600         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
601         if (ret < 0)
602                 goto out;
603         cq = query_shm;
604         query.data = (char *)query_shm + sizeof(*cq);
605         query.size = cq->query_size;
606         ret = cq->handler(&query, &result);
607         ret2 = shm_detach(query_shm);
608         if (ret2 < 0 && ret >= 0)
609                 ret = ret2;
610         if (ret < 0)
611                 goto out;
612         ret = 0;
613         if (!result.data || !result.size)
614                 goto out;
615         ret = shm_new(result.size + sizeof(struct callback_result));
616         if (ret < 0)
617                 goto out;
618         result_shmid = ret;
619         ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
620         if (ret < 0)
621                 goto out;
622         cr = result_shm;
623         cr->result_size = result.size;
624         memcpy(result_shm + sizeof(*cr), result.data, result.size);
625         ret = shm_detach(result_shm);
626         if (ret < 0)
627                 goto out;
628         ret = result_shmid;
629 out:
630         free(result.data);
631         ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
632         if (ret < 0 || ret2 < 0) {
633                 if (result_shmid >= 0)
634                         if (shm_destroy(result_shmid) < 0)
635                                 PARA_ERROR_LOG("destroy result failed\n");
636                 if (ret >= 0)
637                         ret = ret2;
638         }
639         return ret;
640 }
641
642 static void command_post_select(struct sched *s, struct task *t)
643 {
644         struct command_task *ct = t->private_data;
645         struct sockaddr_un unix_addr;
646         char buf[sizeof(uint32_t) + sizeof(int)];
647         uint32_t cookie;
648         int query_shmid, fd;
649
650         t->ret = 1;
651         if (!FD_ISSET(ct->fd, &s->rfds))
652                 return;
653         t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
654         if (t->ret < 0)
655                 return;
656         /*
657          * The following errors may be caused by a malicious local user. So do
658          * not return an error in this case as this would terminate  para_afs
659          * and para_server.
660          */
661         fd = t->ret;
662         /* FIXME: This is easily dosable (peer doesn't send data) */
663         t->ret = recv_bin_buffer(fd, buf, sizeof(buf));
664         if (t->ret < 0) {
665                 PARA_NOTICE_LOG("%s (%d)\n", PARA_STRERROR(-t->ret), t->ret);
666                 goto out;
667         }
668         if (t->ret != sizeof(buf)) {
669                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
670                         t->ret, (long unsigned) sizeof(buf));
671                 goto out;
672         }
673         cookie = *(uint32_t *)buf;
674         if (cookie != ct->cookie) {
675                 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
676                         (unsigned)cookie, (unsigned)ct->cookie);
677                 goto out;
678         }
679         query_shmid = *(int *)(buf + sizeof(cookie));
680         if (query_shmid < 0) {
681                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
682                         query_shmid);
683                 goto out;
684         }
685         /* Ignore return value: Errors might be ok here. */
686         call_callback(fd, query_shmid);
687 out:
688         t->ret = 1;
689         close(fd);
690 }
691
692 static void register_command_task(uint32_t cookie)
693 {
694         struct command_task *ct = &command_task_struct;
695         ct->fd = setup_command_socket_or_die();
696         ct->cookie = cookie;
697
698         ct->task.pre_select = command_pre_select;
699         ct->task.post_select = command_post_select;
700         ct->task.private_data = ct;
701         sprintf(ct->task.status, "command task");
702         register_task(&ct->task);
703 }
704
705 void register_tasks(uint32_t cookie)
706 {
707         register_signal_task();
708         register_command_task(cookie);
709 }
710
711 static char *database_dir;
712
713 static int make_database_dir(void)
714 {
715         int ret;
716
717         if (!database_dir) {
718                 if (conf.afs_database_dir_given)
719                         database_dir = para_strdup(conf.afs_database_dir_arg);
720                 else {
721                         char *home = para_homedir();
722                         database_dir = make_message(
723                                 "%s/.paraslash/afs_database", home);
724                         free(home);
725                 }
726         }
727         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
728         ret = para_mkdir(database_dir, 0777);
729         if (ret >= 0 || ret == -E_EXIST)
730                 return 1;
731         free(database_dir);
732         database_dir = NULL;
733         return ret;
734 }
735
736 static int open_afs_tables(void)
737 {
738         int ret = make_database_dir();
739
740         if (ret < 0)
741                 return ret;
742         ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES], database_dir);
743         if (ret < 0)
744                 return ret;
745         ret = moods_init(&afs_tables[TBLNUM_MOODS], database_dir);
746         if (ret < 0)
747                 goto moods_init_error;
748         ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST], database_dir);
749         if (ret < 0)
750                 goto playlists_init_error;
751         ret = lyrics_init(&afs_tables[TBLNUM_LYRICS], database_dir);
752         if (ret < 0)
753                 goto lyrics_init_error;
754         ret = images_init(&afs_tables[TBLNUM_IMAGES], database_dir);
755         if (ret < 0)
756                 goto images_init_error;
757         ret = score_init(&afs_tables[TBLNUM_SCORES], database_dir);
758         if (ret < 0)
759                 goto score_init_error;
760         ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES], database_dir);
761         if (ret < 0)
762                 goto aft_init_error;
763         return 1;
764
765 aft_init_error:
766         score_shutdown(OSL_MARK_CLEAN);
767 score_init_error:
768         images_shutdown(OSL_MARK_CLEAN);
769 images_init_error:
770         lyrics_shutdown(OSL_MARK_CLEAN);
771 lyrics_init_error:
772         playlists_shutdown(OSL_MARK_CLEAN);
773 playlists_init_error:
774         moods_shutdown(OSL_MARK_CLEAN);
775 moods_init_error:
776         attribute_shutdown(OSL_MARK_CLEAN);
777         return ret;
778 }
779
780 __noreturn int afs_init(uint32_t cookie, int socket_fd)
781 {
782         enum play_mode current_play_mode;
783         struct sched s;
784         int ret = open_afs_tables();
785
786         if (ret < 0) {
787                 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
788                 exit(EXIT_FAILURE);
789         }
790         server_socket = socket_fd;
791         ret = mark_fd_nonblock(server_socket);
792         if (ret < 0)
793                 exit(EXIT_FAILURE);
794         PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
795                 server_socket, (unsigned) cookie);
796         current_play_mode = init_admissible_files();
797         register_tasks(cookie);
798         s.default_timeout.tv_sec = 0;
799         s.default_timeout.tv_usec = 99 * 1000;
800         ret = sched(&s);
801         if (ret < 0)
802                 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
803         close_afs_tables(OSL_MARK_CLEAN);
804         exit(EXIT_FAILURE);
805 }
806
807 static int create_tables_callback(const struct osl_object *query,
808                 __a_unused struct osl_object *result)
809 {
810         uint32_t table_mask = *(uint32_t *)query->data;
811         int i, ret;
812
813         close_afs_tables(OSL_MARK_CLEAN);
814         for (i = 0; i < NUM_AFS_TABLES; i++) {
815                 struct table_info *ti = afs_tables + i;
816
817                 if (ti->flags & TBLFLAG_SKIP_CREATE)
818                         continue;
819                 if (!(table_mask & (1 << i)))
820                         continue;
821                 ret = osl_create_table(ti->desc);
822                 if (ret < 0)
823                         return ret;
824         }
825         ret = open_afs_tables();
826         return ret < 0? ret: 0;
827 }
828
829 int com_init(int fd, int argc, char * const * const argv)
830 {
831         int i, j, ret;
832         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
833         struct osl_object query = {.data = &table_mask,
834                 .size = sizeof(table_mask)};
835
836         if (argc != 1) {
837                 table_mask = 0;
838                 for (i = 1; i < argc; i++) {
839                         for (j = 0; j < NUM_AFS_TABLES; j++) {
840                                 struct table_info *ti = afs_tables + j;
841
842                                 if (ti->flags & TBLFLAG_SKIP_CREATE)
843                                         continue;
844                                 if (strcmp(argv[i], ti->desc->name))
845                                         continue;
846                                 table_mask |= (1 << j);
847                                 break;
848                         }
849                         if (j == NUM_AFS_TABLES)
850                                 return -E_BAD_TABLE_NAME;
851                 }
852         }
853         ret = send_callback_request(create_tables_callback, &query, NULL);
854         if (ret < 0)
855                 return ret;
856         return send_va_buffer(fd, "successfully created afs table(s)\n");
857 }