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