b5cf9f792e955d8c7df53483a3aeb7ec6970d1a1
[paraslash.git] / afs.c
1 #include "para.h"
2 #include "afh.h"
3 #include "error.h"
4 #include <dirent.h> /* readdir() */
5 #include <sys/mman.h>
6 #include <sys/time.h>
7 //#include <inttypes.h>
8
9 #include "net.h"
10 #include "afs.h"
11 #include "ipc.h"
12 #include "string.h"
13 #include "list.h"
14 #include "sched.h"
15 #include "signal.h"
16 #include "fd.h"
17
18 /** \file afs.c Paraslash's audio file selector. */
19
20 /**
21  * Compare two osl objects of string type.
22  *
23  * \param obj1 Pointer to the first object.
24  * \param obj2 Pointer to the second object.
25  *
26  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
27  * are taken into account.
28  *
29  * \return It returns an integer less than, equal to, or greater than zero if
30  * \a obj1 is found, respectively, to be less than, to match, or be greater than
31  * obj2.
32  *
33  * \sa strcmp(3), strncmp(3), osl_compare_func.
34  */
35 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
36 {
37         const char *str1 = (const char *)obj1->data;
38         const char *str2 = (const char *)obj2->data;
39         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
40 }
41
42 /** The osl tables used by afs. \sa blob.c */
43 enum afs_table_num {
44         /** Contains audio file information. See aft.c. */
45         TBLNUM_AUDIO_FILES,
46         /** The table for the paraslash attributes. See attribute.c. */
47         TBLNUM_ATTRIBUTES,
48         /**
49          * Paraslash's scoring system is based on Gaussian normal
50          * distributions, and the relevant data is stored in the rbtrees of an
51          * osl table containing only volatile columns.  See score.c for
52          * details.
53          */
54         TBLNUM_SCORES,
55         /**
56          * A standard blob table containing the mood definitions. For details
57          * see mood.c.
58          */
59         TBLNUM_MOODS,
60         /** A blob table containing lyrics on a per-song basis. */
61         TBLNUM_LYRICS,
62         /** Another blob table for images (for example album cover art). */
63         TBLNUM_IMAGES,
64         /** Yet another blob table for storing standard playlists. */
65         TBLNUM_PLAYLIST,
66         /** How many tables are in use? */
67         NUM_AFS_TABLES
68 };
69
70 static struct table_info afs_tables[NUM_AFS_TABLES];
71
72 struct command_task {
73         /** The file descriptor for the local socket. */
74         int fd;
75         /**
76          * Value sent by the command handlers to identify themselves as
77          * children of the running para_server.
78          */
79         uint32_t cookie;
80         /** The associated task structure. */
81         struct task task;
82 };
83
84
85 /**
86  * A wrapper for strtol(3).
87  *
88  * \param str The string to be converted to a long integer.
89  * \param result The converted value is stored here.
90  *
91  * \return Positive on success, -E_ATOL on errors.
92  *
93  * \sa strtol(3), atoi(3).
94  */
95 int para_atol(const char *str, long *result)
96 {
97         char *endptr;
98         long val;
99         int ret, base = 10;
100
101         errno = 0; /* To distinguish success/failure after call */
102         val = strtol(str, &endptr, base);
103         ret = -E_ATOL;
104         if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
105                 goto out; /* overflow */
106         if (errno != 0 && val == 0)
107                 goto out; /* other error */
108         if (endptr == str)
109                 goto out; /* No digits were found */
110         if (*endptr != '\0')
111                 goto out; /* Further characters after number */
112         *result = val;
113         ret = 1;
114 out:
115         return ret;
116 }
117
118 /**
119  * Struct to let para_server call a function specified from child context.
120  *
121  * Commands that need to change the state of para_server can't
122  * change the relevant data structures directly because commands
123  * are executed in a child process, i.e. they get their own
124  * virtual address space. This structure must be used to let
125  * para_server (i.e. the parent process) call a function specified
126  * by the child (the command handler).
127  *
128  * \sa fork(2), ipc.c.
129  */
130 struct callback_data {
131         /** The function to be called. */
132         callback_function *handler;
133         /** The sma for the parameters of the callback function. */
134         int query_shmid;
135         /** The size of the query sma. */
136         size_t query_size;
137         /** If the callback produced a result, it is stored in this sma. */
138         int result_shmid;
139         /** The size of the result sma. */
140         size_t result_size;
141         /** The return value of the callback function. */
142         int callback_ret;
143         /** The return value of the callback() procedure. */
144         int sma_ret;
145 };
146
147 struct callback_query {
148         /** The function to be called. */
149         callback_function *handler;
150         /** The number of bytes of the query */
151         size_t query_size;
152 };
153
154 struct callback_result {
155         /** The number of bytes of the result. */
156         size_t result_size;
157 };
158
159 static struct callback_data *shm_callback_data;
160 static int callback_mutex;
161 static int child_mutex;
162 static int result_mutex;
163
164 /**
165  * Ask the parent process to call a given function.
166  *
167  * \param f The function to be called.
168  * \param query Pointer to arbitrary data for the callback.
169  * \param result Callback result will be stored here.
170  *
171  * This function creates a shared memory area, copies the buffer pointed to by
172  * \a buf to that area and notifies the parent process that  \a f should be
173  * called ASAP. It provides proper locking via semaphores to protect against
174  * concurent access to the shared memory area and against concurrent access by
175  * another child process that asks to call the same function.
176  *
177  * \return Negative, if the shared memory area could not be set up. The return
178  * value of the callback function otherwise.
179  *
180  * \sa shm_new(), shm_attach(), shm_detach(), mutex_lock(), mutex_unlock(),
181  * shm_destroy(), struct callback_data, send_option_arg_callback_request(),
182  * send_standard_callback_request().
183  */
184 int send_callback_request(callback_function *f, struct osl_object *query,
185                 struct osl_object *result)
186 {
187         struct callback_data cbd = {.handler = f};
188         int ret;
189         void *query_sma;
190
191         assert(query->data && query->size);
192         ret = shm_new(query->size);
193         if (ret < 0)
194                 return ret;
195         cbd.query_shmid = ret;
196         cbd.query_size = query->size;
197         ret = shm_attach(cbd.query_shmid, ATTACH_RW, &query_sma);
198         if (ret < 0)
199                 goto out;
200         memcpy(query_sma, query->data, query->size);
201         ret = shm_detach(query_sma);
202         if (ret < 0)
203                 goto out;
204         /* prevent other children from interacting */
205         mutex_lock(child_mutex);
206         /* prevent parent from messing with shm_callback_data. */
207         mutex_lock(callback_mutex);
208         /* all three mutexes are locked, set parameters for callback */
209         *shm_callback_data = cbd;
210         /* unblock parent */
211         mutex_unlock(callback_mutex);
212         kill(getppid(), SIGUSR1); /* wake up parent */
213         /*
214          * At this time only the parent can run. It will execute our callback
215          * and unlock the result_mutex when ready to indicate that the child
216          * may use the result. So let's sleep on this mutex.
217          */
218         mutex_lock(result_mutex);
219         /* No need to aquire the callback mutex again */
220         ret = shm_callback_data->sma_ret;
221         if (ret < 0) /* sma problem, callback might not have been executed */
222                 goto unlock_child_mutex;
223         if (shm_callback_data->result_shmid >= 0) { /* parent provided a result */
224                 void *sma;
225                 ret = shm_attach(shm_callback_data->result_shmid, ATTACH_RO,
226                         &sma);
227                 if (ret >= 0) {
228                         if (result) { /* copy result */
229                                 result->size = shm_callback_data->result_size;
230                                 result->data = para_malloc(result->size);
231                                 memcpy(result->data, sma, result->size);
232                                 ret = shm_detach(sma);
233                                 if (ret < 0)
234                                         PARA_ERROR_LOG("can not detach result\n");
235                         } else
236                                 PARA_WARNING_LOG("no result pointer\n");
237                 } else
238                         PARA_ERROR_LOG("attach result failed: %d\n", ret);
239                 if (shm_destroy(shm_callback_data->result_shmid) < 0)
240                         PARA_ERROR_LOG("destroy result failed\n");
241         } else { /* no result from callback */
242                 if (result) {
243                         PARA_WARNING_LOG("callback has no result\n");
244                         result->data = NULL;
245                         result->size = 0;
246                 }
247         }
248         ret = shm_callback_data->callback_ret;
249 unlock_child_mutex:
250         /* give other children a chance */
251         mutex_unlock(child_mutex);
252 out:
253         if (shm_destroy(cbd.query_shmid) < 0)
254                 PARA_ERROR_LOG("%s\n", "shm destroy error");
255         PARA_DEBUG_LOG("callback_ret: %d\n", ret);
256         return ret;
257 }
258
259 /**
260  * Send a callback request passing an options structure and an argument vector.
261  *
262  * \param options pointer to an arbitrary data structure.
263  * \param argc Argument count.
264  * \param argv Standard argument vector.
265  * \param f The callback function.
266  * \param result The result of the query is stored here.
267  *
268  * Some commands have a couple of options that are parsed in child context for
269  * syntactic correctness and are stored in a special options structure for that
270  * command. This function allows to pass such a structure together with a list
271  * of further arguments (often a list of audio files) to the parent process.
272  *
273  * \sa send_standard_callback_request(), send_callback_request().
274  */
275 int send_option_arg_callback_request(struct osl_object *options,
276                 int argc, const char **argv, callback_function *f,
277                 struct osl_object *result)
278 {
279         char *p;
280         int i, ret;
281         struct osl_object query = {.size = options? options->size : 0};
282
283         for (i = 0; i < argc; i++)
284                 query.size += strlen(argv[i]) + 1;
285         query.data = para_malloc(query.size);
286         p = query.data;
287         if (options) {
288                 memcpy(query.data, options->data, options->size);
289                 p += options->size;
290         }
291         for (i = 0; i < argc; i++) {
292                 strcpy(p, argv[i]); /* OK */
293                 p += strlen(argv[i]) + 1;
294         }
295         ret = send_callback_request(f, &query, result);
296         free(query.data);
297         return ret;
298 }
299
300 /**
301  * Send a callback request with an argument vector only.
302  *
303  * \param argc The same meaning as in send_option_arg_callback_request().
304  * \param argv The same meaning as in send_option_arg_callback_request().
305  * \param f The same meaning as in send_option_arg_callback_request().
306  * \param result The same meaning as in send_option_arg_callback_request().
307  *
308  * This is similar to send_option_arg_callback_request(), but no options buffer
309  * is passed to the parent process.
310  *
311  * \return The return value of the underlying call to
312  * send_option_arg_callback_request().
313  */
314 int send_standard_callback_request(int argc, const char **argv,
315                 callback_function *f, struct osl_object *result)
316 {
317         return send_option_arg_callback_request(NULL, argc, argv, f, result);
318 }
319
320 /*
321  * write input from fd to dynamically allocated char array,
322  * but maximal max_size byte. Return size.
323  */
324 static int fd2buf(int fd, char **buf, int max_size)
325 {
326         const size_t chunk_size = 1024;
327         size_t size = 2048;
328         char *p;
329         int ret;
330
331         *buf = para_malloc(size * sizeof(char));
332         p = *buf;
333         while ((ret = read(fd, p, chunk_size)) > 0) {
334                 p += ret;
335                 if ((p - *buf) + chunk_size >= size) {
336                         char *tmp;
337
338                         size *= 2;
339                         if (size > max_size) {
340                                 ret = -E_INPUT_TOO_LARGE;
341                                 goto out;
342                         }
343                         tmp = para_realloc(*buf, size);
344                         p = (p - *buf) + tmp;
345                         *buf = tmp;
346                 }
347         }
348         if (ret < 0) {
349                 ret = -E_READ;
350                 goto out;
351         }
352         ret = p - *buf;
353 out:
354         if (ret < 0 && *buf)
355                 free(*buf);
356         return ret;
357 }
358
359 /**
360  * Read from stdin, and send the result to the parent process.
361  *
362  * \param arg_obj Pointer to the arguments to \a f.
363  * \param f The callback function.
364  * \param max_len Don't read more than that many bytes from stdin.
365  * \param result The result of the query is stored here.
366  *
367  * This function is used by commands that wish to let para_server store
368  * arbitrary data specified by the user (for instance the add_blob family of
369  * commands). First, at most \a max_len bytes are read from stdin, the result
370  * is concatenated with the buffer given by \a arg_obj, and the combined buffer
371  * is made available to the parent process via shared memory.
372  *
373  * \return Negative on errors, the return value of the underlying call to
374  * send_callback_request() otherwise.
375  */
376 int stdin_command(struct osl_object *arg_obj, callback_function *f,
377                 unsigned max_len, struct osl_object *result)
378 {
379         char *stdin_buf;
380         size_t stdin_len;
381         struct osl_object query;
382         int ret = fd2buf(STDIN_FILENO, &stdin_buf, max_len);
383
384         if (ret < 0)
385                 return ret;
386         stdin_len = ret;
387         query.size = arg_obj->size + stdin_len;
388         query.data = para_malloc(query.size);
389         memcpy(query.data, arg_obj->data, arg_obj->size);
390         memcpy((char *)query.data + arg_obj->size, stdin_buf, stdin_len);
391         free(stdin_buf);
392         ret = send_callback_request(f, &query, result);
393         free(query.data);
394         return ret;
395 }
396
397 /**
398  * Open the audio file with highest score.
399  *
400  * \param afd Audio file data is returned here.
401  *
402  * This stores all information for streaming the "best" audio file
403  * in the \a afd structure.
404  *
405  * \return Positive on success, negative on errors.
406  *
407  * \sa close_audio_file(), open_and_update_audio_file().
408  */
409 int open_next_audio_file(struct audio_file_data *afd)
410 {
411         struct osl_row *aft_row;
412         int ret;
413         for (;;) {
414                 ret = score_get_best(&aft_row, &afd->score);
415                 if (ret < 0)
416                         return ret;
417                 ret = open_and_update_audio_file(aft_row, afd);
418                 if (ret >= 0)
419                         return ret;
420         }
421 }
422
423 /**
424  * Free all resources which were allocated by open_next_audio_file().
425  *
426  * \param afd The structure previously filled in by open_next_audio_file().
427  *
428  * \return The return value of the underlying call to para_munmap().
429  *
430  * \sa open_next_audio_file().
431  */
432 int close_audio_file(struct audio_file_data *afd)
433 {
434         free(afd->afhi.chunk_table);
435         return para_munmap(afd->map.data, afd->map.size);
436 }
437
438 #if 0
439 static void play_loop(enum play_mode current_play_mode)
440 {
441         int i, ret;
442         struct audio_file_data afd;
443
444         afd.current_play_mode = current_play_mode;
445         for (i = 0; i < 0; i++) {
446                 ret = open_next_audio_file(&afd);
447                 if (ret < 0) {
448                         PARA_ERROR_LOG("failed to open next audio file: %d\n", ret);
449                         return;
450                 }
451                 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd.path, afd.score);
452                 sleep(1);
453                 close_audio_file(&afd);
454         }
455 }
456 #endif
457
458
459 static enum play_mode init_admissible_files(void)
460 {
461         int ret;
462         char *given_mood, *given_playlist;
463
464         given_mood = "mood_that_was_given_at_the_command_line";
465         given_playlist = "given_playlist";
466
467         if (given_mood) {
468                 ret = mood_open(given_mood);
469                 if (ret >= 0) {
470                         if (given_playlist)
471                                 PARA_WARNING_LOG("ignoring playlist %s\n",
472                                         given_playlist);
473                         return PLAY_MODE_MOOD;
474                 }
475         }
476         if (given_playlist) {
477                 ret = playlist_open(given_playlist);
478                 if (ret >= 0)
479                         return PLAY_MODE_PLAYLIST;
480         }
481         ret = mood_open(NULL); /* open first available mood */
482         if (ret >= 0)
483                 return PLAY_MODE_MOOD;
484         mood_open(""); /* open dummy mood, always successful */
485         return PLAY_MODE_MOOD;
486 }
487
488 static int setup_command_socket_or_die(void)
489 {
490         int ret;
491         char *socket_name = "/tmp/afs_command_socket";
492         struct sockaddr_un unix_addr;
493
494         unlink(socket_name);
495         ret = create_local_socket(socket_name, &unix_addr,
496                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
497         if (ret < 0)
498                 exit(EXIT_FAILURE);
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 int server_socket;
509
510 void loop(void)
511 {
512         for (;;)
513                 sleep(1);
514 }
515
516 static void afs_shutdown(enum osl_close_flags flags)
517 {
518         PARA_NOTICE_LOG("cleaning up\n");
519         score_shutdown(flags);
520         attribute_shutdown(flags);
521         mood_close();
522         playlist_close();
523         moods_shutdown(flags);
524         playlists_shutdown(flags);
525         lyrics_shutdown(flags);
526         images_shutdown(flags);
527         aft_shutdown(flags);
528 }
529
530 static void signal_pre_select(struct sched *s, struct task *t)
531 {
532         struct signal_task *st = t->private_data;
533         t->ret = 1;
534         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
535 }
536
537 static void signal_post_select(struct sched *s, struct task *t)
538 {
539         struct signal_task *st = t->private_data;
540         t->ret = 1;
541         if (!FD_ISSET(st->fd, &s->rfds))
542                 return;
543         st->signum = para_next_signal();
544         PARA_NOTICE_LOG("caught signal %d\n", st->signum);
545         t->ret = 1;
546         if (st->signum == SIGUSR1)
547                 return; /* ignore SIGUSR1 */
548         afs_shutdown(OSL_MARK_CLEAN);
549         t->ret = -E_SIGNAL_CAUGHT;
550 }
551
552 static void register_signal_task(void)
553 {
554         static struct signal_task signal_task_struct;
555         struct signal_task *st = &signal_task_struct;
556         st->fd = para_signal_init();
557         PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
558         para_install_sighandler(SIGINT);
559         para_install_sighandler(SIGTERM);
560         para_install_sighandler(SIGPIPE);
561
562         st->task.pre_select = signal_pre_select;
563         st->task.post_select = signal_post_select;
564         st->task.private_data = st;
565         sprintf(st->task.status, "signal task");
566         register_task(&st->task);
567 }
568
569 static void command_pre_select(struct sched *s, struct task *t)
570 {
571         struct command_task *ct = t->private_data;
572         t->ret = 1;
573         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
574 }
575
576 /*
577  * On errors, negative value is written to fd.
578  * On success: If query produced a result, the result_shmid is written to fd.
579  * Otherwise, zero is written.
580  */
581 static int call_callback(int fd, int query_shmid)
582 {
583         void *query_shm, *result_shm;
584         struct callback_query *cq;
585         struct callback_result *cr;
586         struct osl_object query, result = {.data = NULL};
587         int result_shmid = -1, ret, ret2;
588
589         ret = shm_attach(query_shmid, ATTACH_RO, &query_shm);
590         if (ret < 0)
591                 goto out;
592         cq = query_shm;
593         query.data = (char *)query_shm + sizeof(*cq);
594         query.size = cq->query_size;
595         ret = cq->handler(&query, &result);
596         ret2 = shm_detach(query_shm);
597         if (ret2 < 0 && ret >= 0)
598                 ret = ret2;
599         if (ret < 0)
600                 goto out;
601         ret = 0;
602         if (!result.data || !result.size)
603                 goto out;
604         ret = shm_new(result.size + sizeof(struct callback_result));
605         if (ret < 0)
606                 goto out;
607         result_shmid = ret;
608         ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
609         if (ret < 0)
610                 goto out;
611         cr = result_shm;
612         cr->result_size = result.size;
613         memcpy(result_shm + sizeof(*cr), result.data, result.size);
614         ret = shm_detach(result_shm);
615         if (ret < 0)
616                 goto out;
617         ret = result_shmid;
618 out:
619         free(result.data);
620         ret2 = send_bin_buffer(fd, (char *)ret, sizeof(int));
621         if (ret < 0 || ret2 < 0) {
622                 if (result_shmid >= 0)
623                         if (shm_destroy(result_shmid) < 0)
624                                 PARA_ERROR_LOG("destroy result failed\n");
625                 if (ret >= 0)
626                         ret = ret2;
627         }
628         return ret;
629 }
630
631 static void command_post_select(struct sched *s, struct task *t)
632 {
633         struct command_task *ct = t->private_data;
634         struct sockaddr_un unix_addr;
635         char buf[sizeof(uint32_t) + sizeof(int)];
636         uint32_t cookie;
637         int query_shmid, fd;
638
639         t->ret = 1;
640         if (!FD_ISSET(ct->fd, &s->rfds))
641                 return;
642         t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
643         if (t->ret < 0)
644                 return;
645         /*
646          * The following errors may be caused by a malicious local user. So do
647          * not return an error in this case as this would terminate  para_afs
648          * and para_server.
649          */
650         fd = t->ret;
651         t->ret = recv_bin_buffer(ct->fd, buf, sizeof(buf));
652         if (t->ret < 0) {
653                 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
654                 t->ret = 1;
655                 goto out;
656         }
657         if (t->ret != sizeof(buf)) {
658                 PARA_NOTICE_LOG("short read (%d bytes, expected %d)\n",
659                         t->ret, sizeof(buf));
660                 t->ret = 1;
661                 goto out;
662         }
663         cookie = *(uint32_t *)buf;
664         if (cookie != ct->cookie) {
665                 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
666                         (unsigned)cookie, (unsigned)ct->cookie);
667                 t->ret = 1;
668                 goto out;
669         }
670         query_shmid = *(int *)(buf + sizeof(cookie));
671         if (query_shmid < 0) {
672                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
673                         query_shmid);
674                 t->ret = 1;
675                 goto out;
676         }
677         t->ret = call_callback(fd, query_shmid);
678         if (t->ret < 0) {
679                 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
680                 t->ret = 1;
681                 goto out;
682         }
683 out:
684         close(fd);
685 }
686
687 static void register_command_task(uint32_t cookie)
688 {
689         static struct command_task command_task_struct;
690         struct command_task *ct = &command_task_struct;
691         ct->fd = setup_command_socket_or_die();
692         ct->cookie = cookie;
693
694         ct->task.pre_select = command_pre_select;
695         ct->task.post_select = command_post_select;
696         ct->task.private_data = ct;
697         sprintf(ct->task.status, "command task");
698         register_task(&ct->task);
699 }
700
701 void register_tasks(uint32_t cookie)
702 {
703         register_signal_task();
704         register_command_task(cookie);
705 }
706
707 __noreturn int afs_init(uint32_t cookie, int socket_fd)
708 {
709         int ret;
710 //      void *shm_area;
711         enum play_mode current_play_mode;
712         struct sched s;
713
714         server_socket = socket_fd;
715         PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
716                 server_socket, (unsigned) cookie);
717
718         ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES]);
719         if (ret < 0)
720                 goto attribute_init_error;
721         ret = moods_init(&afs_tables[TBLNUM_MOODS]);
722         if (ret < 0)
723                 goto moods_init_error;
724         ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST]);
725         if (ret < 0)
726                 goto playlists_init_error;
727         ret = lyrics_init(&afs_tables[TBLNUM_LYRICS]);
728         if (ret < 0)
729                 goto lyrics_init_error;
730         ret = images_init(&afs_tables[TBLNUM_IMAGES]);
731         if (ret < 0)
732                 goto images_init_error;
733         ret = score_init(&afs_tables[TBLNUM_SCORES]);
734         if (ret < 0)
735                 goto score_init_error;
736         ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES]);
737         if (ret < 0)
738                 goto aft_init_error;
739
740         current_play_mode = init_admissible_files();
741         register_tasks(cookie);
742         s.default_timeout.tv_sec = 0;
743         s.default_timeout.tv_usec = 99 * 1000;
744         sched(&s);
745
746 #if 0
747         ret = shm_new(sizeof(struct callback_data));
748         if (ret < 0)
749                 return ret;
750         shmid = ret;
751         ret = shm_attach(shmid, ATTACH_RW, &shm_area);
752         if (ret < 0)
753                 return ret;
754         shm_callback_data = shm_area;
755         ret = mutex_new();
756         if (ret < 0)
757                 return ret;
758         callback_mutex = ret;
759         ret = mutex_new();
760         if (ret < 0)
761                 return ret;
762         child_mutex = ret;
763         ret = mutex_new();
764         if (ret < 0)
765                 return ret;
766         result_mutex = ret;
767         mutex_lock(result_mutex);
768 #endif 
769 aft_init_error:
770         score_shutdown(OSL_MARK_CLEAN);
771 score_init_error:
772         images_shutdown(OSL_MARK_CLEAN);
773 images_init_error:
774         lyrics_shutdown(OSL_MARK_CLEAN);
775 lyrics_init_error:
776         playlists_shutdown(OSL_MARK_CLEAN);
777 playlists_init_error:
778         moods_shutdown(OSL_MARK_CLEAN);
779 moods_init_error:
780         attribute_shutdown(OSL_MARK_CLEAN);
781 attribute_init_error:
782         exit(EXIT_FAILURE);
783 }
784
785 static int create_all_tables(void)
786 {
787         int i, ret;
788
789         for (i = 0; i < NUM_AFS_TABLES; i++) {
790                 struct table_info *ti = afs_tables + i;
791
792                 if (ti->flags & TBLFLAG_SKIP_CREATE)
793                         continue;
794                 ret = osl_create_table(ti->desc);
795                 if (ret < 0)
796                         return ret;
797         }
798         return 1;
799 }
800
801 /* TODO load tables after init */
802 static int com_init(__a_unused int fd, int argc, const char **argv)
803 {
804         int i, j, ret;
805         if (argc == 1)
806                 return create_all_tables();
807         for (i = 1; i < argc; i++) {
808                 for (j = 0; j < NUM_AFS_TABLES; j++) {
809                         struct table_info *ti = afs_tables + j;
810
811                         if (ti->flags & TBLFLAG_SKIP_CREATE)
812                                 continue;
813                         if (strcmp(argv[i], ti->desc->name))
814                                 continue;
815                         PARA_NOTICE_LOG("creating table %s\n", argv[i]);
816                         ret = osl_create_table(ti->desc);
817                         if (ret < 0)
818                                 return ret;
819                         break;
820                 }
821                 if (j == NUM_AFS_TABLES)
822                         return -E_BAD_TABLE_NAME;
823         }
824         return 1;
825 }
826
827 /** Describes a command of para_server. */
828 struct command {
829         /** The name of the command. */
830         const char *name;
831         /** The handler function. */
832         int (*handler)(int fd, int argc, const char **argv);
833 };
834
835 static struct command afs_cmds[] = {
836 {
837         .name = "add",
838         .handler = com_add,
839 },
840 {
841         .name = "addlyr",
842         .handler = com_addlyr,
843 },
844 {
845         .name = "addimg",
846         .handler = com_addimg,
847 },
848 {
849         .name = "addmood",
850         .handler = com_addmood,
851 },
852 {
853         .name = "addpl",
854         .handler = com_addpl,
855 },
856 {
857         .name = "catlyr",
858         .handler = com_catlyr,
859 },
860 {
861         .name = "catimg",
862         .handler = com_catimg,
863 },
864 {
865         .name = "mvimg",
866         .handler = com_mvimg,
867 },
868 {
869         .name = "mvlyr",
870         .handler = com_mvlyr,
871 },
872 {
873         .name = "mvmood",
874         .handler = com_mvmood,
875 },
876 {
877         .name = "mvpl",
878         .handler = com_mvpl,
879 },
880 {
881         .name = "catmood",
882         .handler = com_catmood,
883 },
884 {
885         .name = "catpl",
886         .handler = com_catpl,
887 },
888 {
889         .name = "rmatt",
890         .handler = com_rmatt,
891 },
892 {
893         .name = "init",
894         .handler = com_init,
895 },
896 {
897         .name = "lsatt",
898         .handler = com_lsatt,
899 },
900 {
901         .name = "ls",
902         .handler = com_afs_ls,
903 },
904 {
905         .name = "lslyr",
906         .handler = com_lslyr,
907 },
908 {
909         .name = "lsimg",
910         .handler = com_lsimg,
911 },
912 {
913         .name = "lsmood",
914         .handler = com_lsmood,
915 },
916 {
917         .name = "lspl",
918         .handler = com_lspl,
919 },
920 {
921         .name = "setatt",
922         .handler = com_setatt,
923 },
924 {
925         .name = "addatt",
926         .handler = com_addatt,
927 },
928 {
929         .name = "rm",
930         .handler = com_afs_rm,
931 },
932 {
933         .name = "rmlyr",
934         .handler = com_rmlyr,
935 },
936 {
937         .name = "rmimg",
938         .handler = com_rmimg,
939 },
940 {
941         .name = "rmmood",
942         .handler = com_rmmood,
943 },
944 {
945         .name = "rmpl",
946         .handler = com_rmpl,
947 },
948 {
949         .name = "touch",
950         .handler = com_touch,
951 },
952 {
953         .name = NULL,
954 }
955 };
956
957 #if 0
958 static void call_callback(void)
959 {
960         struct osl_object query, result = {.data = NULL};
961         int ret, ret2;
962
963         shm_callback_data->result_shmid = -1; /* no result */
964         ret = shm_attach(shm_callback_data->query_shmid, ATTACH_RW,
965                 &query.data);
966         if (ret < 0)
967                 goto out;
968         query.size = shm_callback_data->query_size;
969         shm_callback_data->callback_ret = shm_callback_data->handler(&query,
970                 &result);
971         if (result.data && result.size) {
972                 void *sma;
973                 ret = shm_new(result.size);
974                 if (ret < 0)
975                         goto detach_query;
976                 shm_callback_data->result_shmid = ret;
977                 shm_callback_data->result_size = result.size;
978                 ret = shm_attach(shm_callback_data->result_shmid, ATTACH_RW, &sma);
979                 if (ret < 0)
980                         goto destroy_result;
981                 memcpy(sma, result.data, result.size);
982                 ret = shm_detach(sma);
983                 if (ret < 0) {
984                         PARA_ERROR_LOG("detach result failed\n");
985                         goto destroy_result;
986                 }
987         }
988         ret = 1;
989         goto detach_query;
990 destroy_result:
991         if (shm_destroy(shm_callback_data->result_shmid) < 0)
992                 PARA_ERROR_LOG("destroy result failed\n");
993         shm_callback_data->result_shmid = -1;
994 detach_query:
995         free(result.data);
996         ret2 = shm_detach(query.data);
997         if (ret2 < 0) {
998                 PARA_ERROR_LOG("detach query failed\n");
999                 if (ret >= 0)
1000                         ret = ret2;
1001         }
1002 out:
1003         if (ret < 0)
1004                 PARA_ERROR_LOG("sma error %d\n", ret);
1005         shm_callback_data->sma_ret = ret;
1006         shm_callback_data->handler = NULL;
1007         mutex_unlock(result_mutex); /* wake up child */
1008 }
1009
1010 static int got_sigchld;
1011 static void server_loop(int child_pid)
1012 {
1013 //      int status;
1014
1015         PARA_DEBUG_LOG("server pid: %d, child pid: %d\n",
1016                 getpid(), child_pid);
1017         for (;;)  {
1018                 mutex_lock(callback_mutex);
1019                 if (shm_callback_data->handler)
1020                         call_callback();
1021                 mutex_unlock(callback_mutex);
1022                 usleep(100);
1023                 if (!got_sigchld)
1024                         continue;
1025                 mutex_destroy(result_mutex);
1026                 mutex_destroy(callback_mutex);
1027                 mutex_destroy(child_mutex);
1028                 afs_shutdown(OSL_MARK_CLEAN);
1029                 exit(EXIT_SUCCESS);
1030         }
1031 }
1032
1033 int main(int argc, const char **argv)
1034 {
1035         int i, ret = -E_AFS_SYNTAX;
1036
1037         signal(SIGUSR1, dummy);
1038         signal(SIGCHLD, sigchld_handler);
1039         if (argc < 2)
1040                 goto out;
1041         ret = setup();
1042 //      ret = afs_init();
1043         if (ret < 0) {
1044                 PARA_EMERG_LOG("afs_init returned %d\n", ret);
1045                 exit(EXIT_FAILURE);
1046         }
1047         ret = fork();
1048         if (ret < 0) {
1049                 ret = -E_FORK;
1050                 goto out;
1051         }
1052         if (ret)
1053                 server_loop(ret);
1054         for (i = 0; cmd[i].name; i++) {
1055                 if (strcmp(cmd[i].name, argv[1]))
1056                         continue;
1057                 ret = cmd[i].handler(1, argc - 1 , argv + 1);
1058                 goto out;
1059
1060         }
1061         PARA_ERROR_LOG("unknown command: %s\n", argv[1]);
1062         ret = -1;
1063 out:
1064         if (ret < 0)
1065                 PARA_ERROR_LOG("error %d\n", ret);
1066         else
1067                 PARA_DEBUG_LOG("%s", "success\n");
1068         afs_shutdown(0);
1069         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1070 }
1071 #endif