Add more documentation.
[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 afs 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 /**
311  * Execute the given function for each matching row.
312  *
313  * \param pmd Describes what to match and how.
314  *
315  * \return The return value of the underlying call to osl_rbtree_loop()
316  * or osl_rbtree_loop_reverse().
317  */
318 int for_each_matching_row(struct pattern_match_data *pmd)
319 {
320         if (pmd->pm_flags & PM_REVERSE_LOOP)
321                 return osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
322                         action_if_pattern_matches);
323         return osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
324                         action_if_pattern_matches);
325 }
326
327 /**
328  * Compare two osl objects of string type.
329  *
330  * \param obj1 Pointer to the first object.
331  * \param obj2 Pointer to the second object.
332  *
333  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
334  * are taken into account.
335  *
336  * \return It returns an integer less than, equal to, or greater than zero if
337  * \a obj1 is found, respectively, to be less than, to match, or be greater than
338  * obj2.
339  *
340  * \sa strcmp(3), strncmp(3), osl_compare_func.
341  */
342 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
343 {
344         const char *str1 = (const char *)obj1->data;
345         const char *str2 = (const char *)obj2->data;
346         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
347 }
348
349 /*
350  * write input from fd to dynamically allocated buffer,
351  * but maximal max_size byte.
352  */
353 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
354 {
355         const size_t chunk_size = 1024;
356         size_t size = 2048, received = 0;
357         int ret;
358         char *buf = para_malloc(size);
359
360         for (;;) {
361                 ret = recv_bin_buffer(fd, buf + received, chunk_size);
362                 if (ret <= 0)
363                         break;
364                 received += ret;
365                 if (received + chunk_size >= size) {
366                         size *= 2;
367                         ret = -E_INPUT_TOO_LARGE;
368                         if (size > max_size)
369                                 break;
370                         buf = para_realloc(buf, size);
371                 }
372         }
373         obj->data = buf;
374         obj->size = received;
375         if (ret < 0)
376                 free(buf);
377         return ret;
378 }
379
380 /**
381  * Read data from a file descriptor, and send it to the afs process.
382  *
383  * \param fd File descriptor to read data from.
384  * \param arg_obj Pointer to the arguments to \a f.
385  * \param f The callback function.
386  * \param max_len Don't read more than that many bytes from stdin.
387  * \param result The result of the query is stored here.
388  *
389  * This function is used by commands that wish to let para_server store
390  * arbitrary data specified by the user (for instance the add_blob family of
391  * commands). First, at most \a max_len bytes are read from \a fd, the result
392  * is concatenated with the buffer given by \a arg_obj, and the combined buffer
393  * is made available to the parent process via shared memory.
394  *
395  * \return Negative on errors, the return value of the underlying call to
396  * send_callback_request() otherwise.
397  */
398 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
399                 unsigned max_len, struct osl_object *result)
400 {
401         struct osl_object query, stdin_obj;
402         int ret;
403
404         ret = send_buffer(fd, AWAITING_DATA_MSG);
405         if (ret < 0)
406                 return ret;
407         ret = fd2buf(fd, max_len, &stdin_obj);
408         if (ret < 0)
409                 return ret;
410         query.size = arg_obj->size + stdin_obj.size;
411         query.data = para_malloc(query.size);
412         memcpy(query.data, arg_obj->data, arg_obj->size);
413         memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
414         free(stdin_obj.data);
415         ret = send_callback_request(f, &query, result);
416         free(query.data);
417         return ret;
418 }
419
420 /**
421  * Open the audio file with highest score.
422  *
423  * \param afd Audio file data is returned here.
424  *
425  * This stores all information for streaming the "best" audio file
426  * in the \a afd structure.
427  *
428  * \return Positive on success, negative on errors.
429  *
430  * \sa close_audio_file(), open_and_update_audio_file().
431  */
432 int open_next_audio_file(struct audio_file_data *afd)
433 {
434         struct osl_row *aft_row;
435         int ret;
436         for (;;) {
437                 ret = score_get_best(&aft_row, &afd->score);
438                 if (ret < 0)
439                         return ret;
440                 ret = open_and_update_audio_file(aft_row, afd);
441                 if (ret >= 0)
442                         return ret;
443         }
444 }
445
446 /**
447  * Free all resources which were allocated by open_next_audio_file().
448  *
449  * \param afd The structure previously filled in by open_next_audio_file().
450  *
451  * \return The return value of the underlying call to para_munmap().
452  *
453  * \sa open_next_audio_file().
454  */
455 int close_audio_file(struct audio_file_data *afd)
456 {
457         free(afd->afhi.chunk_table);
458         return para_munmap(afd->map.data, afd->map.size);
459 }
460
461 static enum play_mode init_admissible_files(void)
462 {
463         int ret;
464
465         if (conf.mood_given) {
466                 ret = change_current_mood(conf.mood_arg);
467                 if (ret >= 0) {
468                         if (conf.playlist_given)
469                                 PARA_WARNING_LOG("ignoring playlist %s\n",
470                                         conf.playlist_arg);
471                         return PLAY_MODE_MOOD;
472                 }
473         }
474         if (conf.playlist_given) {
475                 ret = playlist_open(conf.playlist_arg);
476                 if (ret >= 0)
477                         return PLAY_MODE_PLAYLIST;
478         }
479         ret = change_current_mood(NULL); /* open first available mood */
480         if (ret >= 0)
481                 return PLAY_MODE_MOOD;
482         change_current_mood(""); /* open dummy mood, always successful */
483         return PLAY_MODE_MOOD;
484 }
485
486 static int setup_command_socket_or_die(void)
487 {
488         int ret;
489         char *socket_name = conf.afs_socket_arg;
490         struct sockaddr_un unix_addr;
491
492         unlink(socket_name);
493         ret = create_local_socket(socket_name, &unix_addr,
494                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
495         if (ret < 0) {
496                 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
497                 exit(EXIT_FAILURE);
498         }
499         if (listen(ret , 5) < 0) {
500                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
501                 exit(EXIT_FAILURE);
502         }
503         PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
504                 ret);
505         return ret;
506 }
507
508 static void close_afs_tables(enum osl_close_flags flags)
509 {
510         PARA_NOTICE_LOG("closing afs_tables\n");
511         score_shutdown(flags);
512         attribute_shutdown(flags);
513         close_current_mood();
514         playlist_close();
515         moods_shutdown(flags);
516         playlists_shutdown(flags);
517         lyrics_shutdown(flags);
518         images_shutdown(flags);
519         aft_shutdown(flags);
520 }
521
522 static char *database_dir;
523
524 static int make_database_dir(void)
525 {
526         int ret;
527
528         if (!database_dir) {
529                 if (conf.afs_database_dir_given)
530                         database_dir = para_strdup(conf.afs_database_dir_arg);
531                 else {
532                         char *home = para_homedir();
533                         database_dir = make_message(
534                                 "%s/.paraslash/afs_database", home);
535                         free(home);
536                 }
537         }
538         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
539         ret = para_mkdir(database_dir, 0777);
540         if (ret >= 0 || ret == -E_EXIST)
541                 return 1;
542         free(database_dir);
543         database_dir = NULL;
544         return ret;
545 }
546
547
548 static int open_afs_tables(void)
549 {
550         int ret = make_database_dir();
551
552         if (ret < 0)
553                 return ret;
554         ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES], database_dir);
555         if (ret < 0)
556                 return ret;
557         ret = moods_init(&afs_tables[TBLNUM_MOODS], database_dir);
558         if (ret < 0)
559                 goto moods_init_error;
560         ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST], database_dir);
561         if (ret < 0)
562                 goto playlists_init_error;
563         ret = lyrics_init(&afs_tables[TBLNUM_LYRICS], database_dir);
564         if (ret < 0)
565                 goto lyrics_init_error;
566         ret = images_init(&afs_tables[TBLNUM_IMAGES], database_dir);
567         if (ret < 0)
568                 goto images_init_error;
569         ret = score_init(&afs_tables[TBLNUM_SCORES], database_dir);
570         if (ret < 0)
571                 goto score_init_error;
572         ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES], database_dir);
573         if (ret < 0)
574                 goto aft_init_error;
575         return 1;
576
577 aft_init_error:
578         score_shutdown(OSL_MARK_CLEAN);
579 score_init_error:
580         images_shutdown(OSL_MARK_CLEAN);
581 images_init_error:
582         lyrics_shutdown(OSL_MARK_CLEAN);
583 lyrics_init_error:
584         playlists_shutdown(OSL_MARK_CLEAN);
585 playlists_init_error:
586         moods_shutdown(OSL_MARK_CLEAN);
587 moods_init_error:
588         attribute_shutdown(OSL_MARK_CLEAN);
589         return ret;
590 }
591
592 static int server_socket;
593 static struct command_task command_task_struct;
594 static struct signal_task signal_task_struct;
595
596 static void unregister_tasks(void)
597 {
598         unregister_task(&command_task_struct.task);
599         unregister_task(&signal_task_struct.task);
600 }
601
602 static void signal_pre_select(struct sched *s, struct task *t)
603 {
604         struct signal_task *st = t->private_data;
605         t->ret = 1;
606         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
607 }
608
609 static void signal_post_select(struct sched *s, struct task *t)
610 {
611         struct signal_task *st = t->private_data;
612         t->ret = 1;
613         if (!FD_ISSET(st->fd, &s->rfds))
614                 return;
615         st->signum = para_next_signal();
616         t->ret = 1;
617         if (st->signum == SIGUSR1)
618                 return; /* ignore SIGUSR1 */
619         if (st->signum == SIGHUP) {
620                 close_afs_tables(OSL_MARK_CLEAN);
621                 t->ret = open_afs_tables();
622                 return;
623         }
624         PARA_NOTICE_LOG("caught signal %d\n", st->signum);
625         t->ret = -E_SIGNAL_CAUGHT;
626         unregister_tasks();
627 }
628
629 static void register_signal_task(void)
630 {
631         struct signal_task *st = &signal_task_struct;
632         st->fd = para_signal_init();
633         PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
634         para_install_sighandler(SIGINT);
635         para_install_sighandler(SIGTERM);
636         para_install_sighandler(SIGPIPE);
637         para_install_sighandler(SIGHUP);
638
639         st->task.pre_select = signal_pre_select;
640         st->task.post_select = signal_post_select;
641         st->task.private_data = st;
642         sprintf(st->task.status, "signal task");
643         register_task(&st->task);
644 }
645
646 static struct list_head afs_client_list;
647
648 struct afs_client {
649         struct list_head node;
650         int fd;
651         struct timeval connect_time;
652 };
653
654 static void command_pre_select(struct sched *s, struct task *t)
655 {
656         struct command_task *ct = t->private_data;
657         struct afs_client *client;
658
659         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
660         list_for_each_entry(client, &afs_client_list, node)
661                 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
662         t->ret = 1;
663 }
664
665 /*
666  * On errors, negative value is written to fd.
667  * On success: If query produced a result, the result_shmid is written to fd.
668  * Otherwise, zero is written.
669  */
670 static int call_callback(int fd, int query_shmid)
671 {
672         void *query_shm, *result_shm;
673         struct callback_query *cq;
674         struct callback_result *cr;
675         struct osl_object query, result = {.data = NULL};
676         int result_shmid = -1, ret, ret2;
677
678         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
679         if (ret < 0)
680                 goto out;
681         cq = query_shm;
682         query.data = (char *)query_shm + sizeof(*cq);
683         query.size = cq->query_size;
684         ret = cq->handler(&query, &result);
685         ret2 = shm_detach(query_shm);
686         if (ret2 < 0 && ret >= 0)
687                 ret = ret2;
688         if (ret < 0)
689                 goto out;
690         ret = 0;
691         if (!result.data || !result.size)
692                 goto out;
693         ret = shm_new(result.size + sizeof(struct callback_result));
694         if (ret < 0)
695                 goto out;
696         result_shmid = ret;
697         ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
698         if (ret < 0)
699                 goto out;
700         cr = result_shm;
701         cr->result_size = result.size;
702         memcpy(result_shm + sizeof(*cr), result.data, result.size);
703         ret = shm_detach(result_shm);
704         if (ret < 0)
705                 goto out;
706         ret = result_shmid;
707 out:
708         free(result.data);
709         ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
710         if (ret < 0 || ret2 < 0) {
711                 if (result_shmid >= 0)
712                         if (shm_destroy(result_shmid) < 0)
713                                 PARA_ERROR_LOG("destroy result failed\n");
714                 if (ret >= 0)
715                         ret = ret2;
716         }
717         return ret;
718 }
719
720 static void execute_afs_command(int fd, uint32_t expected_cookie)
721 {
722         uint32_t cookie;
723         int query_shmid;
724         char buf[sizeof(cookie) + sizeof(query_shmid)];
725         int ret = recv_bin_buffer(fd, buf, sizeof(buf));
726
727         if (ret < 0) {
728                 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-ret));
729                 return;
730         }
731         if (ret != sizeof(buf)) {
732                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
733                         ret, (long unsigned) sizeof(buf));
734                 return;
735         }
736         cookie = *(uint32_t *)buf;
737         if (cookie != expected_cookie) {
738                 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
739                         (unsigned)cookie, (unsigned)expected_cookie);
740                 return;
741         }
742         query_shmid = *(int *)(buf + sizeof(cookie));
743         if (query_shmid < 0) {
744                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
745                         query_shmid);
746                 return;
747         }
748         /* Ignore return value: Errors might be OK here. */
749         call_callback(fd, query_shmid);
750 }
751
752 /** Shutdown connection if query has not arrived until this many seconds. */
753 #define AFS_CLIENT_TIMEOUT 3
754
755 static void command_post_select(struct sched *s, struct task *t)
756 {
757         struct command_task *ct = t->private_data;
758         struct sockaddr_un unix_addr;
759         struct afs_client *client, *tmp;
760
761         /* First, check the list of connected clients. */
762         list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
763                 if (FD_ISSET(client->fd, &s->rfds))
764                         execute_afs_command(client->fd, ct->cookie);
765                 else { /* prevent bogus connection flooding */
766                         struct timeval diff;
767                         tv_diff(now, &client->connect_time, &diff);
768                         if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
769                                 continue;
770                         PARA_WARNING_LOG("connection timeout\n");
771                 }
772                 close(client->fd);
773                 list_del(&client->node);
774                 free(client);
775         }
776         /* Next, accept connections on the local socket. */
777         if (!FD_ISSET(ct->fd, &s->rfds))
778                 goto out;
779         t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
780         if (t->ret < 0) {
781                 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
782                 goto out;
783         }
784         client = para_malloc(sizeof(*client));
785         client->fd = t->ret;
786         client->connect_time = *now;
787         para_list_add(&client->node, &afs_client_list);
788 out:
789         t->ret = 1;
790 }
791
792 static void register_command_task(uint32_t cookie)
793 {
794         struct command_task *ct = &command_task_struct;
795         ct->fd = setup_command_socket_or_die();
796         ct->cookie = cookie;
797
798         ct->task.pre_select = command_pre_select;
799         ct->task.post_select = command_post_select;
800         ct->task.private_data = ct;
801         sprintf(ct->task.status, "command task");
802         register_task(&ct->task);
803 }
804
805 static void register_tasks(uint32_t cookie)
806 {
807         register_signal_task();
808         register_command_task(cookie);
809 }
810
811 /**
812  * Initialize the audio file selector process.
813  *
814  * \param cookie The value used for "authentication".
815  * \param socket_fd File descriptor used for communication with the server.
816  */
817 __noreturn void afs_init(uint32_t cookie, int socket_fd)
818 {
819         enum play_mode current_play_mode;
820         struct sched s;
821         int ret;
822
823         INIT_LIST_HEAD(&afs_client_list);
824         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 /**
900  * Flags for the check command.
901  *
902  * \sa com_check().
903  */
904 enum com_check_flags {
905         /** Check the audio file table. */
906         CHECK_AFT = 1,
907         /** Check the mood table. */
908         CHECK_MOODS = 2,
909         /** Check the playlist table. */
910         CHECK_PLAYLISTS = 4
911 };
912
913 int com_check(int fd, int argc, char * const * const argv)
914 {
915         unsigned flags = 0;
916         int i, ret;
917         struct osl_object result;
918
919         for (i = 1; i < argc; i++) {
920                 const char *arg = argv[i];
921                 if (arg[0] != '-')
922                         break;
923                 if (!strcmp(arg, "--")) {
924                         i++;
925                         break;
926                 }
927                 if (!strcmp(arg, "-a")) {
928                         flags |= CHECK_AFT;
929                         continue;
930                 }
931                 if (!strcmp(arg, "-p")) {
932                         flags |= CHECK_PLAYLISTS;
933                         continue;
934                 }
935                 if (!strcmp(arg, "-m")) {
936                         flags |= CHECK_MOODS;
937                         continue;
938                 }
939                 return -E_AFS_SYNTAX;
940         }
941         if (i < argc)
942                 return -E_AFS_SYNTAX;
943         if (!flags)
944                 flags = ~0U;
945         if (flags & CHECK_AFT) {
946                 ret = send_callback_request(aft_check_callback, NULL, &result);
947                 if (ret < 0)
948                         return ret;
949                 if (ret > 0) {
950                         ret = send_buffer(fd, (char *) result.data);
951                         free(result.data);
952                         if (ret < 0)
953                                 return ret;
954                 }
955         }
956         if (flags & CHECK_PLAYLISTS) {
957                 ret = send_callback_request(playlist_check_callback, NULL, &result);
958                 if (ret < 0)
959                         return ret;
960                 if (ret > 0) {
961                         ret = send_buffer(fd, (char *) result.data);
962                         free(result.data);
963                         if (ret < 0)
964                                 return ret;
965                 }
966         }
967         if (flags & CHECK_MOODS) {
968                 ret = send_callback_request(mood_check_callback, NULL, &result);
969                 if (ret < 0)
970                         return ret;
971                 if (ret > 0) {
972                         ret = send_buffer(fd, (char *) result.data);
973                         free(result.data);
974                         if (ret < 0)
975                                 return ret;
976                 }
977         }
978         return 1;
979 }