]> git.tuebingen.mpg.de Git - paraslash.git/blob - afs.c
paraslash 0.7.3
[paraslash.git] / afs.c
1 /* Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file afs.c Paraslash's audio file selector. */
4
5 #include <netinet/in.h>
6 #include <sys/socket.h>
7 #include <regex.h>
8 #include <signal.h>
9 #include <fnmatch.h>
10 #include <osl.h>
11 #include <lopsub.h>
12 #include <arpa/inet.h>
13 #include <sys/un.h>
14 #include <netdb.h>
15 #include <lopsub.h>
16
17 #include "server.lsg.h"
18 #include "server_cmd.lsg.h"
19 #include "para.h"
20 #include "error.h"
21 #include "crypt.h"
22 #include "string.h"
23 #include "afh.h"
24 #include "afs.h"
25 #include "net.h"
26 #include "server.h"
27 #include "daemon.h"
28 #include "ipc.h"
29 #include "list.h"
30 #include "sched.h"
31 #include "fd.h"
32 #include "signal.h"
33 #include "sideband.h"
34 #include "command.h"
35
36 /**
37  * The array of tables of the audio file selector.
38  *
39  * We organize them in an array to be able to loop over all tables.
40  */
41 static const struct afs_table {
42         /** The name is no table operation, so define it here. */
43         const char * const name;
44         /** The only way to invoke the ops is via this pointer. */
45         const struct afs_table_operations *ops;
46 } afs_tables[] = {
47         {.name = "audio_files", .ops = &aft_ops},
48         {.name = "attributes", .ops = &attr_ops},
49         {.name = "scores", .ops = &score_ops},
50         {.name = "moods", .ops = &moods_ops},
51         {.name = "lyrics", .ops = &lyrics_ops},
52         {.name = "images", .ops = &images_ops},
53         {.name = "playlists", .ops = &playlists_ops},
54 };
55 /** Used to loop over the afs tables. */
56 #define NUM_AFS_TABLES ARRAY_SIZE(afs_tables)
57
58 struct command_task {
59         /** The file descriptor for the local socket. */
60         int fd;
61         /** The associated task structure. */
62         struct task *task;
63 };
64
65 extern int mmd_mutex;
66 extern struct misc_meta_data *mmd;
67
68 static int server_socket;
69 static struct command_task command_task_struct;
70 static struct signal_task *signal_task;
71
72 static enum play_mode current_play_mode;
73 static char *current_mop; /* mode or playlist specifier. NULL means dummy mood */
74
75 extern uint32_t afs_socket_cookie;
76
77 /**
78  * Passed from command handlers to afs.
79  *
80  * Command handlers cannot change the afs database directly because they run in
81  * a separate process. The callback query structure circumvents this
82  * restriction as follows. To instruct the afs process to execute a particular
83  * function, the command hander writes an instance of this structure to a
84  * shared memory area, along with the arguments to the callback function. The
85  * identifier of the shared memory area is transferred to the afs process via
86  * the command socket.
87  *
88  * The afs process reads the shared memory id from the command socket, attaches
89  * the corresponding area, and calls the callback function whose address is
90  * stored in the area.
91  *
92  * The command output, if any, is transferred back to the command handler in
93  * the same way: The afs process writes the output to a second shared memory
94  * area together with a fixed size metadata header whose format corresponds to
95  * the \ref callback_result structure. The identifier of this area is sent back
96  * to the command handler which attaches the area and forwards the output to
97  * the remote client.
98  *
99  * \sa \ref struct callback_result.
100  */
101 struct callback_query {
102         /** The function to be called. */
103         afs_callback *cb;
104         /** The number of bytes of the query */
105         size_t query_size;
106 };
107
108 /**
109  * Structure embedded in the result of a callback.
110  *
111  * If the callback produced a result, an instance of that structure is embedded
112  * into the shared memory area holding the result, mainly to let the command
113  * handler know the size of the result.
114  *
115  * \sa \ref struct callback_query.
116  */
117 struct callback_result {
118         /** The number of bytes of the result. */
119         size_t result_size;
120         /** The band designator (loglevel for the result). */
121         uint8_t band;
122 };
123
124 static int dispatch_result(int result_shmid, callback_result_handler *handler,
125                 void *private_result_data)
126 {
127         struct osl_object result;
128         void *result_shm;
129         /* must attach r/w as result.data might get encrypted in-place. */
130         int ret2, ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
131         struct callback_result *cr = result_shm;
132
133         if (ret < 0) {
134                 PARA_ERROR_LOG("attach failed: %s\n", para_strerror(-ret));
135                 return ret;
136         }
137         result.size = cr->result_size;
138         result.data = result_shm + sizeof(*cr);
139         assert(handler);
140         ret = handler(&result, cr->band, private_result_data);
141         ret2 = shm_detach(result_shm);
142         if (ret2 < 0) {
143                 PARA_ERROR_LOG("detach failed: %s\n", para_strerror(-ret2));
144                 if (ret >= 0)
145                         ret = ret2;
146         }
147         return ret;
148 }
149
150 /**
151  * Ask the afs process to call a given function.
152  *
153  * \param f The function to be called.
154  * \param query Pointer to arbitrary data for the callback.
155  * \param result_handler Called for each shm area sent by the callback.
156  * \param private_result_data Passed verbatim to \a result_handler.
157  *
158  * This function creates a socket for communication with the afs process and a
159  * shared memory area (sma) to which the buffer pointed to by \a query is
160  * copied.  It then notifies the afs process that the callback function \a f
161  * should be executed by sending the shared memory identifier (shmid) to the
162  * socket.
163  *
164  * If the callback produces a result, it sends any number of shared memory
165  * identifiers back via the socket. For each such identifier received, \a
166  * result_handler is called. The contents of the sma identified by the received
167  * shmid are passed to that function as an osl object. The private_result_data
168  * pointer is passed as the second argument to \a result_handler.
169  *
170  * \return Number of shared memory areas dispatched on success, negative on
171  * errors.
172  */
173 int send_callback_request(afs_callback *f, struct osl_object *query,
174                 callback_result_handler *result_handler,
175                 void *private_result_data)
176 {
177         struct callback_query *cq;
178         int ret, fd = -1, query_shmid, result_shmid;
179         void *query_shm;
180         char buf[sizeof(afs_socket_cookie) + sizeof(int)];
181         size_t query_shm_size = sizeof(*cq);
182         int dispatch_error = 0, num_dispatched = 0;
183
184         if (query)
185                 query_shm_size += query->size;
186         ret = shm_new(query_shm_size);
187         if (ret < 0)
188                 return ret;
189         query_shmid = ret;
190         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
191         if (ret < 0)
192                 goto out;
193         cq = query_shm;
194         cq->cb = f;
195         cq->query_size = query_shm_size - sizeof(*cq);
196
197         if (query)
198                 memcpy(query_shm + sizeof(*cq), query->data, query->size);
199         ret = shm_detach(query_shm);
200         if (ret < 0)
201                 goto out;
202
203         *(uint32_t *)buf = afs_socket_cookie;
204         *(int *)(buf + sizeof(afs_socket_cookie)) = query_shmid;
205
206         ret = connect_local_socket(OPT_STRING_VAL(AFS_SOCKET));
207         if (ret < 0)
208                 goto out;
209         fd = ret;
210         ret = write_all(fd, buf, sizeof(buf));
211         if (ret < 0)
212                 goto out;
213         /*
214          * Read all shmids from afs.
215          *
216          * Even if the dispatcher returns an error we _must_ continue to read
217          * shmids from fd so that we can destroy all shared memory areas that
218          * have been created for us by the afs process.
219          */
220         for (;;) {
221                 ret = recv_bin_buffer(fd, buf, sizeof(int));
222                 if (ret <= 0)
223                         goto out;
224                 assert(ret == sizeof(int));
225                 ret = *(int *) buf;
226                 assert(ret > 0);
227                 result_shmid = ret;
228                 ret = dispatch_result(result_shmid, result_handler,
229                         private_result_data);
230                 if (ret < 0 && dispatch_error >= 0)
231                         dispatch_error = ret;
232                 ret = shm_destroy(result_shmid);
233                 if (ret < 0)
234                         PARA_CRIT_LOG("destroy result failed: %s\n",
235                                 para_strerror(-ret));
236                 num_dispatched++;
237         }
238 out:
239         if (shm_destroy(query_shmid) < 0)
240                 PARA_CRIT_LOG("shm destroy error\n");
241         if (fd >= 0)
242                 close(fd);
243         if (dispatch_error < 0)
244                 return dispatch_error;
245         if (ret < 0)
246                 return ret;
247         return num_dispatched;
248 }
249
250 /**
251  * Wrapper for send_callback_request() which passes a lopsub parse result.
252  *
253  * \param f The callback function.
254  * \param cmd Needed for (de-)serialization.
255  * \param lpr Must match cmd.
256  * \param private_result_data Passed to send_callback_request().
257  *
258  * This function serializes the parse result given by the lpr pointer into a
259  * buffer. The buffer is sent as the query to the afs process with the callback
260  * mechanism.
261  *
262  * \return The return value of the underlying call to send_callback_request().
263  */
264 int send_lls_callback_request(afs_callback *f,
265                 const struct lls_command * const cmd,
266                 struct lls_parse_result *lpr, void *private_result_data)
267 {
268         struct osl_object query;
269         char *buf = NULL;
270         int ret = lls_serialize_parse_result(lpr, cmd, &buf, &query.size);
271
272         assert(ret >= 0);
273         query.data = buf;
274         ret = send_callback_request(f, &query, afs_cb_result_handler,
275                 private_result_data);
276         free(buf);
277         return ret;
278 }
279
280 static int action_if_pattern_matches(struct osl_row *row, void *data)
281 {
282         struct pattern_match_data *pmd = data;
283         struct osl_object name_obj;
284         const char *p, *name;
285         int i, ret;
286
287         ret = osl(osl_get_object(pmd->table, row, pmd->match_col_num,
288                 &name_obj));
289         if (ret < 0)
290                 return ret;
291         name = (char *)name_obj.data;
292         if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
293                 return 1;
294         if (lls_num_inputs(pmd->lpr) == 0) {
295                 if (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING) {
296                         pmd->num_matches++;
297                         return pmd->action(pmd->table, row, name, pmd->data);
298                 }
299         }
300         i = pmd->input_skip;
301         for (;;) {
302                 if (i >= lls_num_inputs(pmd->lpr))
303                         break;
304                 p = lls_input(i, pmd->lpr);
305                 ret = fnmatch(p, name, pmd->fnmatch_flags);
306                 if (ret != FNM_NOMATCH) {
307                         if (ret != 0)
308                                 return -E_FNMATCH;
309                         ret = pmd->action(pmd->table, row, name, pmd->data);
310                         if (ret >= 0)
311                                 pmd->num_matches++;
312                         return ret;
313
314                 }
315                 i++;
316         }
317         return 1;
318 }
319
320 /**
321  * Execute the given function for each matching row.
322  *
323  * \param pmd Describes what to match and how.
324  *
325  * \return Standard.
326  */
327 int for_each_matching_row(struct pattern_match_data *pmd)
328 {
329         if (pmd->pm_flags & PM_REVERSE_LOOP)
330                 return osl(osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
331                         action_if_pattern_matches));
332         return osl(osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
333                         action_if_pattern_matches));
334 }
335
336 /**
337  * Compare two osl objects of string type.
338  *
339  * \param obj1 Pointer to the first object.
340  * \param obj2 Pointer to the second object.
341  *
342  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
343  * are taken into account.
344  *
345  * \return It returns an integer less than, equal to, or greater than zero if
346  * \a obj1 is found, respectively, to be less than, to match, or be greater than
347  * obj2.
348  *
349  * \sa strcmp(3), strncmp(3).
350  */
351 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
352 {
353         const char *str1 = obj1->data;
354         const char *str2 = obj2->data;
355         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
356 }
357
358 static int pass_afd(int fd, char *buf, size_t size)
359 {
360         struct msghdr msg = {.msg_iov = NULL};
361         struct cmsghdr *cmsg;
362         char control[255] __a_aligned(8);
363         int ret;
364         struct iovec iov;
365
366         iov.iov_base = buf;
367         iov.iov_len  = size;
368
369         msg.msg_iov = &iov;
370         msg.msg_iovlen = 1;
371
372         msg.msg_control = control;
373         msg.msg_controllen = sizeof(control);
374
375         cmsg = CMSG_FIRSTHDR(&msg);
376         cmsg->cmsg_level = SOL_SOCKET;
377         cmsg->cmsg_type = SCM_RIGHTS;
378         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
379         *(int *)CMSG_DATA(cmsg) = fd;
380
381         /* Sum of the length of all control messages in the buffer */
382         msg.msg_controllen = cmsg->cmsg_len;
383         PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
384         ret = sendmsg(server_socket, &msg, 0);
385         if (ret < 0) {
386                 ret = -ERRNO_TO_PARA_ERROR(errno);
387                 return ret;
388         }
389         return 1;
390 }
391
392 /**
393  * Pass the fd of the next audio file to the server process.
394  *
395  * This stores all information for streaming the "best" audio file in a shared
396  * memory area. The id of that area and an open file descriptor for the next
397  * audio file are passed to the server process.
398  *
399  * \return Standard.
400  *
401  * \sa \ref open_and_update_audio_file().
402  */
403 static int open_next_audio_file(void)
404 {
405         int ret, shmid, fd;
406         char buf[8];
407
408         ret = open_and_update_audio_file(&fd);
409         if (ret < 0) {
410                 if (ret != -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
411                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
412                 goto no_admissible_files;
413         }
414         shmid = ret;
415         if (!write_ok(server_socket)) {
416                 ret = -E_AFS_SOCKET;
417                 goto destroy;
418         }
419         *(uint32_t *)buf = NEXT_AUDIO_FILE;
420         *(uint32_t *)(buf + 4) = (uint32_t)shmid;
421         ret = pass_afd(fd, buf, 8);
422         close(fd);
423         if (ret >= 0)
424                 return ret;
425 destroy:
426         shm_destroy(shmid);
427         return ret;
428 no_admissible_files:
429         *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
430         *(uint32_t *)(buf + 4) = (uint32_t)0;
431         return write_all(server_socket, buf, 8);
432 }
433
434 static int activate_mood_or_playlist(const char *arg, struct para_buffer *pb)
435 {
436         enum play_mode mode;
437         int ret;
438         char *msg;
439
440         if (!arg) { /* load dummy mood */
441                 ret = mood_load(NULL, NULL, &msg);
442                 mode = PLAY_MODE_MOOD;
443         } else if (!strncmp(arg, "p/", 2)) {
444                 ret = playlist_load(arg + 2, NULL, &msg);
445                 mode = PLAY_MODE_PLAYLIST;
446         } else if (!strncmp(arg, "m/", 2)) {
447                 ret = mood_load(arg + 2, NULL, &msg);
448                 mode = PLAY_MODE_MOOD;
449         } else {
450                 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
451                 msg = make_message("%s: parse error\n", arg);
452         }
453         if (pb)
454                 para_printf(pb, "%s", msg);
455         free(msg);
456         if (ret < 0)
457                 return ret;
458         current_play_mode = mode;
459         /*
460          * We get called with arg == current_mop from the signal dispatcher
461          * after SIGHUP and from the error path of the select command to
462          * re-select the current mood or playlist. In this case the assignment
463          * to current_mop below would result in a use-after-free condition.
464          */
465         if (arg != current_mop) {
466                 free(current_mop);
467                 current_mop = arg? para_strdup(arg) : NULL;
468         }
469         /* Notify the server about the mood/playlist change. */
470         mutex_lock(mmd_mutex);
471         strncpy(mmd->afs_mode_string, arg? arg: "dummy",
472                 sizeof(mmd->afs_mode_string));
473         mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
474         mmd->events++;
475         mutex_unlock(mmd_mutex);
476         return 1;
477 }
478
479 /**
480  * Result handler for sending data to the para_client process.
481  *
482  * \param result The data to be sent.
483  * \param band The band designator.
484  * \param private Pointer to the command context.
485  *
486  * \return The return value of the underlying call to \ref command.c::send_sb.
487  *
488  * \sa \ref callback_result_handler, \ref command.c::send_sb.
489  */
490 int afs_cb_result_handler(struct osl_object *result, uint8_t band,
491                 void *private)
492 {
493         struct command_context *cc = private;
494
495         assert(cc);
496         switch (band) {
497         case SBD_OUTPUT:
498         case SBD_DEBUG_LOG:
499         case SBD_INFO_LOG:
500         case SBD_NOTICE_LOG:
501         case SBD_WARNING_LOG:
502         case SBD_ERROR_LOG:
503         case SBD_CRIT_LOG:
504         case SBD_EMERG_LOG:
505                 assert(result->size > 0);
506                 return send_sb(&cc->scc, result->data, result->size, band, true);
507         case SBD_AFS_CB_FAILURE:
508                 return *(int *)(result->data);
509         default:
510                 return -E_BAD_BAND;
511         }
512 }
513
514 static void flush_and_free_pb(struct para_buffer *pb)
515 {
516         int ret;
517         struct afs_max_size_handler_data *amshd = pb->private_data;
518
519         if (pb->buf && pb->size > 0) {
520                 ret = pass_buffer_as_shm(amshd->fd, amshd->band, pb->buf,
521                         pb->offset);
522                 if (ret < 0)
523                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
524         }
525         free(pb->buf);
526 }
527
528 static void init_admissible_files(const char *arg)
529 {
530         int ret = activate_mood_or_playlist(arg, NULL);
531         if (ret < 0) {
532                 PARA_WARNING_LOG("could not activate %s: %s\n", arg?
533                         arg : "dummy", para_strerror(-ret));
534                 if (arg)
535                         activate_mood_or_playlist(NULL, NULL);
536         }
537 }
538
539 static int setup_command_socket_or_die(void)
540 {
541         int ret, socket_fd;
542         const char *socket_name = OPT_STRING_VAL(AFS_SOCKET);
543
544         unlink(socket_name);
545         ret = create_local_socket(socket_name);
546         if (ret < 0) {
547                 PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret), socket_name);
548                 exit(EXIT_FAILURE);
549         }
550         socket_fd = ret;
551         PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
552                 socket_fd);
553         return socket_fd;
554 }
555
556 static char *database_dir;
557
558 static void close_afs_tables(void)
559 {
560         int i;
561         PARA_NOTICE_LOG("closing afs tables\n");
562         for (i = 0; i < NUM_AFS_TABLES; i++)
563                 afs_tables[i].ops->close();
564         free(database_dir);
565         database_dir = NULL;
566 }
567
568 static void get_database_dir(void)
569 {
570         if (!database_dir) {
571                 if (OPT_GIVEN(AFS_DATABASE_DIR))
572                         database_dir = para_strdup(OPT_STRING_VAL(AFS_DATABASE_DIR));
573                 else {
574                         char *home = para_homedir();
575                         database_dir = make_message(
576                                 "%s/.paraslash/afs_database-0.7", home);
577                         free(home);
578                 }
579         }
580         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
581 }
582
583 static int open_afs_tables(void)
584 {
585         int i, ret;
586
587         get_database_dir();
588         PARA_NOTICE_LOG("opening %zu osl tables in %s\n", NUM_AFS_TABLES,
589                 database_dir);
590         for (i = 0; i < NUM_AFS_TABLES; i++) {
591                 ret = afs_tables[i].ops->open(database_dir);
592                 if (ret >= 0)
593                         continue;
594                 PARA_ERROR_LOG("could not open %s\n", afs_tables[i].name);
595                 break;
596         }
597         if (ret >= 0)
598                 return ret;
599         while (i)
600                 afs_tables[--i].ops->close();
601         return ret;
602 }
603
604 static int afs_signal_post_monitor(struct sched *s, __a_unused void *context)
605 {
606         int signum, ret;
607
608         if (getppid() == 1) {
609                 PARA_EMERG_LOG("para_server died\n");
610                 goto shutdown;
611         }
612         signum = para_next_signal();
613         if (signum == 0)
614                 return 0;
615         if (signum == SIGHUP) {
616                 close_afs_tables();
617                 parse_config_or_die(1);
618                 ret = open_afs_tables();
619                 if (ret < 0)
620                         return ret;
621                 init_admissible_files(current_mop);
622                 return 0;
623         }
624         PARA_EMERG_LOG("terminating on signal %d\n", signum);
625 shutdown:
626         task_notify_all(s, E_AFS_SIGNAL);
627         return -E_AFS_SIGNAL;
628 }
629
630 static void register_signal_task(struct sched *s)
631 {
632         para_sigaction(SIGPIPE, SIG_IGN);
633         signal_task = signal_init_or_die();
634         para_install_sighandler(SIGINT);
635         para_install_sighandler(SIGTERM);
636         para_install_sighandler(SIGHUP);
637
638         signal_task->task = task_register(&(struct task_info) {
639                 .name = "signal",
640                 .pre_monitor = signal_pre_monitor,
641                 .post_monitor = afs_signal_post_monitor,
642                 .context = signal_task,
643
644         }, s);
645 }
646
647 static struct list_head afs_client_list;
648
649 /** Describes one connected afs client. */
650 struct afs_client {
651         /** Position in the afs client list. */
652         struct list_head node;
653         /** The socket file descriptor for this client. */
654         int fd;
655         /** The time the client connected. */
656         struct timeval connect_time;
657 };
658
659 static void command_pre_monitor(struct sched *s, void *context)
660 {
661         struct command_task *ct = context;
662         struct afs_client *client;
663
664         sched_monitor_readfd(server_socket, s);
665         sched_monitor_readfd(ct->fd, s);
666         list_for_each_entry(client, &afs_client_list, node)
667                 sched_monitor_readfd(client->fd, s);
668 }
669
670 /**
671  * Send data as shared memory to a file descriptor.
672  *
673  * \param fd File descriptor to send the shmid to.
674  * \param band The band designator for this data.
675  * \param buf The buffer holding the data to be sent.
676  * \param size The size of \a buf.
677  *
678  * This function creates a shared memory area large enough to hold
679  * the content given by \a buf and \a size and sends the identifier
680  * of this area to the file descriptor \a fd.
681  *
682  * It is called by the AFS max_size handler as well as directly by the AFS
683  * command callbacks to send command output to the command handlers.
684  *
685  * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
686  * and positive on success.
687  */
688 int pass_buffer_as_shm(int fd, uint8_t band, const char *buf, size_t size)
689 {
690         int ret, shmid;
691         void *shm;
692         struct callback_result *cr;
693
694         if (size == 0)
695                 assert(band != SBD_OUTPUT);
696         ret = shm_new(size + sizeof(*cr));
697         if (ret < 0)
698                 return ret;
699         shmid = ret;
700         ret = shm_attach(shmid, ATTACH_RW, &shm);
701         if (ret < 0)
702                 goto err;
703         cr = shm;
704         cr->result_size = size;
705         cr->band = band;
706         if (size > 0)
707                 memcpy(shm + sizeof(*cr), buf, size);
708         ret = shm_detach(shm);
709         if (ret < 0)
710                 goto err;
711         ret = write_all(fd, (char *)&shmid, sizeof(int));
712         if (ret >= 0)
713                 return ret;
714 err:
715         if (shm_destroy(shmid) < 0)
716                 PARA_ERROR_LOG("destroy result failed\n");
717         return ret;
718 }
719
720 /**
721  * Format and send an error message to the command handler.
722  *
723  * To pass an error message from the callback of an afs command to the client,
724  * this function should be called. It formats the message into a buffer which
725  * is passed as a shared memory area to the command handler from where it
726  * propagates to the client.
727  *
728  * The message will be tagged with the ERROR_LOG sideband designator so that
729  * the client writes it to its stderr stream rather than to stdout as with
730  * aca->pbout. In analogy to the default Unix semantics of stderr, the message
731  * is sent without buffering.
732  *
733  * If sending the error message fails, an error is logged on the server side,
734  * but no other action is taken.
735  *
736  * \param aca Used to obtain the fd to send the shmid to.
737  * \param fmt Usual format string.
738  */
739 __printf_2_3 void afs_error(const struct afs_callback_arg *aca,
740                 const char *fmt,...)
741 {
742         va_list argp;
743         char *msg;
744         unsigned n;
745         int ret;
746
747         va_start(argp, fmt);
748         n = xvasprintf(&msg, fmt, argp);
749         va_end(argp);
750         ret = pass_buffer_as_shm(aca->fd, SBD_ERROR_LOG, msg, n + 1);
751         if (ret < 0)
752                 PARA_ERROR_LOG("Could not send %s: %s\n", msg,
753                         para_strerror(-ret));
754         free(msg);
755 }
756
757 static int call_callback(int fd, int query_shmid)
758 {
759         void *query_shm;
760         struct callback_query *cq;
761         int ret, ret2;
762         struct afs_callback_arg aca = {.fd = fd};
763
764         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
765         if (ret < 0)
766                 return ret;
767         cq = query_shm;
768         aca.query.data = (char *)query_shm + sizeof(*cq);
769         aca.query.size = cq->query_size;
770         aca.pbout.max_size = shm_get_shmmax();
771         aca.pbout.max_size_handler = afs_max_size_handler;
772         aca.pbout.private_data = &(struct afs_max_size_handler_data) {
773                 .fd = fd,
774                 .band = SBD_OUTPUT
775         };
776         ret = cq->cb(&aca);
777         ret2 = shm_detach(query_shm);
778         if (ret2 < 0) {
779                 if (ret < 0) /* ignore (but log) detach error */
780                         PARA_ERROR_LOG("could not detach sma: %s\n",
781                                 para_strerror(-ret2));
782                 else
783                         ret = ret2;
784         }
785         flush_and_free_pb(&aca.pbout);
786         if (ret < 0) {
787                 ret2 = pass_buffer_as_shm(fd, SBD_AFS_CB_FAILURE,
788                         (const char *)&ret, sizeof(ret));
789                 if (ret2 < 0)
790                         PARA_ERROR_LOG("could not pass cb failure packet: %s\n",
791                                 para_strerror(-ret));
792         }
793         return ret;
794 }
795
796 static int execute_server_command(void)
797 {
798         char buf[8];
799         size_t n;
800         int ret = read_nonblock(server_socket, buf, sizeof(buf) - 1, &n);
801
802         if (ret < 0 || n == 0)
803                 return ret;
804         buf[n] = '\0';
805         if (strcmp(buf, "new"))
806                 return -ERRNO_TO_PARA_ERROR(EINVAL);
807         return open_next_audio_file();
808 }
809
810 /* returns 0 if no data available, 1 else */
811 static int execute_afs_command(int fd)
812 {
813         uint32_t cookie;
814         int query_shmid;
815         char buf[sizeof(cookie) + sizeof(query_shmid)];
816         size_t n;
817         int ret = read_nonblock(fd, buf, sizeof(buf), &n);
818
819         if (ret < 0)
820                 goto err;
821         if (n == 0)
822                 return 0;
823         if (n != sizeof(buf)) {
824                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
825                         ret, (long unsigned) sizeof(buf));
826                 return 1;
827         }
828         cookie = *(uint32_t *)buf;
829         if (cookie != afs_socket_cookie) {
830                 PARA_NOTICE_LOG("received invalid cookie (got %u, expected %u)\n",
831                         (unsigned)cookie, (unsigned)afs_socket_cookie);
832                 return 1;
833         }
834         query_shmid = *(int *)(buf + sizeof(cookie));
835         if (query_shmid < 0) {
836                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
837                         query_shmid);
838                 return 1;
839         }
840         ret = call_callback(fd, query_shmid);
841         if (ret >= 0)
842                 return 1;
843 err:
844         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
845         return 1;
846 }
847
848 /** Shutdown connection if query has not arrived until this many seconds. */
849 #define AFS_CLIENT_TIMEOUT 3
850
851 static int command_post_monitor(struct sched *s, void *context)
852 {
853         struct command_task *ct = context;
854         struct sockaddr_un unix_addr;
855         struct afs_client *client, *tmp;
856         int fd, ret;
857
858         ret = task_get_notification(ct->task);
859         if (ret < 0)
860                 return ret;
861         ret = execute_server_command();
862         if (ret < 0) {
863                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
864                 task_notify_all(s, -ret);
865                 return ret;
866         }
867         /* Check the list of connected clients. */
868         list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
869                 ret = execute_afs_command(client->fd);
870                 if (ret == 0) { /* prevent bogus connection flooding */
871                         struct timeval diff;
872                         tv_diff(now, &client->connect_time, &diff);
873                         if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
874                                 continue;
875                         PARA_WARNING_LOG("connection timeout\n");
876                 }
877                 close(client->fd);
878                 list_del(&client->node);
879                 free(client);
880         }
881         /* Accept connections on the local socket. */
882         ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr), &fd);
883         if (ret < 0)
884                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
885         if (ret <= 0)
886                 return 0;
887         ret = mark_fd_nonblocking(fd);
888         if (ret < 0) {
889                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
890                 close(fd);
891                 return 0;
892         }
893         client = alloc(sizeof(*client));
894         client->fd = fd;
895         client->connect_time = *now;
896         para_list_add(&client->node, &afs_client_list);
897         return 0;
898 }
899
900 static void register_command_task(struct sched *s)
901 {
902         struct command_task *ct = &command_task_struct;
903         ct->fd = setup_command_socket_or_die();
904
905         ct->task = task_register(&(struct task_info) {
906                 .name = "afs command",
907                 .pre_monitor = command_pre_monitor,
908                 .post_monitor = command_post_monitor,
909                 .context = ct,
910         }, s);
911 }
912
913 static int afs_poll(struct pollfd *fds, nfds_t nfds, int timeout)
914 {
915         mutex_lock(mmd_mutex);
916         daemon_set_loglevel(mmd->loglevel);
917         mutex_unlock(mmd_mutex);
918         return xpoll(fds, nfds, timeout);
919 }
920
921 /**
922  * Initialize the audio file selector process.
923  *
924  * \param socket_fd File descriptor used for communication with the server.
925  */
926 __noreturn void afs_init(int socket_fd)
927 {
928         static struct sched s;
929         int ret;
930
931         register_signal_task(&s);
932         init_list_head(&afs_client_list);
933         ret = open_afs_tables();
934         if (ret < 0)
935                 goto out;
936         server_socket = socket_fd;
937         ret = mark_fd_nonblocking(server_socket);
938         if (ret < 0)
939                 goto out_close;
940         PARA_INFO_LOG("server_socket: %d\n", server_socket);
941         init_admissible_files(OPT_STRING_VAL(AFS_INITIAL_MODE));
942         register_command_task(&s);
943         s.default_timeout = 1000;
944         s.poll_function = afs_poll;
945         ret = write(socket_fd, "\0", 1);
946         if (ret != 1) {
947                 if (ret == 0)
948                         errno = EINVAL;
949                 ret = -ERRNO_TO_PARA_ERROR(errno);
950                 goto out_close;
951         }
952         ret = schedule(&s);
953         sched_shutdown(&s);
954         mood_unload(NULL);
955         playlist_unload(NULL);
956 out_close:
957         close_afs_tables();
958 out:
959         signal_shutdown(signal_task);
960         free_status_items();
961         free(current_mop);
962         free_lpr();
963         if (ret < 0)
964                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
965         exit(EXIT_FAILURE);
966 }
967
968 static int com_select_callback(struct afs_callback_arg *aca)
969 {
970         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
971         const char *arg;
972         int ret;
973         struct para_buffer *pbout;
974
975         ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
976         assert(ret >= 0);
977         arg = lls_input(0, aca->lpr);
978         pbout = SERVER_CMD_OPT_GIVEN(SELECT, VERBOSE, aca->lpr)?
979                 &aca->pbout : NULL;
980         score_clear();
981         if (current_play_mode == PLAY_MODE_MOOD)
982                 mood_unload(NULL);
983         else
984                 playlist_unload(NULL);
985         ret = activate_mood_or_playlist(arg, pbout);
986         if (ret >= 0)
987                 goto free_lpr;
988         /* ignore subsequent errors (but log them) */
989         if (current_mop && strcmp(current_mop, arg) != 0) {
990                 int ret2;
991                 afs_error(aca, "switching back to %s\n", current_mop);
992                 ret2 = activate_mood_or_playlist(current_mop, pbout);
993                 if (ret2 >= 0)
994                         goto free_lpr;
995                 afs_error(aca, "could not reactivate %s: %s\n", current_mop,
996                         para_strerror(-ret2));
997         }
998         activate_mood_or_playlist(NULL, pbout);
999 free_lpr:
1000         lls_free_parse_result(aca->lpr, cmd);
1001         return ret;
1002 }
1003
1004 static int com_select(struct command_context *cc, struct lls_parse_result *lpr)
1005 {
1006         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
1007         char *errctx;
1008         int ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
1009
1010         if (ret < 0) {
1011                 send_errctx(cc, errctx);
1012                 return ret;
1013         }
1014         ret = send_lls_callback_request(com_select_callback, cmd, lpr, cc);
1015         return ret == osl(-E_OSL_RB_KEY_NOT_FOUND)? -E_BAD_MOP : ret;
1016 }
1017 EXPORT_SERVER_CMD_HANDLER(select);
1018
1019 static int com_init_callback(struct afs_callback_arg *aca)
1020 {
1021         uint32_t table_mask = *(uint32_t *)aca->query.data;
1022         int i, ret;
1023
1024         close_afs_tables();
1025         get_database_dir();
1026         for (i = 0; i < NUM_AFS_TABLES; i++) {
1027                 const struct afs_table *t = afs_tables + i;
1028
1029                 if (!(table_mask & (1 << i)))
1030                         continue;
1031                 if (!t->ops->create)
1032                         continue;
1033                 ret = t->ops->create(database_dir);
1034                 if (ret < 0) {
1035                         afs_error(aca, "cannot create table %s\n", t->name);
1036                         goto out;
1037                 }
1038                 para_printf(&aca->pbout, "successfully created %s table\n",
1039                         t->name);
1040         }
1041         ret = open_afs_tables();
1042         if (ret < 0)
1043                 afs_error(aca, "cannot open afs tables: %s\n",
1044                         para_strerror(-ret));
1045 out:
1046         return ret;
1047 }
1048
1049 static int com_init(struct command_context *cc, struct lls_parse_result *lpr)
1050 {
1051         int i, j, ret;
1052         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1053         struct osl_object query = {.data = &table_mask,
1054                 .size = sizeof(table_mask)};
1055         unsigned num_inputs = lls_num_inputs(lpr);
1056
1057         get_database_dir();
1058         ret = para_mkdir(database_dir);
1059         if (ret < 0)
1060                 return ret;
1061         if (num_inputs > 0) {
1062                 table_mask = 0;
1063                 for (i = 0; i < num_inputs; i++) {
1064                         for (j = 0; j < NUM_AFS_TABLES; j++) {
1065                                 const struct afs_table *t = afs_tables + j;
1066
1067                                 if (strcmp(lls_input(i, lpr), t->name))
1068                                         continue;
1069                                 table_mask |= (1 << j);
1070                                 break;
1071                         }
1072                         if (j == NUM_AFS_TABLES)
1073                                 return -E_BAD_TABLE_NAME;
1074                 }
1075         }
1076         return send_callback_request(com_init_callback, &query,
1077                 afs_cb_result_handler, cc);
1078 }
1079 EXPORT_SERVER_CMD_HANDLER(init);
1080
1081 static int com_check(struct command_context *cc, struct lls_parse_result *lpr)
1082 {
1083         const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(CHECK, AFT, lpr);
1084         const struct lls_opt_result *r_A = SERVER_CMD_OPT_RESULT(CHECK, ATTRIBUTE, lpr);
1085         const struct lls_opt_result *r_m = SERVER_CMD_OPT_RESULT(CHECK, MOOD, lpr);
1086         const struct lls_opt_result *r_p = SERVER_CMD_OPT_RESULT(CHECK, PLAYLIST, lpr);
1087         bool noopt = !lls_opt_given(r_a) && !lls_opt_given(r_A)
1088                 && !lls_opt_given(r_m) && !lls_opt_given(r_p);
1089         int ret;
1090
1091         if (noopt || lls_opt_given(r_a)) {
1092                 ret = send_callback_request(aft_check_callback, NULL,
1093                         afs_cb_result_handler, cc);
1094                 if (ret < 0)
1095                         return ret;
1096         }
1097         if (noopt || lls_opt_given(r_A)) {
1098                 ret = send_callback_request(attribute_check_callback, NULL,
1099                         afs_cb_result_handler, cc);
1100                 if (ret < 0)
1101                         return ret;
1102         }
1103         if (noopt || lls_opt_given(r_p)) {
1104                 ret = send_callback_request(playlist_check_callback,
1105                         NULL, afs_cb_result_handler, cc);
1106                 if (ret < 0)
1107                         return ret;
1108         }
1109         if (noopt || lls_opt_given(r_m)) {
1110                 ret = send_callback_request(mood_check_callback, NULL,
1111                         afs_cb_result_handler, cc);
1112                 if (ret < 0)
1113                         return ret;
1114         }
1115         return 1;
1116 }
1117 EXPORT_SERVER_CMD_HANDLER(check);
1118
1119 /**
1120  * The afs event dispatcher.
1121  *
1122  * \param event Type of the event.
1123  * \param pb May be \p NULL.
1124  * \param data Type depends on \a event.
1125  *
1126  * This function calls each table event handler, passing \a pb and \a data
1127  * verbatim. It's up to the handlers to interpret the \a data pointer. If a
1128  * handler returns negative, the loop is aborted.
1129  *
1130  * \return The (negative) error code of the first handler that failed, or non-negative
1131  * if all handlers succeeded.
1132  */
1133 __must_check int afs_event(enum afs_events event, struct para_buffer *pb,
1134                 void *data)
1135 {
1136         int i, ret;
1137
1138         for (i = 0; i < NUM_AFS_TABLES; i++) {
1139                 const struct afs_table *t = afs_tables + i;
1140                 if (!t->ops->event_handler)
1141                         continue;
1142                 ret = t->ops->event_handler(event, pb, data);
1143                 if (ret < 0) {
1144                         PARA_CRIT_LOG("table %s, event %u: %s\n", t->name,
1145                                 event, para_strerror(-ret));
1146                         return ret;
1147                 }
1148         }
1149         return 1;
1150 }
1151
1152 /**
1153  * Dummy event handler for the images table.
1154  *
1155  * \param event Unused.
1156  * \param pb Unused.
1157  * \param data Unused.
1158  *
1159  * \return The images table does not honor events, so this handler always
1160  * returns success.
1161  */
1162 __a_const int images_event_handler(__a_unused enum afs_events event,
1163         __a_unused  struct para_buffer *pb, __a_unused void *data)
1164 {
1165         return 1;
1166 }
1167
1168 /**
1169  * Dummy event handler for the lyrics table.
1170  *
1171  * \param event Unused.
1172  * \param pb Unused.
1173  * \param data Unused.
1174  *
1175  * \return The lyrics table does not honor events, so this handler always
1176  * returns success.
1177  */
1178 __a_const int lyrics_event_handler(__a_unused enum afs_events event,
1179         __a_unused struct para_buffer *pb, __a_unused void *data)
1180 {
1181         return 1;
1182 }