More mood cleanups.
[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         struct sockaddr_un unix_addr;
148         size_t query_shm_size = sizeof(*cq);
149
150         if (query)
151                 query_shm_size += query->size;
152         ret = shm_new(query_shm_size);
153         if (ret < 0)
154                 return ret;
155         query_shmid = ret;
156         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
157         if (ret < 0)
158                 goto out;
159         cq = query_shm;
160         cq->handler = f;
161         cq->query_size = query_shm_size - sizeof(*cq);
162
163         if (query)
164                 memcpy(query_shm + sizeof(*cq), query->data, query->size);
165         ret = shm_detach(query_shm);
166         if (ret < 0)
167                 goto out;
168
169         *(uint32_t *) buf = afs_socket_cookie;
170         *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
171
172         ret = get_stream_socket(PF_UNIX);
173         if (ret < 0)
174                 goto out;
175         fd = ret;
176         ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
177         if (ret < 0)
178                 goto out;
179         ret = PARA_CONNECT(fd, &unix_addr);
180         if (ret < 0)
181                 goto out;
182         ret = send_bin_buffer(fd, buf, sizeof(buf));
183         if (ret < 0)
184                 goto out;
185         ret = recv_bin_buffer(fd, buf, sizeof(buf));
186         if (ret < 0)
187                 goto out;
188         if (ret != sizeof(int)) {
189                 ret = -E_RECV;
190                 goto out;
191         }
192         ret = *(int *) buf;
193         if (ret <= 0)
194                 goto out;
195         result_shmid = ret;
196         ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
197         if (ret >= 0) {
198                 assert(result);
199                 cr = result_shm;
200                 result->size = cr->result_size;
201                 result->data = para_malloc(result->size);
202                 memcpy(result->data, result_shm + sizeof(*cr), result->size);
203                 ret = shm_detach(result_shm);
204                 if (ret < 0)
205                         PARA_ERROR_LOG("can not detach result\n");
206         } else
207                 PARA_ERROR_LOG("attach result failed: %d\n", ret);
208         if (shm_destroy(result_shmid) < 0)
209                 PARA_ERROR_LOG("destroy result failed\n");
210         ret = 1;
211 out:
212         if (shm_destroy(query_shmid) < 0)
213                 PARA_ERROR_LOG("%s\n", "shm destroy error");
214         if (fd >= 0)
215                 close(fd);
216 //      PARA_DEBUG_LOG("callback_ret: %d\n", ret);
217         return ret;
218 }
219
220 /**
221  * Send a callback request passing an options structure and an argument vector.
222  *
223  * \param options pointer to an arbitrary data structure.
224  * \param argc Argument count.
225  * \param argv Standard argument vector.
226  * \param f The callback function.
227  * \param result The result of the query is stored here.
228  *
229  * Some commands have a couple of options that are parsed in child context for
230  * syntactic correctness and are stored in a special options structure for that
231  * command. This function allows to pass such a structure together with a list
232  * of further arguments (often a list of audio files) to the parent process.
233  *
234  * \sa send_standard_callback_request(), send_callback_request().
235  */
236 int send_option_arg_callback_request(struct osl_object *options,
237                 int argc,  char * const * const argv, callback_function *f,
238                 struct osl_object *result)
239 {
240         char *p;
241         int i, ret;
242         struct osl_object query = {.size = options? options->size : 0};
243
244         for (i = 0; i < argc; i++)
245                 query.size += strlen(argv[i]) + 1;
246         query.data = para_malloc(query.size);
247         p = query.data;
248         if (options) {
249                 memcpy(query.data, options->data, options->size);
250                 p += options->size;
251         }
252         for (i = 0; i < argc; i++) {
253                 strcpy(p, argv[i]); /* OK */
254                 p += strlen(argv[i]) + 1;
255         }
256         ret = send_callback_request(f, &query, result);
257         free(query.data);
258         return ret;
259 }
260
261 /**
262  * Send a callback request with an argument vector only.
263  *
264  * \param argc The same meaning as in send_option_arg_callback_request().
265  * \param argv The same meaning as in send_option_arg_callback_request().
266  * \param f The same meaning as in send_option_arg_callback_request().
267  * \param result The same meaning as in send_option_arg_callback_request().
268  *
269  * This is similar to send_option_arg_callback_request(), but no options buffer
270  * is passed to the parent process.
271  *
272  * \return The return value of the underlying call to
273  * send_option_arg_callback_request().
274  */
275 int send_standard_callback_request(int argc,  char * const * const argv,
276                 callback_function *f, struct osl_object *result)
277 {
278         return send_option_arg_callback_request(NULL, argc, argv, f, result);
279 }
280
281 /**
282  * Compare two osl objects of string type.
283  *
284  * \param obj1 Pointer to the first object.
285  * \param obj2 Pointer to the second object.
286  *
287  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
288  * are taken into account.
289  *
290  * \return It returns an integer less than, equal to, or greater than zero if
291  * \a obj1 is found, respectively, to be less than, to match, or be greater than
292  * obj2.
293  *
294  * \sa strcmp(3), strncmp(3), osl_compare_func.
295  */
296 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
297 {
298         const char *str1 = (const char *)obj1->data;
299         const char *str2 = (const char *)obj2->data;
300         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
301 }
302
303 /**
304  * A wrapper for strtol(3).
305  *
306  * \param str The string to be converted to a long integer.
307  * \param result The converted value is stored here.
308  *
309  * \return Positive on success, -E_ATOL on errors.
310  *
311  * \sa strtol(3), atoi(3).
312  */
313 int para_atol(const char *str, long *result)
314 {
315         char *endptr;
316         long val;
317         int ret, base = 10;
318
319         errno = 0; /* To distinguish success/failure after call */
320         val = strtol(str, &endptr, base);
321         ret = -E_ATOL;
322         if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
323                 goto out; /* overflow */
324         if (errno != 0 && val == 0)
325                 goto out; /* other error */
326         if (endptr == str)
327                 goto out; /* No digits were found */
328         if (*endptr != '\0')
329                 goto out; /* Further characters after number */
330         *result = val;
331         ret = 1;
332 out:
333         return ret;
334 }
335
336
337 /*
338  * write input from fd to dynamically allocated buffer,
339  * but maximal max_size byte.
340  */
341 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
342 {
343         const size_t chunk_size = 1024;
344         size_t size = 2048, received = 0;
345         int ret;
346         char *buf = para_malloc(size);
347
348         for (;;) {
349                 ret = recv_bin_buffer(fd, buf + received, chunk_size);
350                 if (ret <= 0)
351                         break;
352                 received += ret;
353                 if (received + chunk_size >= size) {
354                         size *= 2;
355                         ret = -E_INPUT_TOO_LARGE;
356                         if (size > max_size)
357                                 break;
358                         buf = para_realloc(buf, size);
359                 }
360         }
361         obj->data = buf;
362         obj->size = received;
363         if (ret < 0)
364                 free(buf);
365         return ret;
366 }
367
368 /**
369  * Read data from a file descriptor, and send it to the afs process.
370  *
371  * \param fd File descriptor to read data from.
372  * \param arg_obj Pointer to the arguments to \a f.
373  * \param f The callback function.
374  * \param max_len Don't read more than that many bytes from stdin.
375  * \param result The result of the query is stored here.
376  *
377  * This function is used by commands that wish to let para_server store
378  * arbitrary data specified by the user (for instance the add_blob family of
379  * commands). First, at most \a max_len bytes are read from \a fd, the result
380  * is concatenated with the buffer given by \a arg_obj, and the combined buffer
381  * is made available to the parent process via shared memory.
382  *
383  * \return Negative on errors, the return value of the underlying call to
384  * send_callback_request() otherwise.
385  */
386 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
387                 unsigned max_len, struct osl_object *result)
388 {
389         struct osl_object query, stdin_obj;
390         int ret;
391
392         ret = send_buffer(fd, AWAITING_DATA_MSG);
393         if (ret < 0)
394                 return ret;
395         ret = fd2buf(fd, max_len, &stdin_obj);
396         if (ret < 0)
397                 return ret;
398         query.size = arg_obj->size + stdin_obj.size;
399         query.data = para_malloc(query.size);
400         memcpy(query.data, arg_obj->data, arg_obj->size);
401         memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
402         free(stdin_obj.data);
403         ret = send_callback_request(f, &query, result);
404         free(query.data);
405         return ret;
406 }
407
408 /**
409  * Open the audio file with highest score.
410  *
411  * \param afd Audio file data is returned here.
412  *
413  * This stores all information for streaming the "best" audio file
414  * in the \a afd structure.
415  *
416  * \return Positive on success, negative on errors.
417  *
418  * \sa close_audio_file(), open_and_update_audio_file().
419  */
420 int open_next_audio_file(struct audio_file_data *afd)
421 {
422         struct osl_row *aft_row;
423         int ret;
424         for (;;) {
425                 ret = score_get_best(&aft_row, &afd->score);
426                 if (ret < 0)
427                         return ret;
428                 ret = open_and_update_audio_file(aft_row, afd);
429                 if (ret >= 0)
430                         return ret;
431         }
432 }
433
434 /**
435  * Free all resources which were allocated by open_next_audio_file().
436  *
437  * \param afd The structure previously filled in by open_next_audio_file().
438  *
439  * \return The return value of the underlying call to para_munmap().
440  *
441  * \sa open_next_audio_file().
442  */
443 int close_audio_file(struct audio_file_data *afd)
444 {
445         free(afd->afhi.chunk_table);
446         return para_munmap(afd->map.data, afd->map.size);
447 }
448
449 #if 0
450 static void play_loop(enum play_mode current_play_mode)
451 {
452         int i, ret;
453         struct audio_file_data afd;
454
455         afd.current_play_mode = current_play_mode;
456         for (i = 0; i < 0; i++) {
457                 ret = open_next_audio_file(&afd);
458                 if (ret < 0) {
459                         PARA_ERROR_LOG("failed to open next audio file: %d\n", ret);
460                         return;
461                 }
462                 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd.path, afd.score);
463                 sleep(1);
464                 close_audio_file(&afd);
465         }
466 }
467 #endif
468
469
470 static enum play_mode init_admissible_files(void)
471 {
472         int ret;
473         char *given_mood, *given_playlist;
474
475         given_mood = "mood_that_was_given_at_the_command_line";
476         given_playlist = "given_playlist";
477
478         if (given_mood) {
479                 ret = change_current_mood(given_mood);
480                 if (ret >= 0) {
481                         if (given_playlist)
482                                 PARA_WARNING_LOG("ignoring playlist %s\n",
483                                         given_playlist);
484                         return PLAY_MODE_MOOD;
485                 }
486         }
487         if (given_playlist) {
488                 ret = playlist_open(given_playlist);
489                 if (ret >= 0)
490                         return PLAY_MODE_PLAYLIST;
491         }
492         ret = change_current_mood(NULL); /* open first available mood */
493         if (ret >= 0)
494                 return PLAY_MODE_MOOD;
495         change_current_mood(""); /* open dummy mood, always successful */
496         return PLAY_MODE_MOOD;
497 }
498
499 static int setup_command_socket_or_die(void)
500 {
501         int ret;
502         char *socket_name = conf.afs_socket_arg;
503         struct sockaddr_un unix_addr;
504
505         unlink(socket_name);
506         ret = create_local_socket(socket_name, &unix_addr,
507                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
508         if (ret < 0) {
509                 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
510                 exit(EXIT_FAILURE);
511         }
512         if (listen(ret , 5) < 0) {
513                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
514                 exit(EXIT_FAILURE);
515         }
516         PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
517                 ret);
518         return ret;
519 }
520
521 static int server_socket;
522 static struct command_task command_task_struct;
523 static struct signal_task signal_task_struct;
524
525 static void unregister_tasks(void)
526 {
527         unregister_task(&command_task_struct.task);
528         unregister_task(&signal_task_struct.task);
529 }
530
531 static void close_afs_tables(enum osl_close_flags flags)
532 {
533         PARA_NOTICE_LOG("closing afs_tables\n");
534         score_shutdown(flags);
535         attribute_shutdown(flags);
536         close_current_mood();
537         playlist_close();
538         moods_shutdown(flags);
539         playlists_shutdown(flags);
540         lyrics_shutdown(flags);
541         images_shutdown(flags);
542         aft_shutdown(flags);
543 }
544
545 static void signal_pre_select(struct sched *s, struct task *t)
546 {
547         struct signal_task *st = t->private_data;
548         t->ret = 1;
549         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
550 }
551
552 static void signal_post_select(struct sched *s, struct task *t)
553 {
554         struct signal_task *st = t->private_data;
555         t->ret = 1;
556         if (!FD_ISSET(st->fd, &s->rfds))
557                 return;
558         st->signum = para_next_signal();
559         t->ret = 1;
560         if (st->signum == SIGUSR1)
561                 return; /* ignore SIGUSR1 */
562         PARA_NOTICE_LOG("caught signal %d\n", st->signum);
563         t->ret = -E_SIGNAL_CAUGHT;
564         unregister_tasks();
565 }
566
567 static void register_signal_task(void)
568 {
569         struct signal_task *st = &signal_task_struct;
570         st->fd = para_signal_init();
571         PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
572         para_install_sighandler(SIGINT);
573         para_install_sighandler(SIGTERM);
574         para_install_sighandler(SIGPIPE);
575
576         st->task.pre_select = signal_pre_select;
577         st->task.post_select = signal_post_select;
578         st->task.private_data = st;
579         sprintf(st->task.status, "signal task");
580         register_task(&st->task);
581 }
582
583 static void command_pre_select(struct sched *s, struct task *t)
584 {
585         struct command_task *ct = t->private_data;
586         t->ret = 1;
587         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
588 }
589
590 /*
591  * On errors, negative value is written to fd.
592  * On success: If query produced a result, the result_shmid is written to fd.
593  * Otherwise, zero is written.
594  */
595 static int call_callback(int fd, int query_shmid)
596 {
597         void *query_shm, *result_shm;
598         struct callback_query *cq;
599         struct callback_result *cr;
600         struct osl_object query, result = {.data = NULL};
601         int result_shmid = -1, ret, ret2;
602
603         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
604         if (ret < 0)
605                 goto out;
606         cq = query_shm;
607         query.data = (char *)query_shm + sizeof(*cq);
608         query.size = cq->query_size;
609         ret = cq->handler(&query, &result);
610         ret2 = shm_detach(query_shm);
611         if (ret2 < 0 && ret >= 0)
612                 ret = ret2;
613         if (ret < 0)
614                 goto out;
615         ret = 0;
616         if (!result.data || !result.size)
617                 goto out;
618         ret = shm_new(result.size + sizeof(struct callback_result));
619         if (ret < 0)
620                 goto out;
621         result_shmid = ret;
622         ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
623         if (ret < 0)
624                 goto out;
625         cr = result_shm;
626         cr->result_size = result.size;
627         memcpy(result_shm + sizeof(*cr), result.data, result.size);
628         ret = shm_detach(result_shm);
629         if (ret < 0)
630                 goto out;
631         ret = result_shmid;
632 out:
633         free(result.data);
634         ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
635         if (ret < 0 || ret2 < 0) {
636                 if (result_shmid >= 0)
637                         if (shm_destroy(result_shmid) < 0)
638                                 PARA_ERROR_LOG("destroy result failed\n");
639                 if (ret >= 0)
640                         ret = ret2;
641         }
642         return ret;
643 }
644
645 static void command_post_select(struct sched *s, struct task *t)
646 {
647         struct command_task *ct = t->private_data;
648         struct sockaddr_un unix_addr;
649         char buf[sizeof(uint32_t) + sizeof(int)];
650         uint32_t cookie;
651         int query_shmid, fd;
652
653         t->ret = 1;
654         if (!FD_ISSET(ct->fd, &s->rfds))
655                 return;
656         t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
657         if (t->ret < 0)
658                 return;
659         /*
660          * The following errors may be caused by a malicious local user. So do
661          * not return an error in this case as this would terminate  para_afs
662          * and para_server.
663          */
664         fd = t->ret;
665         /* FIXME: This is easily dosable (peer doesn't send data) */
666         t->ret = recv_bin_buffer(fd, buf, sizeof(buf));
667         if (t->ret < 0) {
668                 PARA_NOTICE_LOG("%s (%d)\n", PARA_STRERROR(-t->ret), t->ret);
669                 goto out;
670         }
671         if (t->ret != sizeof(buf)) {
672                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
673                         t->ret, (long unsigned) sizeof(buf));
674                 goto out;
675         }
676         cookie = *(uint32_t *)buf;
677         if (cookie != ct->cookie) {
678                 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
679                         (unsigned)cookie, (unsigned)ct->cookie);
680                 goto out;
681         }
682         query_shmid = *(int *)(buf + sizeof(cookie));
683         if (query_shmid < 0) {
684                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
685                         query_shmid);
686                 goto out;
687         }
688         /* Ignore return value: Errors might be ok here. */
689         call_callback(fd, query_shmid);
690 out:
691         t->ret = 1;
692         close(fd);
693 }
694
695 static void register_command_task(uint32_t cookie)
696 {
697         struct command_task *ct = &command_task_struct;
698         ct->fd = setup_command_socket_or_die();
699         ct->cookie = cookie;
700
701         ct->task.pre_select = command_pre_select;
702         ct->task.post_select = command_post_select;
703         ct->task.private_data = ct;
704         sprintf(ct->task.status, "command task");
705         register_task(&ct->task);
706 }
707
708 void register_tasks(uint32_t cookie)
709 {
710         register_signal_task();
711         register_command_task(cookie);
712 }
713
714 static char *database_dir;
715
716 static int make_database_dir(void)
717 {
718         int ret;
719
720         if (!database_dir) {
721                 if (conf.afs_database_dir_given)
722                         database_dir = para_strdup(conf.afs_database_dir_arg);
723                 else {
724                         char *home = para_homedir();
725                         database_dir = make_message(
726                                 "%s/.paraslash/afs_database", home);
727                         free(home);
728                 }
729         }
730         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
731         ret = para_mkdir(database_dir, 0777);
732         if (ret >= 0 || ret == -E_EXIST)
733                 return 1;
734         free(database_dir);
735         database_dir = NULL;
736         return ret;
737 }
738
739 static int open_afs_tables(void)
740 {
741         int ret = make_database_dir();
742
743         if (ret < 0)
744                 return ret;
745         ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES], database_dir);
746         if (ret < 0)
747                 return ret;
748         ret = moods_init(&afs_tables[TBLNUM_MOODS], database_dir);
749         if (ret < 0)
750                 goto moods_init_error;
751         ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST], database_dir);
752         if (ret < 0)
753                 goto playlists_init_error;
754         ret = lyrics_init(&afs_tables[TBLNUM_LYRICS], database_dir);
755         if (ret < 0)
756                 goto lyrics_init_error;
757         ret = images_init(&afs_tables[TBLNUM_IMAGES], database_dir);
758         if (ret < 0)
759                 goto images_init_error;
760         ret = score_init(&afs_tables[TBLNUM_SCORES], database_dir);
761         if (ret < 0)
762                 goto score_init_error;
763         ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES], database_dir);
764         if (ret < 0)
765                 goto aft_init_error;
766         return 1;
767
768 aft_init_error:
769         score_shutdown(OSL_MARK_CLEAN);
770 score_init_error:
771         images_shutdown(OSL_MARK_CLEAN);
772 images_init_error:
773         lyrics_shutdown(OSL_MARK_CLEAN);
774 lyrics_init_error:
775         playlists_shutdown(OSL_MARK_CLEAN);
776 playlists_init_error:
777         moods_shutdown(OSL_MARK_CLEAN);
778 moods_init_error:
779         attribute_shutdown(OSL_MARK_CLEAN);
780         return ret;
781 }
782
783 __noreturn int afs_init(uint32_t cookie, int socket_fd)
784 {
785         enum play_mode current_play_mode;
786         struct sched s;
787         int ret = open_afs_tables();
788
789         if (ret < 0) {
790                 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
791                 exit(EXIT_FAILURE);
792         }
793         server_socket = socket_fd;
794         ret = mark_fd_nonblock(server_socket);
795         if (ret < 0)
796                 exit(EXIT_FAILURE);
797         PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
798                 server_socket, (unsigned) cookie);
799         current_play_mode = init_admissible_files();
800         register_tasks(cookie);
801         s.default_timeout.tv_sec = 0;
802         s.default_timeout.tv_usec = 99 * 1000;
803         ret = sched(&s);
804         if (ret < 0)
805                 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
806         close_afs_tables(OSL_MARK_CLEAN);
807         exit(EXIT_FAILURE);
808 }
809
810 static int create_tables_callback(const struct osl_object *query,
811                 __a_unused struct osl_object *result)
812 {
813         uint32_t table_mask = *(uint32_t *)query->data;
814         int i, ret;
815
816         close_afs_tables(OSL_MARK_CLEAN);
817         for (i = 0; i < NUM_AFS_TABLES; i++) {
818                 struct table_info *ti = afs_tables + i;
819
820                 if (ti->flags & TBLFLAG_SKIP_CREATE)
821                         continue;
822                 if (!(table_mask & (1 << i)))
823                         continue;
824                 ret = osl_create_table(ti->desc);
825                 if (ret < 0)
826                         return ret;
827         }
828         ret = open_afs_tables();
829         return ret < 0? ret: 0;
830 }
831
832 int com_init(int fd, int argc, char * const * const argv)
833 {
834         int i, j, ret;
835         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
836         struct osl_object query = {.data = &table_mask,
837                 .size = sizeof(table_mask)};
838
839         if (argc != 1) {
840                 table_mask = 0;
841                 for (i = 1; i < argc; i++) {
842                         for (j = 0; j < NUM_AFS_TABLES; j++) {
843                                 struct table_info *ti = afs_tables + j;
844
845                                 if (ti->flags & TBLFLAG_SKIP_CREATE)
846                                         continue;
847                                 if (strcmp(argv[i], ti->desc->name))
848                                         continue;
849                                 table_mask |= (1 << j);
850                                 break;
851                         }
852                         if (j == NUM_AFS_TABLES)
853                                 return -E_BAD_TABLE_NAME;
854                 }
855         }
856         ret = send_callback_request(create_tables_callback, &query, NULL);
857         if (ret < 0)
858                 return ret;
859         return send_va_buffer(fd, "successfully created afs table(s)\n");
860 }
861
862 enum com_check_flags {
863         CHECK_AFT = 1,
864         CHECK_MOODS = 2,
865         CHECK_PLAYLISTS = 4
866 };
867
868 int com_check(int fd, int argc, char * const * const argv)
869 {
870         unsigned flags = 0;
871         int i, ret;
872         struct osl_object result;
873
874         for (i = 1; i < argc; i++) {
875                 const char *arg = argv[i];
876                 if (arg[0] != '-')
877                         break;
878                 if (!strcmp(arg, "--")) {
879                         i++;
880                         break;
881                 }
882                 if (!strcmp(arg, "-a")) {
883                         flags |= CHECK_AFT;
884                         continue;
885                 }
886                 if (!strcmp(arg, "-p")) {
887                         flags |= CHECK_PLAYLISTS;
888                         continue;
889                 }
890                 if (!strcmp(arg, "-m")) {
891                         flags |= CHECK_MOODS;
892                         continue;
893                 }
894                 return -E_AFS_SYNTAX;
895         }
896         if (i < argc)
897                 return -E_AFS_SYNTAX;
898         if (!flags)
899                 flags = ~0U;
900         if (flags & CHECK_AFT) {
901                 ret = send_callback_request(aft_check_callback, NULL, &result);
902                 if (ret < 0)
903                         return ret;
904                 if (ret > 0) {
905                         ret = send_buffer(fd, (char *) result.data);
906                         free(result.data);
907                         if (ret < 0)
908                                 return ret;
909                 }
910         }
911         if (flags & CHECK_PLAYLISTS) {
912                 ret = send_callback_request(playlist_check_callback, NULL, &result);
913                 if (ret < 0)
914                         return ret;
915                 if (ret > 0) {
916                         ret = send_buffer(fd, (char *) result.data);
917                         free(result.data);
918                         if (ret < 0)
919                                 return ret;
920                 }
921         }
922         return 1;
923 }