Merge branch 'master' into next
[paraslash.git] / afs.c
1 /*
2  * Copyright (C) 2007-2009 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 "error.h"
14 #include "string.h"
15 #include "afh.h"
16 #include "afs.h"
17 #include "server.h"
18 #include <dirent.h> /* readdir() */
19 #include <sys/mman.h>
20 #include <sys/time.h>
21 #include "net.h"
22 #include "ipc.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 afs_table afs_tables[NUM_AFS_TABLES] = {
57         [TBLNUM_AUDIO_FILES] = {.init = aft_init},
58         [TBLNUM_ATTRIBUTES] = {.init = attribute_init},
59         [TBLNUM_SCORES] = {.init = score_init},
60         [TBLNUM_MOODS] = {.init = moods_init},
61         [TBLNUM_LYRICS] = {.init = lyrics_init},
62         [TBLNUM_IMAGES] = {.init = images_init},
63         [TBLNUM_PLAYLIST] = {.init = playlists_init},
64 };
65
66 struct command_task {
67         /** The file descriptor for the local socket. */
68         int fd;
69         /**
70          * Value sent by the command handlers to identify themselves as
71          * children of the running para_server.
72          */
73         uint32_t cookie;
74         /** The associated task structure. */
75         struct task task;
76 };
77
78 extern int mmd_mutex;
79 extern struct misc_meta_data *mmd;
80
81 static int server_socket;
82 static struct command_task command_task_struct;
83 static struct signal_task signal_task_struct;
84
85 static enum play_mode current_play_mode;
86 static char *current_mop; /* mode or playlist specifier. NULL means dummy mooe */
87
88
89 /**
90  * A random number used to "authenticate" the connection.
91  *
92  * para_server picks this number by random before forking the afs process.  The
93  * command handlers write this number together with the id of the shared memory
94  * area containing the query. This way, a malicious local user has to know this
95  * number to be able to cause the afs process to crash by sending fake queries.
96  */
97 extern uint32_t afs_socket_cookie;
98
99 /**
100  * Struct to let command handlers execute a callback in afs context.
101  *
102  * Commands that need to change the state of afs can't change the relevant data
103  * structures directly because commands are executed in a child process, i.e.
104  * they get their own virtual address space.
105  *
106  * This structure is used by \p send_callback_request() (executed from handler
107  * context) in order to let the afs process call the specified function. An
108  * instance of that structure is written to a shared memory area together with
109  * the arguments to the callback function. The identifier of the shared memory
110  * area is written to the command socket.
111  *
112  * The afs process accepts connections on the command socket and reads the
113  * shared memory id, attaches the corresponing area, calls the given handler to
114  * perform the desired action and to optionally compute a result.
115  *
116  * The result and a \p callback_result structure is then written to another
117  * shared memory area. The identifier for that area is written to the handler's
118  * command socket, so that the handler process can read the id, attach the
119  * shared memory area and use the result.
120  *
121  * \sa struct callback_result.
122  */
123 struct callback_query {
124         /** The function to be called. */
125         callback_function *handler;
126         /** The number of bytes of the query */
127         size_t query_size;
128 };
129
130 /**
131  * Structure embedded in the result of a callback.
132  *
133  * If the callback produced a result, an instance of that structure is embeeded
134  * into the shared memory area holding the result, mainly to let the command
135  * handler know the size of the result.
136  *
137  * \sa struct callback_query.
138  */
139 struct callback_result {
140         /** The number of bytes of the result. */
141         size_t result_size;
142 };
143
144 static int dispatch_result(int result_shmid, callback_result_handler *handler,
145                 void *private_result_data)
146 {
147         struct osl_object result;
148         void *result_shm;
149         int ret2, ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
150         struct callback_result *cr = result_shm;
151
152         if (ret < 0) {
153                 PARA_ERROR_LOG("attach failed: %s\n", para_strerror(-ret));
154                 return ret;
155         }
156         result.size = cr->result_size;
157         result.data = result_shm + sizeof(*cr);
158         if (result.size) {
159                 assert(handler);
160                 ret = handler(&result, private_result_data);
161                 if (ret < 0)
162                         PARA_NOTICE_LOG("result handler error: %s\n",
163                                 para_strerror(-ret));
164         }
165         ret2 = shm_detach(result_shm);
166         if (ret2 < 0) {
167                 PARA_ERROR_LOG("detach failed: %s\n", para_strerror(-ret2));
168                 if (ret >= 0)
169                         ret = ret2;
170         }
171         return ret;
172 }
173
174 /**
175  * Ask the afs process to call a given function.
176  *
177  * \param f The function to be called.
178  * \param query Pointer to arbitrary data for the callback.
179  * \param result_handler Called for each shm area sent by the callback.
180  * \param private_result_data Passed verbatim to \a result_handler.
181  *
182  * This function creates a socket for communication with the afs process and a
183  * shared memory area (sma) to which the buffer pointed to by \a query is
184  * copied.  It then notifies the afs process that the callback function \a f
185  * should be executed by sending the shared memory identifier (shmid) to the
186  * socket.
187
188  * If the callback produces a result, it sends any number of shared memory
189  * identifiers back via the socket. For each such identifier received, \a
190  * result_handler is called. The contents of the sma identified by the received
191  * shmid are passed to that function as an osl object. The private_result_data
192  * pointer is passed as the second argument to \a result_handler.
193  *
194  * \return Standard.
195  *
196  * \sa send_option_arg_callback_request(), send_standard_callback_request().
197  */
198 int send_callback_request(callback_function *f, struct osl_object *query,
199                 callback_result_handler *result_handler,
200                 void *private_result_data)
201 {
202         struct callback_query *cq;
203         int ret, fd = -1, query_shmid, result_shmid;
204         void *query_shm;
205         char buf[sizeof(afs_socket_cookie) + sizeof(int)];
206         size_t query_shm_size = sizeof(*cq);
207         int dispatch_error = 0;
208
209         if (query)
210                 query_shm_size += query->size;
211         ret = shm_new(query_shm_size);
212         if (ret < 0)
213                 return ret;
214         query_shmid = ret;
215         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
216         if (ret < 0)
217                 goto out;
218         cq = query_shm;
219         cq->handler = f;
220         cq->query_size = query_shm_size - sizeof(*cq);
221
222         if (query)
223                 memcpy(query_shm + sizeof(*cq), query->data, query->size);
224         ret = shm_detach(query_shm);
225         if (ret < 0)
226                 goto out;
227
228         *(uint32_t *) buf = afs_socket_cookie;
229         *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
230
231         ret = create_remote_socket(conf.afs_socket_arg);
232         if (ret < 0)
233                 goto out;
234         fd = ret;
235         ret = send_bin_buffer(fd, buf, sizeof(buf));
236         if (ret < 0)
237                 goto out;
238         /*
239          * Read all shmids from afs.
240          *
241          * Even if the dispatcher returns an error we _must_ continue to read
242          * shmids from fd so that we can destroy all shared memory areas that
243          * have been created for us by the afs process.
244          */
245         for (;;) {
246                 ret = recv_bin_buffer(fd, buf, sizeof(int));
247                 if (ret <= 0)
248                         goto out;
249                 assert(ret == sizeof(int));
250                 ret = *(int *) buf;
251                 assert(ret > 0);
252                 result_shmid = ret;
253                 if (!dispatch_error) {
254                         ret = dispatch_result(result_shmid, result_handler,
255                                 private_result_data);
256                         if (ret < 0)
257                                 dispatch_error = 1;
258                 }
259                 ret = shm_destroy(result_shmid);
260                 if (ret < 0)
261                         PARA_CRIT_LOG("destroy result failed: %s\n",
262                                 para_strerror(-ret));
263         }
264 out:
265         if (shm_destroy(query_shmid) < 0)
266                 PARA_CRIT_LOG("shm destroy error\n");
267         if (fd >= 0)
268                 close(fd);
269 //      PARA_DEBUG_LOG("callback_ret: %d\n", ret);
270         return ret;
271 }
272
273 /**
274  * Send a callback request passing an options structure and an argument vector.
275  *
276  * \param options pointer to an arbitrary data structure.
277  * \param argc Argument count.
278  * \param argv Standard argument vector.
279  * \param f The callback function.
280  * \param result_handler See \ref send_callback_request.
281  * \param private_result_data See \ref send_callback_request.
282  *
283  * Some commands have a couple of options that are parsed in child context for
284  * syntactic correctness and are stored in a special options structure for that
285  * command. This function allows to pass such a structure together with a list
286  * of further arguments (often a list of audio files) to the parent process.
287  *
288  * \sa send_standard_callback_request(), send_callback_request().
289  */
290 int send_option_arg_callback_request(struct osl_object *options,
291                 int argc,  char * const * const argv, callback_function *f,
292                 callback_result_handler *result_handler,
293                 void *private_result_data)
294 {
295         char *p;
296         int i, ret;
297         struct osl_object query = {.size = options? options->size : 0};
298
299         for (i = 0; i < argc; i++)
300                 query.size += strlen(argv[i]) + 1;
301         query.data = para_malloc(query.size);
302         p = query.data;
303         if (options) {
304                 memcpy(query.data, options->data, options->size);
305                 p += options->size;
306         }
307         for (i = 0; i < argc; i++) {
308                 strcpy(p, argv[i]); /* OK */
309                 p += strlen(argv[i]) + 1;
310         }
311         ret = send_callback_request(f, &query, result_handler,
312                 private_result_data);
313         free(query.data);
314         return ret;
315 }
316
317 /**
318  * Send a callback request with an argument vector only.
319  *
320  * \param argc The same meaning as in send_option_arg_callback_request().
321  * \param argv The same meaning as in send_option_arg_callback_request().
322  * \param f The same meaning as in send_option_arg_callback_request().
323  * \param result_handler See \ref send_callback_request.
324  * \param private_result_data See \ref send_callback_request.
325  *
326  * This is similar to send_option_arg_callback_request(), but no options buffer
327  * is passed to the parent process.
328  *
329  * \return The return value of the underlying call to
330  * send_option_arg_callback_request().
331  */
332 int send_standard_callback_request(int argc,  char * const * const argv,
333                 callback_function *f, callback_result_handler *result_handler,
334                 void *private_result_data)
335 {
336         return send_option_arg_callback_request(NULL, argc, argv, f, result_handler,
337                 private_result_data);
338 }
339
340 static int action_if_pattern_matches(struct osl_row *row, void *data)
341 {
342         struct pattern_match_data *pmd = data;
343         struct osl_object name_obj;
344         const char *p, *name;
345         int ret = osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj);
346         const char *pattern_txt = (const char *)pmd->patterns.data;
347
348         if (ret < 0)
349                 return ret;
350         name = (char *)name_obj.data;
351         if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
352                 return 1;
353         if (!pmd->patterns.size && (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING))
354                 return pmd->action(pmd->table, row, name, pmd->data);
355         for (p = pattern_txt; p < pattern_txt + pmd->patterns.size;
356                         p += strlen(p) + 1) {
357                 ret = fnmatch(p, name, pmd->fnmatch_flags);
358                 if (ret == FNM_NOMATCH)
359                         continue;
360                 if (ret)
361                         return -E_FNMATCH;
362                 return pmd->action(pmd->table, row, name, pmd->data);
363         }
364         return 1;
365 }
366
367 /**
368  * Execute the given function for each matching row.
369  *
370  * \param pmd Describes what to match and how.
371  *
372  * \return The return value of the underlying call to osl_rbtree_loop()
373  * or osl_rbtree_loop_reverse().
374  */
375 int for_each_matching_row(struct pattern_match_data *pmd)
376 {
377         if (pmd->pm_flags & PM_REVERSE_LOOP)
378                 return osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
379                         action_if_pattern_matches);
380         return osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
381                         action_if_pattern_matches);
382 }
383
384 /**
385  * Compare two osl objects of string type.
386  *
387  * \param obj1 Pointer to the first object.
388  * \param obj2 Pointer to the second object.
389  *
390  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
391  * are taken into account.
392  *
393  * \return It returns an integer less than, equal to, or greater than zero if
394  * \a obj1 is found, respectively, to be less than, to match, or be greater than
395  * obj2.
396  *
397  * \sa strcmp(3), strncmp(3), osl_compare_func.
398  */
399 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
400 {
401         const char *str1 = (const char *)obj1->data;
402         const char *str2 = (const char *)obj2->data;
403         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
404 }
405
406 /*
407  * write input from fd to dynamically allocated buffer,
408  * but maximal max_size byte.
409  */
410 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
411 {
412         const size_t chunk_size = 1024;
413         size_t size = 2048, received = 0;
414         int ret;
415         char *buf = para_malloc(size);
416
417         for (;;) {
418                 ret = recv_bin_buffer(fd, buf + received, chunk_size);
419                 if (ret <= 0)
420                         break;
421                 received += ret;
422                 if (received + chunk_size >= size) {
423                         size *= 2;
424                         ret = -E_INPUT_TOO_LARGE;
425                         if (size > max_size)
426                                 break;
427                         buf = para_realloc(buf, size);
428                 }
429         }
430         obj->data = buf;
431         obj->size = received;
432         if (ret < 0)
433                 free(buf);
434         return ret;
435 }
436
437 /**
438  * Read data from a file descriptor, and send it to the afs process.
439  *
440  * \param fd File descriptor to read data from.
441  * \param arg_obj Pointer to the arguments to \a f.
442  * \param f The callback function.
443  * \param max_len Don't read more than that many bytes from stdin.
444  * \param result_handler See \ref send_callback_request.
445  * \param private_result_data See \ref send_callback_request.
446  *
447  * This function is used by commands that wish to let para_server store
448  * arbitrary data specified by the user (for instance the add_blob family of
449  * commands). First, at most \a max_len bytes are read from \a fd, the result
450  * is concatenated with the buffer given by \a arg_obj, and the combined buffer
451  * is made available to the afs process via the callback method. See \ref
452  * send_callback_request for details.
453  *
454  * \return Negative on errors, the return value of the underlying call to
455  * send_callback_request() otherwise.
456  */
457 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
458                 unsigned max_len, callback_result_handler *result_handler,
459                 void *private_result_data)
460 {
461         struct osl_object query, stdin_obj;
462         int ret;
463
464         ret = send_buffer(fd, AWAITING_DATA_MSG);
465         if (ret < 0)
466                 return ret;
467         ret = fd2buf(fd, max_len, &stdin_obj);
468         if (ret < 0)
469                 return ret;
470         query.size = arg_obj->size + stdin_obj.size;
471         query.data = para_malloc(query.size);
472         memcpy(query.data, arg_obj->data, arg_obj->size);
473         memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
474         free(stdin_obj.data);
475         ret = send_callback_request(f, &query, result_handler, private_result_data);
476         free(query.data);
477         return ret;
478 }
479
480 static int pass_afd(int fd, char *buf, size_t size)
481 {
482         struct msghdr msg = {.msg_iov = NULL};
483         struct cmsghdr *cmsg;
484         char control[255];
485         int ret;
486         struct iovec iov;
487
488         iov.iov_base = buf;
489         iov.iov_len  = size;
490
491         msg.msg_iov = &iov;
492         msg.msg_iovlen = 1;
493
494         msg.msg_control = control;
495         msg.msg_controllen = sizeof(control);
496
497         cmsg = CMSG_FIRSTHDR(&msg);
498         cmsg->cmsg_level = SOL_SOCKET;
499         cmsg->cmsg_type = SCM_RIGHTS;
500         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
501         *(int *)CMSG_DATA(cmsg) = fd;
502
503         /* Sum of the length of all control messages in the buffer */
504         msg.msg_controllen = cmsg->cmsg_len;
505         PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
506         ret = sendmsg(server_socket, &msg, 0);
507         if (ret < 0) {
508                 ret = -ERRNO_TO_PARA_ERROR(errno);
509                 return ret;
510         }
511         return 1;
512 }
513
514 /**
515  * Open the audio file with highest score.
516  *
517  * This stores all information for streaming the "best" audio file in a shared
518  * memory area. The id of that area and an open file descriptor for the next
519  * audio file are passed to the server process.
520  *
521  * \return Standard.
522  *
523  * \sa open_and_update_audio_file().
524  */
525 static int open_next_audio_file(void)
526 {
527         struct osl_row *aft_row;
528         struct audio_file_data afd;
529         int ret, shmid;
530         char buf[8];
531         long score;
532 again:
533         PARA_NOTICE_LOG("getting next audio file\n");
534         ret = score_get_best(&aft_row, &score);
535         if (ret < 0) {
536                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
537                 goto no_admissible_files;
538         }
539         ret = open_and_update_audio_file(aft_row, score, &afd);
540         if (ret < 0) {
541                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
542                 ret = score_delete(aft_row);
543                 if (ret < 0) {
544                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
545                         goto no_admissible_files;
546                 }
547                 goto again;
548         }
549         shmid = ret;
550         if (!write_ok(server_socket)) {
551                 ret = -E_AFS_SOCKET;
552                 goto destroy;
553         }
554         *(uint32_t *)buf = NEXT_AUDIO_FILE;
555         *(uint32_t *)(buf + 4) = (uint32_t)shmid;
556         ret = pass_afd(afd.fd, buf, 8);
557         close(afd.fd);
558         if (ret >= 0)
559                 return ret;
560 destroy:
561         shm_destroy(shmid);
562         return ret;
563 no_admissible_files:
564         *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
565         *(uint32_t *)(buf + 4) = (uint32_t)0;
566         return send_bin_buffer(server_socket, buf, 8);
567 }
568
569 /* Never fails if arg == NULL */
570 static int activate_mood_or_playlist(char *arg, int *num_admissible)
571 {
572         enum play_mode mode;
573         int ret;
574
575         if (!arg) {
576                 ret = change_current_mood(NULL); /* always successful */
577                 mode = PLAY_MODE_MOOD;
578         } else {
579                 if (!strncmp(arg, "p/", 2)) {
580                         ret = playlist_open(arg + 2);
581                         mode = PLAY_MODE_PLAYLIST;
582                 } else if (!strncmp(arg, "m/", 2)) {
583                         ret = change_current_mood(arg + 2);
584                         mode = PLAY_MODE_MOOD;
585                 } else
586                         return -E_AFS_SYNTAX;
587                 if (ret < 0)
588                         return ret;
589         }
590         if (num_admissible)
591                 *num_admissible = ret;
592         current_play_mode = mode;
593         if (arg != current_mop) {
594                 free(current_mop);
595                 if (arg) {
596                         current_mop = para_strdup(arg);
597                         mutex_lock(mmd_mutex);
598                         strncpy(mmd->afs_mode_string, arg,
599                                 sizeof(mmd->afs_mode_string));
600                         mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
601                         mutex_unlock(mmd_mutex);
602                 } else {
603                         mutex_lock(mmd_mutex);
604                         strcpy(mmd->afs_mode_string, "dummy");
605                         mutex_unlock(mmd_mutex);
606                         current_mop = NULL;
607                 }
608         }
609         return 1;
610 }
611
612 static void com_select_callback(int fd, const struct osl_object *query)
613 {
614         struct para_buffer pb = {
615                 .max_size = SHMMAX,
616                 .private_data = &fd,
617                 .max_size_handler = pass_buffer_as_shm
618         };
619         char *arg = query->data;
620         int num_admissible, ret, ret2;
621
622         ret = clear_score_table();
623         if (ret < 0) {
624                 ret2 = para_printf(&pb, "%s\n", para_strerror(-ret));
625                 goto out;
626         }
627         if (current_play_mode == PLAY_MODE_MOOD)
628                 close_current_mood();
629         else
630                 playlist_close();
631         ret = activate_mood_or_playlist(arg, &num_admissible);
632         if (ret < 0) {
633                 ret2 = para_printf(&pb, "%s\nswitching back to %s\n",
634                         para_strerror(-ret), current_mop?
635                         current_mop : "dummy");
636                 ret = activate_mood_or_playlist(current_mop, &num_admissible);
637                 if (ret < 0) {
638                         if (ret2 >= 0)
639                                 ret2 = para_printf(&pb, "failed, switching to dummy\n");
640                         activate_mood_or_playlist(NULL, &num_admissible);
641                 }
642         } else
643                 ret2 = para_printf(&pb, "activated %s (%d admissible files)\n", current_mop?
644                         current_mop : "dummy mood", num_admissible);
645 out:
646         if (ret2 >= 0 && pb.offset)
647                 pass_buffer_as_shm(pb.buf, pb.offset, &fd);
648         free(pb.buf);
649 }
650
651 /**
652  * Result handler for sending data to the para_client process.
653  *
654  * \param result The data to be sent.
655  * \param fd_ptr Pointer to the file descriptor.
656  *
657  * \return The return value of the underlying call to send_bin_buffer().
658  *
659  * \sa \ref callback_result_handler.
660  */
661 int send_result(struct osl_object *result, void *fd_ptr)
662 {
663         int fd = *(int *)fd_ptr;
664         if (!result->size)
665                 return 1;
666         return send_bin_buffer(fd, result->data, result->size);
667 }
668
669 int com_select(int fd, int argc, char * const * const argv)
670 {
671         struct osl_object query;
672
673         if (argc != 2)
674                 return -E_AFS_SYNTAX;
675         query.data = argv[1];
676         query.size = strlen(argv[1]) + 1;
677         return send_callback_request(com_select_callback, &query,
678                 &send_result, &fd);
679 }
680
681 static void init_admissible_files(char *arg)
682 {
683         if (activate_mood_or_playlist(arg, NULL) < 0)
684                 activate_mood_or_playlist(NULL, NULL); /* always successful */
685 }
686
687 static int setup_command_socket_or_die(void)
688 {
689         int ret, socket_fd;
690         char *socket_name = conf.afs_socket_arg;
691         struct sockaddr_un unix_addr;
692
693         unlink(socket_name);
694         ret = create_local_socket(socket_name, &unix_addr,
695                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
696         if (ret < 0) {
697                 PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret), socket_name);
698                 exit(EXIT_FAILURE);
699         }
700         socket_fd = ret;
701         if (listen(socket_fd , 5) < 0) {
702                 PARA_EMERG_LOG("can not listen on socket\n");
703                 exit(EXIT_FAILURE);
704         }
705         ret = mark_fd_nonblocking(socket_fd);
706         if (ret < 0) {
707                 close(socket_fd);
708                 return ret;
709         }
710         PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
711                 socket_fd);
712         return socket_fd;
713 }
714
715 static void close_afs_tables(void)
716 {
717         int i;
718         PARA_NOTICE_LOG("closing afs_tables\n");
719         for (i = 0; i < NUM_AFS_TABLES; i++)
720                 afs_tables[i].close();
721 }
722
723 static char *database_dir;
724
725 static void get_database_dir(void)
726 {
727         if (!database_dir) {
728                 if (conf.afs_database_dir_given)
729                         database_dir = para_strdup(conf.afs_database_dir_arg);
730                 else {
731                         char *home = para_homedir();
732                         database_dir = make_message(
733                                 "%s/.paraslash/afs_database", home);
734                         free(home);
735                 }
736         }
737         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
738 }
739
740 static int make_database_dir(void)
741 {
742         int ret;
743
744         get_database_dir();
745         ret = para_mkdir(database_dir, 0777);
746         if (ret >= 0 || is_errno(-ret, EEXIST))
747                 return 1;
748         return ret;
749 }
750
751 static int open_afs_tables(void)
752 {
753         int i, ret;
754
755         get_database_dir();
756         PARA_NOTICE_LOG("opening %u osl tables in %s\n", NUM_AFS_TABLES,
757                 database_dir);
758         for (i = 0; i < NUM_AFS_TABLES; i++) {
759                 ret = afs_tables[i].open(database_dir);
760                 if (ret >= 0)
761                         continue;
762                 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
763                         para_strerror(-ret));
764                 break;
765         }
766         if (ret >= 0)
767                 return ret;
768         while (i)
769                 afs_tables[--i].close();
770         return ret;
771 }
772
773 static void signal_pre_select(struct sched *s, struct task *t)
774 {
775         struct signal_task *st = container_of(t, struct signal_task, task);
776         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
777 }
778
779 static void signal_post_select(struct sched *s, struct task *t)
780 {
781         struct signal_task *st = container_of(t, struct signal_task, task);
782         if (getppid() == 1) {
783                 PARA_EMERG_LOG("para_server died\n");
784                 goto shutdown;
785         }
786         if (!FD_ISSET(st->fd, &s->rfds))
787                 return;
788         st->signum = para_next_signal();
789         if (st->signum == SIGHUP) {
790                 close_afs_tables();
791                 parse_config_or_die(1);
792                 t->error = open_afs_tables();
793                 if (t->error < 0)
794                         return;
795                 init_admissible_files(current_mop);
796                 return;
797         }
798         PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
799 shutdown:
800         sched_shutdown();
801         t->error = -E_AFS_SIGNAL;
802 }
803
804 static void register_signal_task(void)
805 {
806         struct signal_task *st = &signal_task_struct;
807
808         para_sigaction(SIGPIPE, SIG_IGN);
809         st->fd = para_signal_init();
810         PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
811         para_install_sighandler(SIGINT);
812         para_install_sighandler(SIGTERM);
813         para_install_sighandler(SIGHUP);
814
815         st->task.pre_select = signal_pre_select;
816         st->task.post_select = signal_post_select;
817         sprintf(st->task.status, "signal task");
818         register_task(&st->task);
819 }
820
821 static struct list_head afs_client_list;
822
823 /** Describes on connected afs client. */
824 struct afs_client {
825         /** Position in the afs client list. */
826         struct list_head node;
827         /** The socket file descriptor for this client. */
828         int fd;
829         /** The time the client connected. */
830         struct timeval connect_time;
831 };
832
833 static void command_pre_select(struct sched *s, struct task *t)
834 {
835         struct command_task *ct = container_of(t, struct command_task, task);
836         struct afs_client *client;
837
838         para_fd_set(server_socket, &s->rfds, &s->max_fileno);
839         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
840         list_for_each_entry(client, &afs_client_list, node)
841                 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
842 }
843
844 /**
845  * Send data as shared memory to a file descriptor.
846  *
847  * \param buf The buffer holding the data to be sent.
848  * \param size The size of \a buf.
849  * \param fd_ptr A pointer to the file descriptor.
850  *
851  * This function is used as the \a max_size handler in a \ref para_buffer
852  * structure. If used this way, it is called by \ref para_printf() whenever
853  * the buffer passed to para_printf() is about to exceed its maximal size.
854  *
855  * This function creates a shared memory area large enough to hold
856  * the content given by \a buf and \a size and sends the identifier
857  * of this area to the file descriptor given by \a fd_ptr.
858  *
859  * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
860  * and positive on success.
861  */
862 int pass_buffer_as_shm(char *buf, size_t size, void *fd_ptr)
863 {
864         int ret, shmid, fd = *(int *)fd_ptr;
865         void *shm;
866         struct callback_result *cr;
867
868         if (!buf || !size)
869                 return 0;
870         ret = shm_new(size + sizeof(struct callback_result));
871         if (ret < 0)
872                 return ret;
873         shmid = ret;
874         ret = shm_attach(shmid, ATTACH_RW, &shm);
875         if (ret < 0)
876                 goto err;
877         cr = shm;
878         cr->result_size = size;
879         memcpy(shm + sizeof(*cr), buf, size);
880         ret = shm_detach(shm);
881         if (ret < 0)
882                 goto err;
883         ret = send_bin_buffer(fd, (char *)&shmid, sizeof(int));
884         if (ret >= 0)
885                 return ret;
886 err:
887         if (shm_destroy(shmid) < 0)
888                 PARA_ERROR_LOG("destroy result failed\n");
889         return ret;
890 }
891
892 /*
893  * On errors, negative value is written to fd.
894  * On success: If query produced a result, the result_shmid is written to fd.
895  * Otherwise, zero is written.
896  */
897 static int call_callback(int fd, int query_shmid)
898 {
899         void *query_shm;
900         struct callback_query *cq;
901         struct osl_object query;
902         int ret;
903
904         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
905         if (ret < 0)
906                 return ret;
907         cq = query_shm;
908         query.data = (char *)query_shm + sizeof(*cq);
909         query.size = cq->query_size;
910         cq->handler(fd, &query);
911         return shm_detach(query_shm);
912 }
913
914 static int execute_server_command(void)
915 {
916         char buf[8];
917         int ret = recv_bin_buffer(server_socket, buf, sizeof(buf) - 1);
918
919         if (ret <= 0) {
920                 if (!ret)
921                         ret = -ERRNO_TO_PARA_ERROR(ECONNRESET);
922                 goto err;
923         }
924         buf[ret] = '\0';
925         PARA_DEBUG_LOG("received: %s\n", buf);
926         ret = -E_BAD_CMD;
927         if (strcmp(buf, "new"))
928                 goto err;
929         ret = open_next_audio_file();
930 err:
931         return ret;
932 }
933
934 static void execute_afs_command(int fd, uint32_t expected_cookie)
935 {
936         uint32_t cookie;
937         int query_shmid;
938         char buf[sizeof(cookie) + sizeof(query_shmid)];
939         int ret = recv_bin_buffer(fd, buf, sizeof(buf));
940
941         if (ret < 0)
942                 goto err;
943         if (ret != sizeof(buf)) {
944                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
945                         ret, (long unsigned) sizeof(buf));
946                 return;
947         }
948         cookie = *(uint32_t *)buf;
949         if (cookie != expected_cookie) {
950                 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
951                         (unsigned)cookie, (unsigned)expected_cookie);
952                 return;
953         }
954         query_shmid = *(int *)(buf + sizeof(cookie));
955         if (query_shmid < 0) {
956                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
957                         query_shmid);
958                 return;
959         }
960         ret = call_callback(fd, query_shmid);
961         if (ret >= 0)
962                 return;
963 err:
964         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
965 }
966
967 /** Shutdown connection if query has not arrived until this many seconds. */
968 #define AFS_CLIENT_TIMEOUT 3
969
970 static void command_post_select(struct sched *s, struct task *t)
971 {
972         struct command_task *ct = container_of(t, struct command_task, task);
973         struct sockaddr_un unix_addr;
974         struct afs_client *client, *tmp;
975         int fd, ret;
976
977         if (FD_ISSET(server_socket, &s->rfds)) {
978                 ret = execute_server_command();
979                 if (ret < 0) {
980                         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
981                         sched_shutdown();
982                         return;
983                 }
984         }
985
986         /* Check the list of connected clients. */
987         list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
988                 if (FD_ISSET(client->fd, &s->rfds))
989                         execute_afs_command(client->fd, ct->cookie);
990                 else { /* prevent bogus connection flooding */
991                         struct timeval diff;
992                         tv_diff(now, &client->connect_time, &diff);
993                         if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
994                                 continue;
995                         PARA_WARNING_LOG("connection timeout\n");
996                 }
997                 close(client->fd);
998                 list_del(&client->node);
999                 free(client);
1000         }
1001         /* Accept connections on the local socket. */
1002         if (!FD_ISSET(ct->fd, &s->rfds))
1003                 return;
1004         ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
1005         if (ret < 0) {
1006                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1007                 return;
1008         }
1009         fd = ret;
1010         ret = mark_fd_nonblocking(fd);
1011         if (ret < 0) {
1012                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1013                 close(fd);
1014                 return;
1015         }
1016         client = para_malloc(sizeof(*client));
1017         client->fd = fd;
1018         client->connect_time = *now;
1019         para_list_add(&client->node, &afs_client_list);
1020 }
1021
1022 static void register_command_task(uint32_t cookie)
1023 {
1024         struct command_task *ct = &command_task_struct;
1025         ct->fd = setup_command_socket_or_die();
1026         ct->cookie = cookie;
1027
1028         ct->task.pre_select = command_pre_select;
1029         ct->task.post_select = command_post_select;
1030         sprintf(ct->task.status, "command task");
1031         register_task(&ct->task);
1032 }
1033
1034 /**
1035  * Initialize the audio file selector process.
1036  *
1037  * \param cookie The value used for "authentication".
1038  * \param socket_fd File descriptor used for communication with the server.
1039  */
1040 __noreturn void afs_init(uint32_t cookie, int socket_fd)
1041 {
1042         static struct sched s;
1043         int i, ret;
1044
1045         register_signal_task();
1046         INIT_LIST_HEAD(&afs_client_list);
1047         for (i = 0; i < NUM_AFS_TABLES; i++)
1048                 afs_tables[i].init(&afs_tables[i]);
1049         ret = open_afs_tables();
1050         if (ret < 0)
1051                 goto out;
1052         server_socket = socket_fd;
1053         ret = mark_fd_nonblocking(server_socket);
1054         if (ret < 0)
1055                 goto out_close;
1056         PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
1057                 server_socket, (unsigned) cookie);
1058         init_admissible_files(conf.afs_initial_mode_arg);
1059         register_command_task(cookie);
1060         s.default_timeout.tv_sec = 0;
1061         s.default_timeout.tv_usec = 999 * 1000;
1062         ret = schedule(&s);
1063 out_close:
1064         close_afs_tables();
1065 out:
1066         if (ret < 0)
1067                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1068         exit(EXIT_FAILURE);
1069 }
1070
1071 static void create_tables_callback(int fd, const struct osl_object *query)
1072 {
1073         uint32_t table_mask = *(uint32_t *)query->data;
1074         int i, ret;
1075         char *buf;
1076
1077         close_afs_tables();
1078         for (i = 0; i < NUM_AFS_TABLES; i++) {
1079                 struct afs_table *t = &afs_tables[i];
1080
1081                 if (!(table_mask & (1 << i)))
1082                         continue;
1083                 if (!t->create)
1084                         continue;
1085                 ret = t->create(database_dir);
1086                 if (ret < 0)
1087                         goto out;
1088         }
1089         ret = open_afs_tables();
1090 out:
1091         if (ret >= 0)
1092                 buf = make_message("successfully created afs table(s)\n");
1093         else
1094                 buf = make_message("%s\n", para_strerror(-ret));
1095         pass_buffer_as_shm(buf, strlen(buf), &fd);
1096         free(buf);
1097 }
1098
1099 int com_init(int fd, int argc, char * const * const argv)
1100 {
1101         int i, j, ret;
1102         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1103         struct osl_object query = {.data = &table_mask,
1104                 .size = sizeof(table_mask)};
1105
1106         ret = make_database_dir();
1107         if (ret < 0)
1108                 return ret;
1109         if (argc != 1) {
1110                 table_mask = 0;
1111                 for (i = 1; i < argc; i++) {
1112                         for (j = 0; j < NUM_AFS_TABLES; j++) {
1113                                 struct afs_table *t = &afs_tables[j];
1114
1115                                 if (strcmp(argv[i], t->name))
1116                                         continue;
1117                                 table_mask |= (1 << j);
1118                                 break;
1119                         }
1120                         if (j == NUM_AFS_TABLES)
1121                                 return -E_BAD_TABLE_NAME;
1122                 }
1123         }
1124         ret = send_callback_request(create_tables_callback, &query, &send_result, &fd);
1125         if (ret < 0)
1126                 return send_va_buffer(fd, "%s\n", para_strerror(-ret));
1127         return ret;
1128 }
1129
1130 /**
1131  * Flags for the check command.
1132  *
1133  * \sa com_check().
1134  */
1135 enum com_check_flags {
1136         /** Check the audio file table. */
1137         CHECK_AFT = 1,
1138         /** Check the mood table. */
1139         CHECK_MOODS = 2,
1140         /** Check the playlist table. */
1141         CHECK_PLAYLISTS = 4
1142 };
1143
1144 int com_check(int fd, int argc, char * const * const argv)
1145 {
1146         unsigned flags = 0;
1147         int i, ret;
1148
1149         for (i = 1; i < argc; i++) {
1150                 const char *arg = argv[i];
1151                 if (arg[0] != '-')
1152                         break;
1153                 if (!strcmp(arg, "--")) {
1154                         i++;
1155                         break;
1156                 }
1157                 if (!strcmp(arg, "-a")) {
1158                         flags |= CHECK_AFT;
1159                         continue;
1160                 }
1161                 if (!strcmp(arg, "-p")) {
1162                         flags |= CHECK_PLAYLISTS;
1163                         continue;
1164                 }
1165                 if (!strcmp(arg, "-m")) {
1166                         flags |= CHECK_MOODS;
1167                         continue;
1168                 }
1169                 return -E_AFS_SYNTAX;
1170         }
1171         if (i < argc)
1172                 return -E_AFS_SYNTAX;
1173         if (!flags)
1174                 flags = ~0U;
1175         if (flags & CHECK_AFT) {
1176                 ret = send_callback_request(aft_check_callback, NULL, send_result, &fd);
1177                 if (ret < 0)
1178                         return ret;
1179         }
1180         if (flags & CHECK_PLAYLISTS) {
1181                 ret = send_callback_request(playlist_check_callback, NULL, send_result, &fd);
1182                 if (ret < 0)
1183                         return ret;
1184         }
1185         if (flags & CHECK_MOODS) {
1186                 ret = send_callback_request(mood_check_callback, NULL, send_result, &fd);
1187                 if (ret < 0)
1188                         return ret;
1189         }
1190         return 1;
1191 }
1192
1193 /**
1194  * The afs event dispatcher.
1195  *
1196  * \param event Type of the event.
1197  * \param pb May be \p NULL.
1198  * \param data Type depends on \a event.
1199  *
1200  * This function calls the table handlers of all tables and passes \a pb and \a
1201  * data verbatim. It's up to the handlers to interpret the \a data pointer.
1202  */
1203 void afs_event(enum afs_events event, struct para_buffer *pb,
1204                 void *data)
1205 {
1206         int i, ret;
1207
1208         for (i = 0; i < NUM_AFS_TABLES; i++) {
1209                 struct afs_table *t = &afs_tables[i];
1210                 if (!t->event_handler)
1211                         continue;
1212                 ret = t->event_handler(event, pb, data);
1213                 if (ret < 0)
1214                         PARA_CRIT_LOG("table %s, event %d: %s\n", t->name,
1215                                 event, para_strerror(-ret));
1216         }
1217 }
1218
1219 int images_event_handler(__a_unused enum afs_events event,
1220         __a_unused  struct para_buffer *pb, __a_unused void *data)
1221 {
1222         return 1;
1223 }
1224
1225 int lyrics_event_handler(__a_unused enum afs_events event,
1226         __a_unused struct para_buffer *pb, __a_unused void *data)
1227 {
1228         return 1;
1229 }