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