server: Convert com_ls() to lopsub.
[paraslash.git] / aft.c
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file aft.c Audio file table functions. */
8
9 #include <regex.h>
10 #include <sys/mman.h>
11 #include <fnmatch.h>
12 #include <sys/shm.h>
13 #include <osl.h>
14 #include <lopsub.h>
15
16 #include "server_cmd.lsg.h"
17 #include "para.h"
18 #include "error.h"
19 #include "crypt.h"
20 #include "string.h"
21 #include "afh.h"
22 #include "afs.h"
23 #include "fd.h"
24 #include "ipc.h"
25 #include "portable_io.h"
26 #include "sideband.h"
27 #include "command.h"
28
29 static struct osl_table *audio_file_table;
30 static char *status_items;
31 static char *parser_friendly_status_items;
32
33 /** The different sorting methods of the ls command. */
34 enum ls_sorting_method {
35         /** -sp (default) */
36         LS_SORT_BY_PATH,
37         /** -ss */
38         LS_SORT_BY_SCORE,
39         /** -sl */
40         LS_SORT_BY_LAST_PLAYED,
41         /** -sn */
42         LS_SORT_BY_NUM_PLAYED,
43         /** -sf */
44         LS_SORT_BY_FREQUENCY,
45         /** -sc */
46         LS_SORT_BY_CHANNELS,
47         /** -si */
48         LS_SORT_BY_IMAGE_ID,
49         /** -sy */
50         LS_SORT_BY_LYRICS_ID,
51         /** -sb */
52         LS_SORT_BY_BITRATE,
53         /** -sd */
54         LS_SORT_BY_DURATION,
55         /** -sa */
56         LS_SORT_BY_AUDIO_FORMAT,
57         /** -sh */
58         LS_SORT_BY_HASH,
59 };
60
61 /** The different listing modes of the ls command. */
62 enum ls_listing_mode {
63         /** Default listing mode. */
64         LS_MODE_SHORT,
65         /** -l or -ll */
66         LS_MODE_LONG,
67         /** -lv */
68         LS_MODE_VERBOSE,
69         /** -lm */
70         LS_MODE_MBOX,
71         /** -lc */
72         LS_MODE_CHUNKS,
73         /** -lp */
74         LS_MODE_PARSER,
75 };
76
77 /* Data about one audio file. Needed for ls and stat output. */
78 struct ls_data {
79         /* Usual audio format handler information. */
80         struct afh_info afhi;
81         /* Audio file selector information. */
82         struct afs_info afsi;
83         /* The full path of the audio file. */
84         char *path;
85         /* The score value (if -a was given). */
86         long score;
87         /* The hash value of the audio file data. */
88         unsigned char *hash;
89 };
90
91 /**
92  * The size of the individual output fields of the ls command.
93  *
94  * These depend on the content being listed. For example, if each listed file
95  * is shorter than an hour, the duration format is set to mm:ss. Otherwise it
96  * is set to hh:mm:ss.
97  */
98 struct ls_widths {
99         /** size of the score field. */
100         unsigned short score_width;
101         /** size of the image id field. */
102         unsigned short image_id_width;
103         /** size of the lyrics id field. */
104         unsigned short lyrics_id_width;
105         /** size of the bitrate field. */
106         unsigned short bitrate_width;
107         /** size of the frequency field. */
108         unsigned short frequency_width;
109         /** size of the duration field. */
110         unsigned short duration_width;
111         /** size of the num played field. */
112         unsigned short num_played_width;
113         /** size of the amp field. */
114         unsigned short amp_width;
115         /** size of the audio format field. */
116         unsigned short audio_format_width;
117 };
118
119 /** Data passed from the ls command handler to its callback function. */
120 struct ls_options {
121         struct lls_parse_result *lpr;
122         /* Derived from lpr */
123         enum ls_sorting_method sorting;
124         /* Derived from lpr */
125         enum ls_listing_mode mode;
126         /** Used for long listing mode to align the output fields. */
127         struct ls_widths widths;
128         /** Size of the \a data array. */
129         uint32_t array_size;
130         /** Number of used entries in the data array. */
131         uint32_t num_matching_paths;
132         /** Array of matching entries. */
133         struct ls_data *data;
134         /** Used to sort the array. */
135         struct ls_data **data_ptr;
136 };
137
138 /**
139  * Describes the layout of the mmapped-afs info struct.
140  *
141  * \sa struct afs_info.
142  */
143 enum afsi_offsets {
144         /** Where .last_played is stored. */
145         AFSI_LAST_PLAYED_OFFSET = 0,
146         /** Storage position of the attributes bitmap. */
147         AFSI_ATTRIBUTES_OFFSET = 8,
148         /** Storage position of the .num_played field. */
149         AFSI_NUM_PLAYED_OFFSET = 16,
150         /** Storage position of the .image_id field. */
151         AFSI_IMAGE_ID_OFFSET = 20,
152         /** Storage position of the .lyrics_id field. */
153         AFSI_LYRICS_ID_OFFSET = 24,
154         /** Storage position of the .audio_format_id field. */
155         AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
156         /** Storage position of the amplification field. */
157         AFSI_AMP_OFFSET = 29,
158         /** 2 bytes reserved space for future usage. */
159         AFSI_AUDIO_FORMAT_UNUSED_OFFSET = 30,
160         /** On-disk storage space needed. */
161         AFSI_SIZE = 32
162 };
163
164 /*
165  * Convert a struct afs_info to an osl object.
166  *
167  * \param afsi Pointer to the audio file info to be converted.
168  * \param obj Result pointer.
169  *
170  * \sa load_afsi().
171  */
172 static void save_afsi(struct afs_info *afsi, struct osl_object *obj)
173 {
174         char *buf = obj->data;
175
176         write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
177         write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
178         write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
179         write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
180         write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
181         write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
182                 afsi->audio_format_id);
183         write_u8(buf + AFSI_AMP_OFFSET, afsi->amp);
184         memset(buf + AFSI_AUDIO_FORMAT_UNUSED_OFFSET, 0, 2);
185 }
186
187 /*
188  * Get the audio file selector info struct stored in an osl object.
189  *
190  * \param afsi Points to the audio_file info structure to be filled in.
191  * \param obj The osl object holding the data.
192  *
193  * \return Standard.
194  *
195  * \sa save_afsi().
196  */
197 static int load_afsi(struct afs_info *afsi, struct osl_object *obj)
198 {
199         char *buf = obj->data;
200         if (obj->size < AFSI_SIZE)
201                 return -E_BAD_AFSI;
202         afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
203         afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
204         afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
205         afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
206         afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
207         afsi->audio_format_id = read_u8(buf +
208                 AFSI_AUDIO_FORMAT_ID_OFFSET);
209         afsi->amp = read_u8(buf + AFSI_AMP_OFFSET);
210         return 1;
211 }
212
213 /** The columns of the audio file table. */
214 enum audio_file_table_columns {
215         /** The hash on the content of the audio file. */
216         AFTCOL_HASH,
217         /** The full path in the filesystem. */
218         AFTCOL_PATH,
219         /** The audio file selector info. */
220         AFTCOL_AFSI,
221         /** The audio format handler info. */
222         AFTCOL_AFHI,
223         /** The chunk table info and the chunk table of the audio file. */
224         AFTCOL_CHUNKS,
225         /** The number of columns of this table. */
226         NUM_AFT_COLUMNS
227 };
228
229 /* compare function for the hash column */
230 static int aft_hash_compare(const struct osl_object *obj1,
231                 const struct osl_object *obj2)
232 {
233         return hash_compare((unsigned char *)obj1->data,
234                 (unsigned char *)obj2->data);
235 }
236
237 static struct osl_column_description aft_cols[] = {
238         [AFTCOL_HASH] = {
239                 .storage_type = OSL_MAPPED_STORAGE,
240                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
241                 .name = "hash",
242                 .compare_function = aft_hash_compare,
243                 .data_size = HASH_SIZE
244         },
245         [AFTCOL_PATH] = {
246                 .storage_type = OSL_MAPPED_STORAGE,
247                 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
248                 .name = "path",
249                 .compare_function = string_compare,
250         },
251         [AFTCOL_AFSI] = {
252                 .storage_type = OSL_MAPPED_STORAGE,
253                 .storage_flags = OSL_FIXED_SIZE,
254                 .name = "afs_info",
255                 .data_size = AFSI_SIZE
256         },
257         [AFTCOL_AFHI] = {
258                 .storage_type = OSL_MAPPED_STORAGE,
259                 .name = "afh_info",
260         },
261         [AFTCOL_CHUNKS] = {
262                 .storage_type = OSL_DISK_STORAGE,
263                 .name = "chunks",
264         }
265 };
266
267 static struct osl_table_description audio_file_table_desc = {
268         .name = "audio_files",
269         .num_columns = NUM_AFT_COLUMNS,
270         .flags = OSL_LARGE_TABLE,
271         .column_descriptions = aft_cols
272 };
273
274 /*
275  * Produce a canonicalized absolute pathname.
276  *
277  * Returns one if the resolved path a directory, zero if it is a regular file,
278  * negative on errors.
279  */
280 static int verify_path(const char *orig_path, char **resolved_path)
281 {
282         int ret;
283         char *path = NULL;
284         struct stat statbuf;
285
286         if (*orig_path != '/') /* we only accept absolute paths */
287                 goto fail;
288         path = realpath(orig_path, NULL);
289         if (!path)
290                 goto fail;
291         if (stat(path, &statbuf) < 0)
292                 goto fail;
293         if (S_ISREG(statbuf.st_mode))
294                 ret = 0;
295         else if (S_ISDIR(statbuf.st_mode))
296                 ret = 1;
297         else
298                 goto fail;
299         *resolved_path = path;
300         return ret;
301 fail:
302         *resolved_path = NULL;
303         free(path);
304         return -E_BAD_PATH;
305 }
306
307 /** The on-disk layout of a afhi struct. */
308 enum afhi_offsets {
309         /** Where the number of seconds is stored. */
310         AFHI_SECONDS_TOTAL_OFFSET = 0,
311         /** Position of the bitrate. */
312         AFHI_BITRATE_OFFSET = 4,
313         /** Position of the frequency. */
314         AFHI_FREQUENCY_OFFSET = 8,
315         /** Was: Location of the audio file header. */
316         AFHI_UNUSED1_OFFSET = 12,
317         /* Length of the audio file header. Zero means: No header. */
318         AFHI_HEADER_LEN_OFFSET = 16,
319         /** The total number of chunks (4 bytes). */
320         CHUNKS_TOTAL_OFFSET = 20,
321         /** The length of the audio file header (4 bytes). */
322         HEADER_LEN_OFFSET = 24,
323         /** Was: The start of the audio file header (4 bytes). */
324         AFHI_UNUSED2_OFFSET = 28,
325         /** The seconds part of the chunk time (4 bytes). */
326         CHUNK_TV_TV_SEC_OFFSET = 32,
327         /** The microseconds part of the chunk time (4 bytes). */
328         CHUNK_TV_TV_USEC_OFFSET = 36,
329         /** Number of channels is stored here. (1 byte) */
330         AFHI_CHANNELS_OFFSET = 40,
331         /** The tag info position. */
332         AFHI_INFO_STRING_OFFSET = 41,
333         /** Minimal on-disk size of a valid afhi struct. */
334         MIN_AFHI_SIZE = 47, /* at least 6 null bytes for techinfo/tags */
335 };
336
337 static unsigned sizeof_afhi_buf(const struct afh_info *afhi)
338 {
339         if (!afhi)
340                 return 0;
341         return MIN_AFHI_SIZE
342                 + strlen(afhi->techinfo)
343                 + strlen(afhi->tags.artist)
344                 + strlen(afhi->tags.title)
345                 + strlen(afhi->tags.year)
346                 + strlen(afhi->tags.album)
347                 + strlen(afhi->tags.comment);
348 }
349
350 static void save_afhi(struct afh_info *afhi, char *buf)
351 {
352         char *p;
353
354         if (!afhi)
355                 return;
356         write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET, afhi->seconds_total);
357         write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
358         write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
359         write_u32(buf + AFHI_UNUSED1_OFFSET, 0);
360         write_u32(buf + AFHI_HEADER_LEN_OFFSET, afhi->header_len);
361         write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
362         write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
363         write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
364         write_u32(buf + AFHI_UNUSED2_OFFSET, 0);
365         write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
366         write_u32(buf + CHUNK_TV_TV_USEC_OFFSET, afhi->chunk_tv.tv_usec);
367         p = buf + AFHI_INFO_STRING_OFFSET;
368         /* The sprintf's below are OK as our caller made sure that buf is large enough */
369         p += sprintf(p, "%s", afhi->techinfo) + 1;
370         p += sprintf(p, "%s", afhi->tags.artist) + 1;
371         p += sprintf(p, "%s", afhi->tags.title) + 1;
372         p += sprintf(p, "%s", afhi->tags.year) + 1;
373         p += sprintf(p, "%s", afhi->tags.album) + 1;
374         sprintf(p, "%s", afhi->tags.comment);
375 }
376
377 static void load_afhi(const char *buf, struct afh_info *afhi)
378 {
379         afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
380         afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
381         afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
382         afhi->header_len = read_u32(buf + AFHI_HEADER_LEN_OFFSET);
383         afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
384         afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
385         afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
386         afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
387         afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC_OFFSET);
388         afhi->techinfo = (char *)buf + AFHI_INFO_STRING_OFFSET;
389         afhi->tags.artist = afhi->techinfo + strlen(afhi->techinfo) + 1;
390         afhi->tags.title = afhi->tags.artist + strlen(afhi->tags.artist) + 1;
391         afhi->tags.year = afhi->tags.title + strlen(afhi->tags.title) + 1;
392         afhi->tags.album = afhi->tags.year + strlen(afhi->tags.year) + 1;
393         afhi->tags.comment = afhi->tags.album + strlen(afhi->tags.album) + 1;
394 }
395
396 static unsigned sizeof_chunk_table(struct afh_info *afhi)
397 {
398         if (!afhi)
399                 return 0;
400         return 4 * (afhi->chunks_total + 1);
401 }
402
403 static uint32_t save_chunk_table(struct afh_info *afhi, char *buf)
404 {
405         int i;
406         uint32_t max = 0, old = 0;
407
408         for (i = 0; i <= afhi->chunks_total; i++) {
409                 uint32_t val = afhi->chunk_table[i];
410                 write_u32(buf + 4 * i, val);
411                 /*
412                  * If the first chunk is the header, do not consider it for the
413                  * calculation of the largest chunk size.
414                  */
415                 if (i == 0 || (i == 1 && afhi->header_len > 0)) {
416                         old = val;
417                         continue;
418                 }
419                 max = PARA_MAX(max, val - old);
420                 old = val;
421         }
422         return max;
423 }
424
425 static void load_chunk_table(struct afh_info *afhi, char *buf)
426 {
427         int i;
428
429         afhi->chunk_table = para_malloc(sizeof_chunk_table(afhi));
430         for (i = 0; i <= afhi->chunks_total; i++)
431                 afhi->chunk_table[i] = read_u32(buf + 4 * i);
432 }
433
434 /**
435  * Get the row of the audio file table corresponding to the given path.
436  *
437  * \param path The full path of the audio file.
438  * \param row Result pointer.
439  *
440  * \return Standard.
441  */
442 int aft_get_row_of_path(const char *path, struct osl_row **row)
443 {
444         struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
445
446         return osl(osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row));
447 }
448
449 /**
450  * Get the row of the audio file table corresponding to the given hash value.
451  *
452  * \param hash The hash value of the desired audio file.
453  * \param row Result pointer.
454  *
455  * \return Standard.
456  */
457 static int aft_get_row_of_hash(unsigned char *hash, struct osl_row **row)
458 {
459         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
460         return osl(osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row));
461 }
462
463 /*
464  * Get the audio file selector info object of a row.
465  *
466  * \param row Pointer to a row in the audio file table.
467  * \param obj Result pointer.
468  *
469  * \return Standard.
470  */
471 static int get_afsi_object_of_row(const struct osl_row *row,
472                 struct osl_object *obj)
473 {
474         return osl(osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj));
475 }
476
477 /**
478  * Get the osl object holding the audio file selector info, given a path.
479  *
480  *
481  * \param path The full path of the audio file.
482  * \param obj Result pointer.
483  *
484  * \return Positive on success, negative on errors.
485  */
486 static int get_afsi_object_of_path(const char *path, struct osl_object *obj)
487 {
488         struct osl_row *row;
489         int ret = aft_get_row_of_path(path, &row);
490         if (ret < 0)
491                 return ret;
492         return get_afsi_object_of_row(row, obj);
493 }
494
495 /**
496  * Get the audio file selector info, given a row of the audio file table.
497  *
498  * \param row Pointer to a row in the audio file table.
499  * \param afsi Result pointer.
500  *
501  * \return Positive on success, negative on errors.
502  */
503 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
504 {
505         struct osl_object obj;
506         int ret = get_afsi_object_of_row(row, &obj);
507         if (ret < 0)
508                 return ret;
509         return load_afsi(afsi, &obj);
510 }
511
512 /*
513  * Get the audio file selector info, given the path of an audio table.
514  *
515  * \param path The full path of the audio file.
516  * \param afsi Result pointer.
517  *
518  * \return Standard.
519  */
520 static int get_afsi_of_path(const char *path, struct afs_info *afsi)
521 {
522         struct osl_object obj;
523         int ret = get_afsi_object_of_path(path, &obj);
524         if (ret < 0)
525                 return ret;
526         return load_afsi(afsi, &obj);
527 }
528
529 /**
530  * Get the path of an audio file, given a row of the audio file table.
531  *
532  * \param row Pointer to a row in the audio file table.
533  * \param path Result pointer.
534  *
535  * The result is a pointer to mmapped data. The caller must not attempt
536  * to free it.
537  *
538  * \return Standard.
539  */
540 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
541 {
542         struct osl_object path_obj;
543         int ret = osl(osl_get_object(audio_file_table, row, AFTCOL_PATH,
544                 &path_obj));
545         if (ret < 0)
546                 return ret;
547         *path = path_obj.data;
548         return 1;
549 }
550
551 /**
552  * Get the object containing the hash value of an audio file, given a row.
553  *
554  * \param row Pointer to a row of the audio file table.
555  * \param obj Result pointer.
556  *
557  * \return The return value of the underlying call to osl_get_object().
558  *
559  * \sa get_hash_of_row().
560  */
561 static int get_hash_object_of_aft_row(const struct osl_row *row,
562                 struct osl_object *obj)
563 {
564         return osl(osl_get_object(audio_file_table, row, AFTCOL_HASH, obj));
565 }
566
567 /**
568  * Get the hash value of an audio file, given a row of the audio file table.
569  *
570  * \param row Pointer to a row of the audio file table.
571  * \param hash Result pointer.
572  *
573  * \a hash points to mapped data and must not be freed by the caller.
574  *
575  * \return The return value of the underlying call to
576  * get_hash_object_of_aft_row().
577  */
578 static int get_hash_of_row(const struct osl_row *row, unsigned char **hash)
579 {
580         struct osl_object obj;
581         int ret = get_hash_object_of_aft_row(row, &obj);
582
583         if (ret < 0)
584                 return ret;
585         *hash = obj.data;
586         return 1;
587 }
588
589 /**
590  * Get the audio format handler info, given a row of the audio file table.
591  *
592  * \param row Pointer to a row of the audio file table.
593  * \param afhi Result pointer.
594  *
595  * \return The return value of the underlying call to osl_get_object().
596  *
597  * \sa get_chunk_table_of_row().
598  */
599 int get_afhi_of_row(const struct osl_row *row, struct afh_info *afhi)
600 {
601         struct osl_object obj;
602         int ret = osl(osl_get_object(audio_file_table, row, AFTCOL_AFHI,
603                 &obj));
604         if (ret < 0)
605                 return ret;
606         load_afhi(obj.data, afhi);
607         return 1;
608 }
609
610 /* returns shmid on success */
611 static int save_afd(struct audio_file_data *afd)
612 {
613         size_t size = sizeof(*afd) + sizeof_chunk_table(&afd->afhi);
614         int shmid, ret = shm_new(size);
615         void *shm_afd;
616         char *buf;
617
618         if (ret < 0)
619                 return ret;
620         shmid = ret;
621         ret = shm_attach(shmid, ATTACH_RW, &shm_afd);
622         if (ret < 0)
623                 goto err;
624         buf = shm_afd;
625         buf += sizeof(*afd);
626         afd->max_chunk_size = save_chunk_table(&afd->afhi, buf);
627         *(struct audio_file_data *)shm_afd = *afd;
628         shm_detach(shm_afd);
629         return shmid;
630 err:
631         shm_destroy(shmid);
632         return ret;
633 }
634
635 /**
636  * Extract a afd stored in a shared memory area.
637  *
638  * Attach the shared memory area given by \a shmid, load the audio file data
639  * stored therein and detach the area afterwards.  Called by vss, after
640  * receiving a positive response to the request for the next audio file.
641  +
642  * \param shmid The identifier of the shared memory area containing the afd.
643  * \param afd Result pointer.
644  *
645  * \return Standard.
646  */
647 int load_afd(int shmid, struct audio_file_data *afd)
648 {
649         void *shm_afd;
650         int ret;
651
652         ret = shm_attach(shmid, ATTACH_RO, &shm_afd);
653         if (ret < 0)
654                 return ret;
655         *afd = *(struct audio_file_data *)shm_afd;
656         load_chunk_table(&afd->afhi, shm_afd + sizeof(*afd));
657         shm_detach(shm_afd);
658         return 1;
659 }
660
661 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
662         time_t current_time, enum ls_listing_mode lm)
663 {
664         struct tm *tm;
665         /*
666          * Omit year but show time if the given value is closer to the current
667          * time than this many seconds.
668          */
669         const time_t m = 6 * 30 * 24 * 3600; /* six months */
670
671         tm = localtime((time_t *)seconds);
672         if (!tm)
673                 return -E_LOCALTIME;
674         if (lm == LS_MODE_MBOX) {
675                 if (!strftime(buf, size, "%c", tm))
676                         return -E_STRFTIME;
677                 return 1;
678         }
679         if (*seconds > current_time - m && *seconds < current_time + m) {
680                 if (!strftime(buf, size, "%b %e %k:%M", tm))
681                         return -E_STRFTIME;
682                 return 1;
683         }
684         /*
685          * If the given time is more than six month away from the current time,
686          * we print only the year. The additional space character in the format
687          * string below makes the formated date align nicely with dates that
688          * contain the time (those written by the above strftime() statement).
689          */
690         if (!strftime(buf, size, "%b %e  %Y", tm))
691                 return -E_STRFTIME;
692         return 1;
693 }
694
695 /** Compute the number of (decimal) digits of a number. */
696 #define GET_NUM_DIGITS(x, num) { \
697         typeof((x)) _tmp = PARA_ABS(x); \
698         *num = 1; \
699         if ((_tmp)) \
700                 while ((_tmp) > 9) { \
701                         (_tmp) /= 10; \
702                         (*num)++; \
703                 } \
704         }
705
706 __a_const static short unsigned get_duration_width(int seconds)
707 {
708         short unsigned width;
709         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
710
711         if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
712                 return 4 + (mins > 9);
713         /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
714         GET_NUM_DIGITS(hours, &width);
715         return width + 6;
716 }
717
718 static void get_duration_buf(int seconds, char *buf, struct ls_options *opts)
719 {
720         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
721         short unsigned max_width;
722
723         if (!hours) { /* m:ss or mm:ss */
724                 max_width = opts->mode == LS_MODE_LONG?
725                         opts->widths.duration_width : 4;
726                 sprintf(buf, "%*u:%02d", max_width - 3, mins, seconds % 60);
727         } else { /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
728                 max_width = opts->mode == LS_MODE_LONG?
729                         opts->widths.duration_width : 7;
730                 sprintf(buf, "%*u:%02u:%02d", max_width - 6, hours, mins,
731                         seconds % 60);
732         }
733 }
734
735 static int write_attribute_items(struct para_buffer *b,
736                 const char *att_bitmap, struct afs_info *afsi)
737 {
738         char *att_text;
739         int ret;
740
741         WRITE_STATUS_ITEM(b, SI_ATTRIBUTES_BITMAP, "%s\n", att_bitmap);
742         ret = get_attribute_text(&afsi->attributes, " ", &att_text);
743         if (ret < 0)
744                 return ret;
745         WRITE_STATUS_ITEM(b, SI_ATTRIBUTES_TXT, "%s\n", att_text);
746         free(att_text);
747         return ret;
748 }
749
750 static void write_lyrics_items(struct para_buffer *b, struct afs_info *afsi)
751 {
752         char *lyrics_name;
753
754         WRITE_STATUS_ITEM(b, SI_LYRICS_ID, "%u\n", afsi->lyrics_id);
755         lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
756         WRITE_STATUS_ITEM(b, SI_LYRICS_NAME, "%s\n", lyrics_name?
757                 lyrics_name : "(none)");
758 }
759
760 static void write_image_items(struct para_buffer *b, struct afs_info *afsi)
761 {
762         char *image_name;
763
764         WRITE_STATUS_ITEM(b, SI_IMAGE_ID, "%u\n", afsi->image_id);
765         img_get_name_by_id(afsi->image_id, &image_name);
766         WRITE_STATUS_ITEM(b, SI_IMAGE_NAME, "%s\n", image_name?
767                 image_name : "(none)");
768 }
769
770 static void write_filename_items(struct para_buffer *b, const char *path,
771                 bool basename)
772 {
773         char *val;
774
775         if (basename) {
776                 WRITE_STATUS_ITEM(b, SI_BASENAME, "%s\n", path);
777                 return;
778         }
779         WRITE_STATUS_ITEM(b, SI_PATH, "%s\n", path);
780         val = para_basename(path);
781         WRITE_STATUS_ITEM(b, SI_BASENAME, "%s\n", val? val : "");
782         val = para_dirname(path);
783         WRITE_STATUS_ITEM(b, SI_DIRECTORY, "%s\n", val? val : "");
784         free(val);
785 }
786
787 static int print_chunk_table(struct ls_data *d, struct para_buffer *b)
788 {
789         struct osl_object chunk_table_obj;
790         struct osl_row *aft_row;
791         int ret, i;
792         char *buf;
793
794         ret = aft_get_row_of_hash(d->hash, &aft_row);
795         if (ret < 0)
796                 return ret;
797         ret = osl(osl_open_disk_object(audio_file_table, aft_row,
798                 AFTCOL_CHUNKS, &chunk_table_obj));
799         if (ret < 0)
800                 return ret;
801         para_printf(b, "%s\n"
802                 "chunk_time: %lu:%lu\nchunk_offsets: ",
803                 d->path,
804                 (long unsigned) d->afhi.chunk_tv.tv_sec,
805                 (long unsigned) d->afhi.chunk_tv.tv_usec
806         );
807         buf = chunk_table_obj.data;
808         for (i = 0; i <= d->afhi.chunks_total; i++)
809                 para_printf(b, "%u ", (unsigned) read_u32(buf + 4 * i));
810         para_printf(b, "\n");
811         ret = 1;
812         osl_close_disk_object(&chunk_table_obj);
813         return ret;
814 }
815
816 static int print_list_item(struct ls_data *d, struct ls_options *opts,
817         struct para_buffer *b, time_t current_time)
818 {
819         const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(LS, ADMISSIBLE, opts->lpr);
820         const struct lls_opt_result *r_b = SERVER_CMD_OPT_RESULT(LS, BASENAME, opts->lpr);
821         const struct lls_opt_result *r_d = SERVER_CMD_OPT_RESULT(LS, UNIX_DATE, opts->lpr);
822         int ret;
823         char att_buf[65];
824         char last_played_time[30];
825         char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
826         struct afs_info *afsi = &d->afsi;
827         struct afh_info *afhi = &d->afhi;
828         char asc_hash[2 * HASH_SIZE + 1];
829
830         if (opts->mode == LS_MODE_SHORT) {
831                 para_printf(b, "%s\n", d->path);
832                 ret = 1;
833                 goto out;
834         }
835         if (opts->mode == LS_MODE_CHUNKS) {
836                 ret = print_chunk_table(d, b);
837                 goto out;
838         }
839         get_attribute_bitmap(&afsi->attributes, att_buf);
840         if (lls_opt_given(r_d))
841                 sprintf(last_played_time, "%llu",
842                         (long long unsigned)afsi->last_played);
843         else {
844                 ret = get_local_time(&afsi->last_played, last_played_time,
845                         sizeof(last_played_time), current_time, opts->mode);
846                 if (ret < 0)
847                         goto out;
848         }
849         get_duration_buf(afhi->seconds_total, duration_buf, opts);
850         if (opts->mode == LS_MODE_LONG) {
851                 struct ls_widths *w = &opts->widths;
852                 if (lls_opt_given(r_a))
853                         para_printf(b, "%*li ", opts->widths.score_width,
854                                 d->score);
855                 para_printf(b,
856                         "%s "   /* attributes */
857                         "%*u "  /* amp */
858                         "%*u "  /* image_id  */
859                         "%*u "  /* lyrics_id */
860                         "%*u "  /* bitrate */
861                         "%*s "  /* audio format */
862                         "%*u "  /* frequency */
863                         "%u "   /* channels */
864                         "%s "   /* duration */
865                         "%*u "  /* num_played */
866                         "%s "   /* last_played */
867                         "%s\n", /* path */
868                         att_buf,
869                         w->amp_width, afsi->amp,
870                         w->image_id_width, afsi->image_id,
871                         w->lyrics_id_width, afsi->lyrics_id,
872                         w->bitrate_width, afhi->bitrate,
873                         w->audio_format_width,
874                         audio_format_name(afsi->audio_format_id),
875                         w->frequency_width, afhi->frequency,
876                         afhi->channels,
877                         duration_buf,
878                         w->num_played_width, afsi->num_played,
879                         last_played_time,
880                         d->path
881                 );
882                 ret = 1;
883                 goto out;
884         }
885         if (opts->mode == LS_MODE_MBOX) {
886                 const char *bn = para_basename(d->path);
887                 para_printf(b,
888                         "From foo@localhost %s\n"
889                         "Received: from\nTo: bar\nFrom: a\n"
890                         "Subject: %s\n\n",
891                         last_played_time,
892                         bn? bn : "?");
893         }
894         write_filename_items(b, d->path, lls_opt_given(r_b) > 0);
895         if (lls_opt_given(r_a))
896                 WRITE_STATUS_ITEM(b, SI_SCORE, "%li\n", d->score);
897         ret = write_attribute_items(b, att_buf, afsi);
898         if (ret < 0)
899                 goto out;
900         write_image_items(b, afsi);
901         write_lyrics_items(b, afsi);
902         hash_to_asc(d->hash, asc_hash);
903         WRITE_STATUS_ITEM(b, SI_HASH, "%s\n", asc_hash);
904         WRITE_STATUS_ITEM(b, SI_BITRATE, "%dkbit/s\n", afhi->bitrate);
905         WRITE_STATUS_ITEM(b, SI_FORMAT, "%s\n",
906                 audio_format_name(afsi->audio_format_id));
907         WRITE_STATUS_ITEM(b, SI_FREQUENCY, "%dHz\n", afhi->frequency);
908         WRITE_STATUS_ITEM(b, SI_CHANNELS, "%d\n", afhi->channels);
909         WRITE_STATUS_ITEM(b, SI_DURATION, "%s\n", duration_buf);
910         WRITE_STATUS_ITEM(b, SI_SECONDS_TOTAL, "%" PRIu32 "\n",
911                 afhi->seconds_total);
912         WRITE_STATUS_ITEM(b, SI_LAST_PLAYED, "%s\n", last_played_time);
913         WRITE_STATUS_ITEM(b, SI_NUM_PLAYED, "%u\n", afsi->num_played);
914         WRITE_STATUS_ITEM(b, SI_AMPLIFICATION, "%u\n", afsi->amp);
915         WRITE_STATUS_ITEM(b, SI_CHUNK_TIME, "%lu\n", tv2ms(&afhi->chunk_tv));
916         WRITE_STATUS_ITEM(b, SI_NUM_CHUNKS, "%" PRIu32 "\n",
917                 afhi->chunks_total);
918         WRITE_STATUS_ITEM(b, SI_TECHINFO, "%s\n", afhi->techinfo);
919         WRITE_STATUS_ITEM(b, SI_ARTIST, "%s\n", afhi->tags.artist);
920         WRITE_STATUS_ITEM(b, SI_TITLE, "%s\n", afhi->tags.title);
921         WRITE_STATUS_ITEM(b, SI_YEAR, "%s\n", afhi->tags.year);
922         WRITE_STATUS_ITEM(b, SI_ALBUM, "%s\n", afhi->tags.album);
923         WRITE_STATUS_ITEM(b, SI_COMMENT, "%s\n", afhi->tags.comment);
924         if (opts->mode == LS_MODE_MBOX) {
925                 struct osl_object lyrics_def;
926                 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
927                 if (lyrics_def.data) {
928                         para_printf(b, "Lyrics:\n~~~~~~~\n%s",
929                                 (char *)lyrics_def.data);
930                         osl_close_disk_object(&lyrics_def);
931                 }
932         }
933 out:
934         return ret;
935 }
936
937 static struct ls_data status_item_ls_data;
938 static struct osl_row *current_aft_row;
939
940 static void make_inode_status_items(struct para_buffer *pb)
941 {
942         struct stat statbuf = {.st_size = 0};
943         char *path, mtime_str[30] = "\0";
944         struct tm mtime_tm;
945         int ret;
946
947         ret = get_audio_file_path_of_row(current_aft_row, &path);
948         if (ret < 0)
949                 goto out;
950         ret = stat(path, &statbuf);
951         if (ret < 0)
952                 goto out;
953         localtime_r(&statbuf.st_mtime, &mtime_tm);
954         ret = strftime(mtime_str, 29, "%b %d %Y", &mtime_tm);
955         assert(ret > 0); /* number of bytes placed in mtime_str */
956 out:
957         WRITE_STATUS_ITEM(pb, SI_MTIME, "%s\n", mtime_str);
958         WRITE_STATUS_ITEM(pb, SI_FILE_SIZE, "%ld\n", statbuf.st_size / 1024);
959 }
960
961 static int make_status_items(void)
962 {
963         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
964         char *argv[] = {"ls", "--path", "--admissible",
965                 "--listing-mode=verbose"};
966         struct ls_options opts = {.mode = LS_MODE_VERBOSE};
967         struct para_buffer pb = {.max_size = shm_get_shmmax() - 1};
968         time_t current_time;
969         int ret;
970
971         ret = lls_parse(ARRAY_SIZE(argv), argv, cmd, &opts.lpr, NULL);
972         assert(ret >= 0);
973         time(&current_time);
974         ret = print_list_item(&status_item_ls_data, &opts, &pb, current_time);
975         if (ret < 0)
976                 goto out;
977         make_inode_status_items(&pb);
978         free(status_items);
979         status_items = pb.buf;
980
981         memset(&pb, 0, sizeof(pb));
982         pb.max_size = shm_get_shmmax() - 1;
983         pb.flags = PBF_SIZE_PREFIX;
984         ret = print_list_item(&status_item_ls_data, &opts, &pb, current_time);
985         if (ret < 0) {
986                 free(status_items);
987                 status_items = NULL;
988                 return ret;
989         }
990         make_inode_status_items(&pb);
991         free(parser_friendly_status_items);
992         parser_friendly_status_items = pb.buf;
993         ret = 1;
994 out:
995         lls_free_parse_result(opts.lpr, cmd);
996         return ret;
997 }
998
999 /**
1000  * Open the audio file with highest score and set up an afd structure.
1001  *
1002  * \param afd Result pointer.
1003  *
1004  * On success, the numplayed field of the audio file selector info is increased
1005  * and the lastplayed time is set to the current time. Finally, the score of
1006  * the audio file is updated.
1007  *
1008  * \return Positive shmid on success, negative on errors.
1009  */
1010 int open_and_update_audio_file(struct audio_file_data *afd)
1011 {
1012         unsigned char file_hash[HASH_SIZE];
1013         struct osl_object afsi_obj;
1014         struct afs_info new_afsi;
1015         int ret;
1016         struct afsi_change_event_data aced;
1017         struct osl_object map, chunk_table_obj;
1018         struct ls_data *d = &status_item_ls_data;
1019 again:
1020         ret = score_get_best(&current_aft_row, &d->score);
1021         if (ret < 0)
1022                 return ret;
1023         ret = get_hash_of_row(current_aft_row, &d->hash);
1024         if (ret < 0)
1025                 return ret;
1026         ret = get_audio_file_path_of_row(current_aft_row, &d->path);
1027         if (ret < 0)
1028                 return ret;
1029         PARA_NOTICE_LOG("%s\n", d->path);
1030         ret = get_afsi_object_of_row(current_aft_row, &afsi_obj);
1031         if (ret < 0)
1032                 return ret;
1033         ret = load_afsi(&d->afsi, &afsi_obj);
1034         if (ret < 0)
1035                 return ret;
1036         ret = get_afhi_of_row(current_aft_row, &afd->afhi);
1037         if (ret < 0)
1038                 return ret;
1039         d->afhi = afd->afhi;
1040         d->afhi.chunk_table = afd->afhi.chunk_table = NULL;
1041         ret = osl(osl_open_disk_object(audio_file_table, current_aft_row,
1042                 AFTCOL_CHUNKS, &chunk_table_obj));
1043         if (ret < 0)
1044                 return ret;
1045         ret = mmap_full_file(d->path, O_RDONLY, &map.data, &map.size, &afd->fd);
1046         if (ret < 0)
1047                 goto out;
1048         hash_function(map.data, map.size, file_hash);
1049         ret = hash_compare(file_hash, d->hash);
1050         para_munmap(map.data, map.size);
1051         if (ret) {
1052                 ret = -E_HASH_MISMATCH;
1053                 goto out;
1054         }
1055         new_afsi = d->afsi;
1056         new_afsi.num_played++;
1057         new_afsi.last_played = time(NULL);
1058         save_afsi(&new_afsi, &afsi_obj); /* in-place update */
1059
1060         afd->audio_format_id = d->afsi.audio_format_id;
1061         load_chunk_table(&afd->afhi, chunk_table_obj.data);
1062         aced.aft_row = current_aft_row;
1063         aced.old_afsi = &d->afsi;
1064         /*
1065          * No need to update the status items as the AFSI_CHANGE event will
1066          * recreate them.
1067          */
1068         ret = afs_event(AFSI_CHANGE, NULL, &aced);
1069         if (ret < 0)
1070                 goto out;
1071         ret = save_afd(afd);
1072 out:
1073         free(afd->afhi.chunk_table);
1074         osl_close_disk_object(&chunk_table_obj);
1075         if (ret < 0) {
1076                 PARA_ERROR_LOG("%s: %s\n", d->path, para_strerror(-ret));
1077                 ret = score_delete(current_aft_row);
1078                 if (ret >= 0)
1079                         goto again;
1080         }
1081         return ret;
1082 }
1083
1084 static int ls_audio_format_compare(const void *a, const void *b)
1085 {
1086         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1087         return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
1088 }
1089
1090 static int ls_duration_compare(const void *a, const void *b)
1091 {
1092         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1093         return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
1094 }
1095
1096 static int ls_bitrate_compare(const void *a, const void *b)
1097 {
1098         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1099         return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
1100 }
1101
1102 static int ls_lyrics_id_compare(const void *a, const void *b)
1103 {
1104         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1105         return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
1106 }
1107
1108 static int ls_image_id_compare(const void *a, const void *b)
1109 {
1110         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1111         return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
1112 }
1113
1114 static int ls_channels_compare(const void *a, const void *b)
1115 {
1116         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1117         return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
1118 }
1119
1120 static int ls_frequency_compare(const void *a, const void *b)
1121 {
1122         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1123         return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
1124 }
1125
1126 static int ls_num_played_compare(const void *a, const void *b)
1127 {
1128         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1129         return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
1130 }
1131
1132 static int ls_last_played_compare(const void *a, const void *b)
1133 {
1134         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1135         return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
1136 }
1137
1138 static int ls_score_compare(const void *a, const void *b)
1139 {
1140         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1141         return NUM_COMPARE(d1->score, d2->score);
1142 }
1143
1144 static int ls_path_compare(const void *a, const void *b)
1145 {
1146         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1147         return strcmp(d1->path, d2->path);
1148 }
1149
1150 static inline bool admissible_only(struct ls_options *opts)
1151 {
1152         return SERVER_CMD_OPT_GIVEN(LS, ADMISSIBLE, opts->lpr)
1153                 || opts->sorting == LS_SORT_BY_SCORE;
1154 }
1155
1156 static int sort_matching_paths(struct ls_options *options)
1157 {
1158         const struct lls_opt_result *r_b = SERVER_CMD_OPT_RESULT(LS, BASENAME,
1159                 options->lpr);
1160         size_t nmemb = options->num_matching_paths;
1161         size_t size = sizeof(*options->data_ptr);
1162         int (*compar)(const void *, const void *);
1163         int i;
1164
1165         options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
1166         for (i = 0; i < nmemb; i++)
1167                 options->data_ptr[i] = options->data + i;
1168
1169         /* In these cases the array is already sorted */
1170         if (admissible_only(options)) {
1171                 if (options->sorting == LS_SORT_BY_SCORE)
1172                         return 1;
1173         } else {
1174                 if (options->sorting == LS_SORT_BY_PATH && !lls_opt_given(r_b))
1175                         return 1;
1176         }
1177
1178         switch (options->sorting) {
1179         case LS_SORT_BY_PATH:
1180                 compar = ls_path_compare; break;
1181         case LS_SORT_BY_SCORE:
1182                 compar = ls_score_compare; break;
1183         case LS_SORT_BY_LAST_PLAYED:
1184                 compar = ls_last_played_compare; break;
1185         case LS_SORT_BY_NUM_PLAYED:
1186                 compar = ls_num_played_compare; break;
1187         case LS_SORT_BY_FREQUENCY:
1188                 compar = ls_frequency_compare; break;
1189         case LS_SORT_BY_CHANNELS:
1190                 compar = ls_channels_compare; break;
1191         case LS_SORT_BY_IMAGE_ID:
1192                 compar = ls_image_id_compare; break;
1193         case LS_SORT_BY_LYRICS_ID:
1194                 compar = ls_lyrics_id_compare; break;
1195         case LS_SORT_BY_BITRATE:
1196                 compar = ls_bitrate_compare; break;
1197         case LS_SORT_BY_DURATION:
1198                 compar = ls_duration_compare; break;
1199         case LS_SORT_BY_AUDIO_FORMAT:
1200                 compar = ls_audio_format_compare; break;
1201         default:
1202                 return -E_BAD_SORT;
1203         }
1204         qsort(options->data_ptr, nmemb, size, compar);
1205         return 1;
1206 }
1207
1208 /* row is either an aft_row or a row of the score table */
1209 /* TODO: Only compute widths if we need them */
1210 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1211 {
1212         int ret, i;
1213         struct ls_options *options = ls_opts;
1214         bool basename_given = SERVER_CMD_OPT_GIVEN(LS, BASENAME, options->lpr) > 0;
1215         struct ls_data *d;
1216         struct ls_widths *w;
1217         unsigned short num_digits;
1218         unsigned tmp, num_inputs;
1219         struct osl_row *aft_row;
1220         long score;
1221         char *path;
1222
1223         if (admissible_only(options)) {
1224                 ret = get_score_and_aft_row(row, &score, &aft_row);
1225                 if (ret < 0)
1226                         return ret;
1227         } else {
1228                 aft_row = row;
1229                 score = 0;
1230         }
1231         ret = get_audio_file_path_of_row(aft_row, &path);
1232         if (ret < 0)
1233                 return ret;
1234         if (basename_given) {
1235                 char *p = strrchr(path, '/');
1236                 if (p)
1237                         path = p + 1;
1238         }
1239         num_inputs = lls_num_inputs(options->lpr);
1240         if (num_inputs > 0) {
1241                 for (i = 0; i < num_inputs; i++) {
1242                         ret = fnmatch(lls_input(i, options->lpr), path, 0);
1243                         if (!ret)
1244                                 break;
1245                         if (ret == FNM_NOMATCH)
1246                                 continue;
1247                         return -E_FNMATCH;
1248                 }
1249                 if (i >= num_inputs) /* no match */
1250                         return 1;
1251         }
1252         tmp = options->num_matching_paths++;
1253         if (options->num_matching_paths > options->array_size) {
1254                 options->array_size++;
1255                 options->array_size *= 2;
1256                 options->data = para_realloc(options->data, options->array_size
1257                         * sizeof(*options->data));
1258         }
1259         d = options->data + tmp;
1260         ret = get_afsi_of_row(aft_row, &d->afsi);
1261         if (ret < 0)
1262                 return ret;
1263         ret = get_afhi_of_row(aft_row, &d->afhi);
1264         if (ret < 0)
1265                 return ret;
1266         d->path = path;
1267         ret = get_hash_of_row(aft_row, &d->hash);
1268         if (ret < 0)
1269                 goto err;
1270         w = &options->widths;
1271         GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1272         w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1273         GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1274         w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1275         GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1276         w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1277         GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1278         w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1279         GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1280         w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1281         /* get the number of chars to print this amount of time */
1282         num_digits = get_duration_width(d->afhi.seconds_total);
1283         w->duration_width = PARA_MAX(w->duration_width, num_digits);
1284         GET_NUM_DIGITS(d->afsi.amp, &num_digits);
1285         w->amp_width = PARA_MAX(w->amp_width, num_digits);
1286         num_digits = strlen(audio_format_name(d->afsi.audio_format_id));
1287         w->audio_format_width = PARA_MAX(w->audio_format_width, num_digits);
1288         if (admissible_only(options)) {
1289                 GET_NUM_DIGITS(score, &num_digits);
1290                 num_digits++; /* add one for the sign (space or "-") */
1291                 w->score_width = PARA_MAX(w->score_width, num_digits);
1292                 d->score = score;
1293         }
1294         return 1;
1295 err:
1296         return ret;
1297 }
1298
1299 static int com_ls_callback(struct afs_callback_arg *aca)
1300 {
1301         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
1302         struct ls_options *opts = aca->query.data;
1303         int i = 0, ret;
1304         time_t current_time;
1305         const struct lls_opt_result *r_r;
1306
1307         ret = lls_deserialize_parse_result(
1308                 (char *)aca->query.data + sizeof(*opts), cmd, &opts->lpr);
1309         assert(ret >= 0);
1310         r_r = SERVER_CMD_OPT_RESULT(LS, REVERSE, opts->lpr);
1311
1312         aca->pbout.flags = (opts->mode == LS_MODE_PARSER)? PBF_SIZE_PREFIX : 0;
1313         if (admissible_only(opts))
1314                 ret = admissible_file_loop(opts, prepare_ls_row);
1315         else
1316                 ret = osl(osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1317                         prepare_ls_row));
1318         if (ret < 0)
1319                 goto out;
1320         if (opts->num_matching_paths == 0) {
1321                 ret = lls_num_inputs(opts->lpr) > 0? -E_NO_MATCH : 0;
1322                 goto out;
1323         }
1324         ret = sort_matching_paths(opts);
1325         if (ret < 0)
1326                 goto out;
1327         time(&current_time);
1328         if (lls_opt_given(r_r))
1329                 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1330                         ret = print_list_item(opts->data_ptr[i], opts,
1331                                 &aca->pbout, current_time);
1332                         if (ret < 0)
1333                                 goto out;
1334                 }
1335         else
1336                 for (i = 0; i < opts->num_matching_paths; i++) {
1337                         ret = print_list_item(opts->data_ptr[i], opts,
1338                                 &aca->pbout, current_time);
1339                         if (ret < 0)
1340                                 goto out;
1341                 }
1342 out:
1343         lls_free_parse_result(opts->lpr, cmd);
1344         free(opts->data);
1345         free(opts->data_ptr);
1346         return ret;
1347 }
1348
1349 /* TODO: flags -h (sort by hash) */
1350 static int com_ls(struct command_context *cc, struct lls_parse_result *lpr)
1351 {
1352         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
1353         struct ls_options *opts;
1354         struct osl_object query;
1355         const struct lls_opt_result *r_l = SERVER_CMD_OPT_RESULT(LS, LISTING_MODE,
1356                 lpr);
1357         const struct lls_opt_result *r_s = SERVER_CMD_OPT_RESULT(LS, SORT, lpr);
1358         int ret;
1359         char *slpr;
1360
1361         ret = lls_serialize_parse_result(lpr, cmd, NULL, &query.size);
1362         assert(ret >= 0);
1363         query.size += sizeof(*opts);
1364         query.data = para_malloc(query.size);
1365         opts = query.data;
1366         memset(opts, 0, sizeof(*opts));
1367         slpr = query.data + sizeof(*opts);
1368         ret = lls_serialize_parse_result(lpr, cmd, &slpr, NULL);
1369         assert(ret >= 0);
1370         opts->mode = LS_MODE_SHORT;
1371         opts->sorting = LS_SORT_BY_PATH;
1372         if (lls_opt_given(r_l)) {
1373                 const char *val = lls_string_val(0, r_l);
1374                 if (!strcmp(val, "l") || !strcmp(val, "long"))
1375                         opts->mode = LS_MODE_LONG;
1376                 else if (!strcmp(val, "s") || !strcmp(val, "short"))
1377                         opts->mode = LS_MODE_SHORT;
1378                 else if (!strcmp(val, "v") || !strcmp(val, "verbose"))
1379                         opts->mode = LS_MODE_VERBOSE;
1380                 else if (!strcmp(val, "m") || !strcmp(val, "mbox"))
1381                         opts->mode = LS_MODE_MBOX;
1382                 else if (!strcmp(val, "c") || !strcmp(val, "chunk-table"))
1383                         opts->mode = LS_MODE_MBOX;
1384                 else if (!strcmp(val, "p") || !strcmp(val, "parser-friendly"))
1385                         opts->mode = LS_MODE_PARSER;
1386                 else {
1387                         ret = -E_AFT_SYNTAX;
1388                         goto out;
1389                 }
1390         }
1391         if (lls_opt_given(r_s)) {
1392                 const char *val = lls_string_val(0, r_s);
1393                 if (!strcmp(val, "p") || !strcmp(val, "path"))
1394                         opts->sorting = LS_SORT_BY_PATH;
1395                 else if (!strcmp(val, "s") || !strcmp(val, "score"))
1396                         opts->sorting = LS_SORT_BY_SCORE;
1397                 else if (!strcmp(val, "l") || !strcmp(val, "lastplayed"))
1398                         opts->sorting = LS_SORT_BY_LAST_PLAYED;
1399                 else if (!strcmp(val, "n") || !strcmp(val, "numplayed"))
1400                         opts->sorting = LS_SORT_BY_NUM_PLAYED;
1401                 else if (!strcmp(val, "f") || !strcmp(val, "frquency"))
1402                         opts->sorting = LS_SORT_BY_FREQUENCY;
1403                 else if (!strcmp(val, "c") || !strcmp(val, "channels"))
1404                         opts->sorting = LS_SORT_BY_CHANNELS;
1405                 else if (!strcmp(val, "i") || !strcmp(val, "image-id"))
1406                         opts->sorting = LS_SORT_BY_IMAGE_ID;
1407                 else if (!strcmp(val, "y") || !strcmp(val, "lyrics-id"))
1408                         opts->sorting = LS_SORT_BY_LYRICS_ID;
1409                 else if (!strcmp(val, "b") || !strcmp(val, "bitrate"))
1410                         opts->sorting = LS_SORT_BY_BITRATE;
1411                 else if (!strcmp(val, "d") || !strcmp(val, "duration"))
1412                         opts->sorting = LS_SORT_BY_DURATION;
1413                 else if (!strcmp(val, "a") || !strcmp(val, "audio-format"))
1414                         opts->sorting = LS_SORT_BY_AUDIO_FORMAT;
1415                 else {
1416                         ret = -E_AFT_SYNTAX;
1417                         goto out;
1418                 }
1419         }
1420         ret = send_callback_request(com_ls_callback, &query,
1421                 afs_cb_result_handler, cc);
1422 out:
1423         free(query.data);
1424         return ret;
1425 }
1426 EXPORT_SERVER_CMD_HANDLER(ls);
1427
1428 /**
1429  * Call the given function for each file in the audio file table.
1430  *
1431  * \param private_data An arbitrary data pointer, passed to \a func.
1432  * \param func The custom function to be called.
1433  *
1434  * \return Standard.
1435  */
1436 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1437 {
1438         return osl(osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1439                 func));
1440 }
1441
1442 static int find_hash_sister(unsigned char *hash, struct osl_row **result)
1443 {
1444         int ret = aft_get_row_of_hash(hash, result);
1445
1446         if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1447                 return 0;
1448         return ret;
1449 }
1450
1451 static int find_path_brother(const char *path, struct osl_row **result)
1452 {
1453         int ret = aft_get_row_of_path(path, result);
1454
1455         if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1456                 return 0;
1457         return ret;
1458 }
1459
1460 /** The format of the data stored by save_audio_file_data(). */
1461 enum com_add_buffer_offsets {
1462         /* afhi (if present) starts at this offset. */
1463         CAB_AFHI_OFFSET_POS = 0,
1464         /** Start of the chunk table (if present). */
1465         CAB_CHUNKS_OFFSET_POS = 4,
1466         /** Start of the (serialized) lopsub parse result. */
1467         CAB_LPR_OFFSET = 8,
1468         /** Audio format id. */
1469         CAB_AUDIO_FORMAT_ID_OFFSET = 12,
1470         /** The hash of the audio file being added. */
1471         CAB_HASH_OFFSET = 13,
1472         /** Start of the path of the audio file. */
1473         CAB_PATH_OFFSET = (CAB_HASH_OFFSET + HASH_SIZE),
1474 };
1475
1476 /*
1477  * Store the given data to a single buffer. Doesn't need the audio file selector
1478  * info struct as the server knows it as well.
1479  *
1480  * It's OK to call this with afhi == NULL. In this case, the audio format
1481  * handler info won't be stored in the buffer.
1482  */
1483 static void save_add_callback_buffer(unsigned char *hash, const char *path,
1484                 struct afh_info *afhi, const char *slpr, size_t slpr_size,
1485                 uint8_t audio_format_num, struct osl_object *obj)
1486 {
1487         size_t path_len = strlen(path) + 1;
1488         size_t afhi_size = sizeof_afhi_buf(afhi);
1489         size_t size = CAB_PATH_OFFSET + path_len + afhi_size
1490                 + sizeof_chunk_table(afhi) + slpr_size;
1491         char *buf = para_malloc(size);
1492         uint32_t pos;
1493
1494         assert(size <= ~(uint32_t)0);
1495         write_u8(buf + CAB_AUDIO_FORMAT_ID_OFFSET, audio_format_num);
1496         memcpy(buf + CAB_HASH_OFFSET, hash, HASH_SIZE);
1497         strcpy(buf + CAB_PATH_OFFSET, path);
1498         pos = CAB_PATH_OFFSET + path_len;
1499         write_u32(buf + CAB_AFHI_OFFSET_POS, pos);
1500         save_afhi(afhi, buf + pos);
1501         pos += afhi_size;
1502         write_u32(buf + CAB_CHUNKS_OFFSET_POS, pos);
1503         if (afhi) {
1504                 save_chunk_table(afhi, buf + pos);
1505                 pos += sizeof_chunk_table(afhi);
1506         }
1507         write_u32(buf + CAB_LPR_OFFSET, pos);
1508         memcpy(buf + pos, slpr, slpr_size);
1509         assert(pos + slpr_size == size);
1510         obj->data = buf;
1511         obj->size = size;
1512 }
1513
1514 /*
1515
1516 Overview of the add command.
1517
1518 Input: What was passed to the callback by the command handler.
1519 ~~~~~~
1520 HS:     Hash sister. Whether an audio file with identical hash
1521         already exists in the osl database.
1522
1523 PB:     Path brother. Whether a file with the given path exists
1524         in the table.
1525
1526 F:      Force flag given. Whether add was called with -f.
1527
1528 output: Action performed by the callback.
1529 ~~~~~~~
1530 AFHI:   Whether afhi and chunk table are computed and sent.
1531 ACTION: Table modifications to be done by the callback.
1532
1533 +----+----+---+------+---------------------------------------------------+
1534 | HS | PB | F | AFHI | ACTION
1535 +----+----+---+------+---------------------------------------------------+
1536 | Y  |  Y | Y |  Y   | if HS != PB: remove PB. HS: force afhi update,
1537 |                    | update path, keep afsi
1538 +----+----+---+------+---------------------------------------------------+
1539 | Y  |  Y | N |  N   | if HS == PB: do not send callback request at all.
1540 |                    | otherwise: remove PB, HS: update path, keep afhi,
1541 |                    | afsi.
1542 +----+----+---+------+---------------------------------------------------+
1543 | Y  |  N | Y |  Y   | (rename) force afhi update of HS, update path of
1544 |                    | HS, keep afsi
1545 +----+----+---+------+---------------------------------------------------+
1546 | Y  |  N | N |  N   | (file rename) update path of HS, keep afsi, afhi
1547 +----+----+---+------+---------------------------------------------------+
1548 | N  |  Y | Y |  Y   | (file change) update afhi, hash, of PB, keep afsi
1549 |                    | (force has no effect)
1550 +----+----+---+------+---------------------------------------------------+
1551 | N  |  Y | N |  Y   | (file change) update afhi, hash of PB, keep afsi
1552 +----+----+---+------+---------------------------------------------------+
1553 | N  |  N | Y |  Y   | (new file) create new entry (force has no effect)
1554 +----+----+---+------+---------------------------------------------------+
1555 |  N |  N | N |  Y   | (new file) create new entry
1556 +----+----+---+------+---------------------------------------------------+
1557
1558 Notes:
1559
1560         afhi <=> force or no HS
1561         F => AFHI
1562
1563 */
1564
1565 static int com_add_callback(struct afs_callback_arg *aca)
1566 {
1567         char *buf = aca->query.data, *path;
1568         struct osl_row *pb, *aft_row;
1569         struct osl_row *hs;
1570         struct osl_object objs[NUM_AFT_COLUMNS];
1571         unsigned char *hash;
1572         char asc[2 * HASH_SIZE + 1];
1573         int ret;
1574         char afsi_buf[AFSI_SIZE];
1575         char *slpr = buf + read_u32(buf + CAB_LPR_OFFSET);
1576         struct afs_info default_afsi = {.last_played = 0};
1577         uint16_t afhi_offset, chunks_offset;
1578         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(ADD);
1579         const struct lls_opt_result *r_f, *r_v;
1580
1581         ret = lls_deserialize_parse_result(slpr, cmd, &aca->lpr);
1582         assert(ret >= 0);
1583         r_f = SERVER_CMD_OPT_RESULT(ADD, FORCE, aca->lpr);
1584         r_v = SERVER_CMD_OPT_RESULT(ADD, VERBOSE, aca->lpr);
1585
1586         hash = (unsigned char *)buf + CAB_HASH_OFFSET;
1587         hash_to_asc(hash, asc);
1588         objs[AFTCOL_HASH].data = buf + CAB_HASH_OFFSET;
1589         objs[AFTCOL_HASH].size = HASH_SIZE;
1590
1591         path = buf + CAB_PATH_OFFSET;
1592         objs[AFTCOL_PATH].data = path;
1593         objs[AFTCOL_PATH].size = strlen(path) + 1;
1594
1595         PARA_INFO_LOG("request to add %s\n", path);
1596         ret = find_hash_sister(hash, &hs);
1597         if (ret < 0)
1598                 goto out;
1599         ret = find_path_brother(path, &pb);
1600         if (ret < 0)
1601                 goto out;
1602         if (hs && pb && hs == pb && !lls_opt_given(r_f)) {
1603                 if (lls_opt_given(r_v))
1604                         para_printf(&aca->pbout, "ignoring duplicate\n");
1605                 ret = 1;
1606                 goto out;
1607         }
1608         if (hs && hs != pb) {
1609                 struct osl_object obj;
1610                 if (pb) { /* hs trumps pb, remove pb */
1611                         if (lls_opt_given(r_v))
1612                                 para_printf(&aca->pbout, "removing %s\n", path);
1613                         ret = afs_event(AUDIO_FILE_REMOVE, &aca->pbout, pb);
1614                         if (ret < 0)
1615                                 goto out;
1616                         ret = osl(osl_del_row(audio_file_table, pb));
1617                         if (ret < 0)
1618                                 goto out;
1619                         pb = NULL;
1620                 }
1621                 /* file rename, update hs' path */
1622                 if (lls_opt_given(r_v)) {
1623                         ret = osl(osl_get_object(audio_file_table, hs,
1624                                 AFTCOL_PATH, &obj));
1625                         if (ret < 0)
1626                                 goto out;
1627                         para_printf(&aca->pbout, "renamed from %s\n",
1628                                 (char *)obj.data);
1629                 }
1630                 ret = osl(osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1631                         &objs[AFTCOL_PATH]));
1632                 if (ret < 0)
1633                         goto out;
1634                 ret = afs_event(AUDIO_FILE_RENAME, &aca->pbout, hs);
1635                 if (ret < 0)
1636                         goto out;
1637                 if (!lls_opt_given(r_f))
1638                         goto out;
1639         }
1640         /* no hs or force mode, child must have sent afhi */
1641         afhi_offset = read_u32(buf + CAB_AFHI_OFFSET_POS);
1642         chunks_offset = read_u32(buf + CAB_CHUNKS_OFFSET_POS);
1643
1644         objs[AFTCOL_AFHI].data = buf + afhi_offset;
1645         objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1646         ret = -E_NO_AFHI;
1647         if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1648                 goto out;
1649         objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1650         objs[AFTCOL_CHUNKS].size = aca->query.size - chunks_offset;
1651         if (pb && !hs) { /* update pb's hash */
1652                 char old_asc[2 * HASH_SIZE + 1];
1653                 unsigned char *old_hash;
1654                 ret = get_hash_of_row(pb, &old_hash);
1655                 if (ret < 0)
1656                         goto out;
1657                 hash_to_asc(old_hash, old_asc);
1658                 if (lls_opt_given(r_v))
1659                         para_printf(&aca->pbout, "file change: %s -> %s\n",
1660                                 old_asc, asc);
1661                 ret = osl(osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1662                         &objs[AFTCOL_HASH]));
1663                 if (ret < 0)
1664                         goto out;
1665         }
1666         if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1667                 struct osl_row *row = pb? pb : hs;
1668                 /* update afhi and chunk_table */
1669                 if (lls_opt_given(r_v))
1670                         para_printf(&aca->pbout,
1671                                 "updating afhi and chunk table\n");
1672                 ret = osl(osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1673                         &objs[AFTCOL_AFHI]));
1674                 if (ret < 0)
1675                         goto out;
1676                 ret = osl(osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1677                         &objs[AFTCOL_CHUNKS]));
1678                 if (ret < 0)
1679                         goto out;
1680                 ret = afs_event(AFHI_CHANGE, &aca->pbout, row);
1681                 goto out;
1682         }
1683         /* new entry, use default afsi */
1684         if (lls_opt_given(r_v))
1685                 para_printf(&aca->pbout, "new file\n");
1686         default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1687         default_afsi.audio_format_id = read_u8(buf + CAB_AUDIO_FORMAT_ID_OFFSET);
1688
1689         objs[AFTCOL_AFSI].data = &afsi_buf;
1690         objs[AFTCOL_AFSI].size = AFSI_SIZE;
1691         save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1692         ret = osl(osl_add_and_get_row(audio_file_table, objs, &aft_row));
1693         if (ret < 0)
1694                 goto out;
1695         ret = afs_event(AUDIO_FILE_ADD, &aca->pbout, aft_row);
1696 out:
1697         if (ret < 0)
1698                 para_printf(&aca->pbout, "could not add %s\n", path);
1699         lls_free_parse_result(aca->lpr, cmd);
1700         return ret;
1701 }
1702
1703 /* Used by com_add(). */
1704 struct private_add_data {
1705         /* The pointer passed to the original command handler. */
1706         struct command_context *cc;
1707         /* Contains the flags given at the command line. */
1708         struct lls_parse_result *lpr;
1709         /* Serialized lopsub parse result. */
1710         char *slpr;
1711         /* Number of bytes. */
1712         size_t slpr_size;
1713 };
1714
1715 static int path_brother_callback(struct afs_callback_arg *aca)
1716 {
1717         char *path = aca->query.data;
1718         struct osl_row *path_brother;
1719         int ret = find_path_brother(path, &path_brother);
1720         if (ret <= 0)
1721                 return ret;
1722         return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, (char *)&path_brother,
1723                 sizeof(path_brother));
1724 }
1725
1726 static int hash_sister_callback(struct afs_callback_arg *aca)
1727 {
1728         unsigned char *hash = aca->query.data;
1729         struct osl_row *hash_sister;
1730         int ret = find_hash_sister(hash, &hash_sister);
1731
1732         if (ret <= 0)
1733                 return ret;
1734         return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, (char *)&hash_sister,
1735                 sizeof(hash_sister));
1736 }
1737
1738 static int get_row_pointer_from_result(struct osl_object *result,
1739                 __a_unused uint8_t band, void *private)
1740 {
1741         struct osl_row **row = private;
1742
1743         if (band == SBD_OUTPUT)
1744                 *row = *(struct osl_row **)(result->data);
1745         return 1;
1746 }
1747
1748 static int add_one_audio_file(const char *path, void *private_data)
1749 {
1750         int ret, send_ret = 1, fd;
1751         uint8_t format_num = -1;
1752         struct private_add_data *pad = private_data;
1753         struct afh_info afhi, *afhi_ptr = NULL;
1754         struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1755         struct osl_object map, obj = {.data = NULL}, query;
1756         unsigned char hash[HASH_SIZE];
1757         bool a_given = SERVER_CMD_OPT_GIVEN(ADD, ALL, pad->lpr);
1758         bool f_given = SERVER_CMD_OPT_GIVEN(ADD, FORCE, pad->lpr);
1759         bool l_given = SERVER_CMD_OPT_GIVEN(ADD, LAZY, pad->lpr);
1760         bool v_given = SERVER_CMD_OPT_GIVEN(ADD, VERBOSE, pad->lpr);
1761
1762         ret = guess_audio_format(path);
1763         if (ret < 0 && !a_given) {
1764                 ret = 0;
1765                 goto out_free;
1766         }
1767         query.data = (char *)path;
1768         query.size = strlen(path) + 1;
1769         ret = send_callback_request(path_brother_callback, &query,
1770                 get_row_pointer_from_result, &pb);
1771         if (ret < 0 && ret != -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1772                 goto out_free;
1773         ret = 1;
1774         if (pb && l_given) { /* lazy is really cheap */
1775                 if (v_given)
1776                         send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1777                                 "lazy-ignore: %s\n", path);
1778                 goto out_free;
1779         }
1780         /* We still want to add this file. Compute its hash. */
1781         ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, &fd);
1782         if (ret < 0)
1783                 goto out_free;
1784         hash_function(map.data, map.size, hash);
1785
1786         /* Check whether the database contains a file with the same hash. */
1787         query.data = hash;
1788         query.size = HASH_SIZE;
1789         ret = send_callback_request(hash_sister_callback, &query,
1790                 get_row_pointer_from_result, &hs);
1791         if (ret < 0)
1792                 goto out_unmap;
1793         /* Return success if we already know this file. */
1794         ret = 1;
1795         if (pb && hs && hs == pb && !f_given) {
1796                 if (v_given)
1797                         send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1798                                 "%s exists, not forcing update\n", path);
1799                 goto out_unmap;
1800         }
1801         /*
1802          * We won't recalculate the audio format info and the chunk table if
1803          * there is a hash sister and FORCE was not given.
1804          */
1805         if (!hs || f_given) {
1806                 ret = compute_afhi(path, map.data, map.size, fd, &afhi);
1807                 if (ret < 0)
1808                         goto out_unmap;
1809                 format_num = ret;
1810                 afhi_ptr = &afhi;
1811         }
1812         munmap(map.data, map.size);
1813         close(fd);
1814         if (v_given) {
1815                 send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1816                         "adding %s\n", path);
1817                 if (send_ret < 0)
1818                         goto out_free;
1819         }
1820         save_add_callback_buffer(hash, path, afhi_ptr, pad->slpr,
1821                 pad->slpr_size, format_num, &obj);
1822         /* Ask afs to consider this entry for adding. */
1823         ret = send_callback_request(com_add_callback, &obj,
1824                 afs_cb_result_handler, pad->cc);
1825         goto out_free;
1826
1827 out_unmap:
1828         close(fd);
1829         munmap(map.data, map.size);
1830 out_free:
1831         if (ret < 0 && send_ret >= 0)
1832                 send_ret = send_sb_va(&pad->cc->scc, SBD_ERROR_LOG,
1833                         "failed to add %s (%s)\n", path, para_strerror(-ret));
1834         free(obj.data);
1835         clear_afhi(afhi_ptr);
1836         /* Stop adding files only on send errors. */
1837         return send_ret;
1838 }
1839
1840 static int com_add(struct command_context *cc, struct lls_parse_result *lpr)
1841 {
1842         int i, ret;
1843         struct private_add_data pad = {.cc = cc, .lpr = lpr};
1844         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(ADD);
1845         unsigned num_inputs;
1846         char *errctx;
1847
1848         ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
1849         if (ret < 0) {
1850                 send_errctx(cc, errctx);
1851                 return ret;
1852         }
1853         ret = lls_serialize_parse_result(lpr, cmd, &pad.slpr, &pad.slpr_size);
1854         assert(ret >= 0);
1855         num_inputs = lls_num_inputs(lpr);
1856         for (i = 0; i < num_inputs; i++) {
1857                 char *path;
1858                 ret = verify_path(lls_input(i, lpr), &path);
1859                 if (ret < 0) {
1860                         ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s: %s\n",
1861                                 lls_input(i, lpr), para_strerror(-ret));
1862                         if (ret < 0)
1863                                 goto out;
1864                         continue;
1865                 }
1866                 if (ret == 1) /* directory */
1867                         ret = for_each_file_in_dir(path, add_one_audio_file,
1868                                 &pad);
1869                 else /* regular file */
1870                         ret = add_one_audio_file(path, &pad);
1871                 if (ret < 0) {
1872                         send_sb_va(&cc->scc, SBD_OUTPUT, "%s: %s\n", path,
1873                                 para_strerror(-ret));
1874                         free(path);
1875                         return ret;
1876                 }
1877                 free(path);
1878         }
1879         ret = 1;
1880 out:
1881         free(pad.slpr);
1882         return ret;
1883 }
1884 EXPORT_SERVER_CMD_HANDLER(add);
1885
1886 /**
1887  * Flags used by the touch command.
1888  *
1889  * \sa com_touch().
1890  */
1891 enum touch_flags {
1892         /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1893         TOUCH_FLAG_FNM_PATHNAME = 1,
1894         /** Activates verbose mode. */
1895         TOUCH_FLAG_VERBOSE = 2
1896 };
1897
1898 static int touch_audio_file(__a_unused struct osl_table *table,
1899                 struct osl_row *row, const char *name, void *data)
1900 {
1901         struct afs_callback_arg *aca = data;
1902         bool v_given = SERVER_CMD_OPT_GIVEN(TOUCH, VERBOSE, aca->lpr);
1903         const struct lls_opt_result *r_n, *r_l, *r_i, *r_y, *r_a;
1904         int ret;
1905         struct osl_object obj;
1906         struct afs_info old_afsi, new_afsi;
1907         bool no_options;
1908         struct afsi_change_event_data aced;
1909
1910         r_n = SERVER_CMD_OPT_RESULT(TOUCH, NUMPLAYED, aca->lpr);
1911         r_l = SERVER_CMD_OPT_RESULT(TOUCH, LASTPLAYED, aca->lpr);
1912         r_i = SERVER_CMD_OPT_RESULT(TOUCH, IMAGE_ID, aca->lpr);
1913         r_y = SERVER_CMD_OPT_RESULT(TOUCH, LYRICS_ID, aca->lpr);
1914         r_a = SERVER_CMD_OPT_RESULT(TOUCH, AMP, aca->lpr);
1915         no_options = !lls_opt_given(r_n) && !lls_opt_given(r_l) && !lls_opt_given(r_i)
1916                 && !lls_opt_given(r_y) && !lls_opt_given(r_a);
1917
1918         ret = get_afsi_object_of_row(row, &obj);
1919         if (ret < 0) {
1920                 para_printf(&aca->pbout, "cannot touch %s\n", name);
1921                 return ret;
1922         }
1923         ret = load_afsi(&old_afsi, &obj);
1924         if (ret < 0) {
1925                 para_printf(&aca->pbout, "cannot touch %s\n", name);
1926                 return ret;
1927         }
1928         new_afsi = old_afsi;
1929         if (no_options) {
1930                 new_afsi.num_played++;
1931                 new_afsi.last_played = time(NULL);
1932                 if (v_given)
1933                         para_printf(&aca->pbout, "%s: num_played = %u, "
1934                                 "last_played = now()\n", name,
1935                                 new_afsi.num_played);
1936         } else {
1937                 if (lls_opt_given(r_l))
1938                         new_afsi.last_played = lls_uint64_val(0, r_l);
1939                 if (lls_opt_given(r_n))
1940                         new_afsi.num_played = lls_uint32_val(0, r_n);
1941                 if (lls_opt_given(r_i))
1942                         new_afsi.image_id = lls_uint32_val(0, r_i);
1943                 if (lls_opt_given(r_y))
1944                         new_afsi.lyrics_id = lls_uint32_val(0, r_y);
1945                 if (lls_opt_given(r_a))
1946                         new_afsi.amp = lls_uint32_val(0, r_a);
1947                 if (v_given)
1948                         para_printf(&aca->pbout, "touching %s\n", name);
1949         }
1950         save_afsi(&new_afsi, &obj); /* in-place update */
1951         aced.aft_row = row;
1952         aced.old_afsi = &old_afsi;
1953         return afs_event(AFSI_CHANGE, &aca->pbout, &aced);
1954 }
1955
1956 static int com_touch_callback(struct afs_callback_arg *aca)
1957 {
1958         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(TOUCH);
1959         bool p_given;
1960         const struct lls_opt_result *r_i, *r_y;
1961         int ret;
1962         struct pattern_match_data pmd = {
1963                 .table = audio_file_table,
1964                 .loop_col_num = AFTCOL_HASH,
1965                 .match_col_num = AFTCOL_PATH,
1966                 .data = aca,
1967                 .action = touch_audio_file
1968         };
1969
1970         ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
1971         assert(ret >= 0);
1972         pmd.lpr = aca->lpr;
1973
1974         r_i = SERVER_CMD_OPT_RESULT(TOUCH, IMAGE_ID, aca->lpr);
1975         if (lls_opt_given(r_i)) {
1976                 uint32_t id = lls_uint32_val(0, r_i);
1977                 ret = img_get_name_by_id(id, NULL);
1978                 if (ret < 0) {
1979                         para_printf(&aca->pbout, "invalid image ID: %u\n", id);
1980                         return ret;
1981                 }
1982         }
1983         r_y = SERVER_CMD_OPT_RESULT(TOUCH, LYRICS_ID, aca->lpr);
1984         if (lls_opt_given(r_y)) {
1985                 uint32_t id = lls_uint32_val(0, r_y);
1986                 ret = lyr_get_name_by_id(id, NULL);
1987                 if (ret < 0) {
1988                         para_printf(&aca->pbout, "invalid lyrics ID: %u\n", id);
1989                         return ret;
1990                 }
1991         }
1992         p_given = SERVER_CMD_OPT_GIVEN(TOUCH, PATHNAME_MATCH, aca->lpr);
1993         if (p_given)
1994                 pmd.fnmatch_flags |= FNM_PATHNAME;
1995         ret = for_each_matching_row(&pmd);
1996         if (ret >= 0 && pmd.num_matches == 0)
1997                 ret = -E_NO_MATCH;
1998         lls_free_parse_result(aca->lpr, cmd);
1999         return ret;
2000 }
2001
2002 static int com_touch(struct command_context *cc, struct lls_parse_result *lpr)
2003 {
2004         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(TOUCH);
2005         int ret;
2006         char *errctx;
2007
2008         ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
2009         if (ret < 0) {
2010                 send_errctx(cc, errctx);
2011                 return ret;
2012         }
2013         return send_lls_callback_request(com_touch_callback, cmd, lpr, cc);
2014 }
2015 EXPORT_SERVER_CMD_HANDLER(touch);
2016
2017 static int remove_audio_file(__a_unused struct osl_table *table,
2018                 struct osl_row *row, const char *name, void *data)
2019 {
2020         struct afs_callback_arg *aca = data;
2021         bool v_given = SERVER_CMD_OPT_GIVEN(RM, VERBOSE, aca->lpr);
2022         int ret;
2023
2024         if (v_given)
2025                 para_printf(&aca->pbout, "removing %s\n", name);
2026         ret = afs_event(AUDIO_FILE_REMOVE, &aca->pbout, row);
2027         if (ret < 0)
2028                 return ret;
2029         ret = osl(osl_del_row(audio_file_table, row));
2030         if (ret < 0)
2031                 para_printf(&aca->pbout, "cannot remove %s\n", name);
2032         return ret;
2033 }
2034
2035 static int com_rm_callback(struct afs_callback_arg *aca)
2036 {
2037         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(RM);
2038         int ret;
2039         struct pattern_match_data pmd = {
2040                 .table = audio_file_table,
2041                 .loop_col_num = AFTCOL_HASH,
2042                 .match_col_num = AFTCOL_PATH,
2043                 .data = aca,
2044                 .action = remove_audio_file
2045         };
2046         bool v_given, p_given, f_given;
2047
2048         ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2049         assert(ret >= 0);
2050         pmd.lpr = aca->lpr;
2051         v_given = SERVER_CMD_OPT_GIVEN(RM, VERBOSE, aca->lpr);
2052         p_given = SERVER_CMD_OPT_GIVEN(RM, PATHNAME_MATCH, aca->lpr);
2053         f_given = SERVER_CMD_OPT_GIVEN(RM, FORCE, aca->lpr);
2054
2055         if (p_given)
2056                 pmd.fnmatch_flags |= FNM_PATHNAME;
2057         ret = for_each_matching_row(&pmd);
2058         if (ret < 0)
2059                 goto out;
2060         if (pmd.num_matches == 0) {
2061                 if (!f_given)
2062                         ret = -E_NO_MATCH;
2063         } else if (v_given)
2064                 para_printf(&aca->pbout, "removed %u file(s)\n",
2065                         pmd.num_matches);
2066 out:
2067         lls_free_parse_result(aca->lpr, cmd);
2068         return ret;
2069 }
2070
2071 /* TODO options: -r (recursive) */
2072 static int com_rm(struct command_context *cc, struct lls_parse_result *lpr)
2073 {
2074         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(RM);
2075         char *errctx;
2076         int ret;
2077
2078         ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
2079         if (ret < 0) {
2080                 send_errctx(cc, errctx);
2081                 return ret;
2082         }
2083         return send_lls_callback_request(com_rm_callback, cmd, lpr, cc);
2084 }
2085 EXPORT_SERVER_CMD_HANDLER(rm);
2086
2087 /** Data passed to the action handler of com_cpsi(). */
2088 struct cpsi_action_data {
2089         /** Values are copied from here. */
2090         struct afs_info source_afsi;
2091         /** What was passed to com_cpsi_callback(). */
2092         struct afs_callback_arg *aca;
2093         bool copy_all;
2094 };
2095
2096 static int copy_selector_info(__a_unused struct osl_table *table,
2097                 struct osl_row *row, const char *name, void *data)
2098 {
2099         struct cpsi_action_data *cad = data;
2100         struct osl_object target_afsi_obj;
2101         int ret;
2102         struct afs_info old_afsi, target_afsi;
2103         struct afsi_change_event_data aced;
2104         bool a_given, y_given, i_given, l_given, n_given, v_given;
2105
2106         a_given = SERVER_CMD_OPT_GIVEN(CPSI, ATTRIBUTE_BITMAP, cad->aca->lpr);
2107         y_given = SERVER_CMD_OPT_GIVEN(CPSI, LYRICS_ID, cad->aca->lpr);
2108         i_given = SERVER_CMD_OPT_GIVEN(CPSI, IMAGE_ID, cad->aca->lpr);
2109         l_given = SERVER_CMD_OPT_GIVEN(CPSI, LASTPLAYED, cad->aca->lpr);
2110         n_given = SERVER_CMD_OPT_GIVEN(CPSI, NUMPLAYED, cad->aca->lpr);
2111         v_given = SERVER_CMD_OPT_GIVEN(CPSI, VERBOSE, cad->aca->lpr);
2112
2113         ret = get_afsi_object_of_row(row, &target_afsi_obj);
2114         if (ret < 0)
2115                 return ret;
2116         load_afsi(&target_afsi, &target_afsi_obj);
2117         old_afsi = target_afsi;
2118         if (cad->copy_all || y_given)
2119                 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2120         if (cad->copy_all || i_given)
2121                 target_afsi.image_id = cad->source_afsi.image_id;
2122         if (cad->copy_all || l_given)
2123                 target_afsi.last_played = cad->source_afsi.last_played;
2124         if (cad->copy_all || n_given)
2125                 target_afsi.num_played = cad->source_afsi.num_played;
2126         if (cad->copy_all || a_given)
2127                 target_afsi.attributes = cad->source_afsi.attributes;
2128         save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2129         if (v_given)
2130                 para_printf(&cad->aca->pbout, "copied afsi to %s\n", name);
2131         aced.aft_row = row;
2132         aced.old_afsi = &old_afsi;
2133         return afs_event(AFSI_CHANGE, &cad->aca->pbout, &aced);
2134 }
2135
2136 static int com_cpsi_callback(struct afs_callback_arg *aca)
2137 {
2138         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(CPSI);
2139         bool a_given, y_given, i_given, l_given, n_given, v_given;
2140         struct cpsi_action_data cad = {.aca = aca};
2141         int ret;
2142         struct pattern_match_data pmd = {
2143                 .table = audio_file_table,
2144                 .loop_col_num = AFTCOL_HASH,
2145                 .match_col_num = AFTCOL_PATH,
2146                 .input_skip = 1, /* skip first argument (source file) */
2147                 .data = &cad,
2148                 .action = copy_selector_info
2149         };
2150
2151         ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2152         assert(ret >= 0);
2153         pmd.lpr = aca->lpr;
2154
2155         a_given = SERVER_CMD_OPT_GIVEN(CPSI, ATTRIBUTE_BITMAP, aca->lpr);
2156         y_given = SERVER_CMD_OPT_GIVEN(CPSI, LYRICS_ID, aca->lpr);
2157         i_given = SERVER_CMD_OPT_GIVEN(CPSI, IMAGE_ID, aca->lpr);
2158         l_given = SERVER_CMD_OPT_GIVEN(CPSI, LASTPLAYED, aca->lpr);
2159         n_given = SERVER_CMD_OPT_GIVEN(CPSI, NUMPLAYED, aca->lpr);
2160         v_given = SERVER_CMD_OPT_GIVEN(CPSI, VERBOSE, aca->lpr);
2161         cad.copy_all = !a_given && !y_given && !i_given && !l_given && !n_given;
2162
2163         ret = get_afsi_of_path(lls_input(0, aca->lpr), &cad.source_afsi);
2164         if (ret < 0)
2165                 goto out;
2166         ret = for_each_matching_row(&pmd);
2167         if (ret < 0)
2168                 goto out;
2169         if (pmd.num_matches > 0) {
2170                 if (v_given)
2171                         para_printf(&aca->pbout, "updated afsi of %u file(s)\n",
2172                                 pmd.num_matches);
2173         } else
2174                 ret = -E_NO_MATCH;
2175 out:
2176         lls_free_parse_result(aca->lpr, cmd);
2177         return ret;
2178 }
2179
2180 static int com_cpsi(struct command_context *cc, struct lls_parse_result *lpr)
2181 {
2182         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(CPSI);
2183         char *errctx;
2184         int ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
2185         if (ret < 0) {
2186                 send_errctx(cc, errctx);
2187                 return ret;
2188         }
2189         return send_lls_callback_request(com_cpsi_callback, cmd, lpr, cc);
2190 }
2191 EXPORT_SERVER_CMD_HANDLER(cpsi);
2192
2193 struct change_atts_data {
2194         uint64_t add_mask, del_mask;
2195         struct afs_callback_arg *aca;
2196 };
2197
2198 static int change_atts(__a_unused struct osl_table *table,
2199                 struct osl_row *row, __a_unused const char *name, void *data)
2200 {
2201         int ret;
2202         struct osl_object obj;
2203         struct afs_info old_afsi, new_afsi;
2204         struct afsi_change_event_data aced = {
2205                 .aft_row = row,
2206                 .old_afsi = &old_afsi
2207         };
2208         struct change_atts_data *cad = data;
2209
2210         ret = get_afsi_object_of_row(row, &obj);
2211         if (ret < 0)
2212                 return ret;
2213         ret = load_afsi(&old_afsi, &obj);
2214         if (ret < 0)
2215                 return ret;
2216         new_afsi = old_afsi;
2217         new_afsi.attributes |= cad->add_mask;
2218         new_afsi.attributes &= ~cad->del_mask;
2219         save_afsi(&new_afsi, &obj); /* in-place update */
2220         return afs_event(AFSI_CHANGE, &cad->aca->pbout, &aced);
2221 }
2222
2223 static int com_setatt_callback(struct afs_callback_arg *aca)
2224 {
2225         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SETATT);
2226         int i, ret;
2227         struct change_atts_data cad = {.aca = aca};
2228         struct pattern_match_data pmd = {
2229                 .table = audio_file_table,
2230                 .loop_col_num = AFTCOL_HASH,
2231                 .match_col_num = AFTCOL_PATH,
2232                 .pm_flags = PM_SKIP_EMPTY_NAME,
2233                 .data = &cad,
2234                 .action = change_atts
2235         };
2236         unsigned num_inputs;
2237
2238         ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2239         assert(ret >= 0);
2240         pmd.lpr = aca->lpr;
2241
2242         num_inputs = lls_num_inputs(aca->lpr);
2243         for (i = 0; i < num_inputs; i++) {
2244                 unsigned char bitnum;
2245                 uint64_t one = 1;
2246                 const char *arg = lls_input(i, aca->lpr);
2247                 char c, *p;
2248                 size_t len = strlen(arg);
2249
2250                 ret = -E_ATTR_SYNTAX;
2251                 if (len == 0)
2252                         goto out;
2253                 c = arg[len - 1];
2254                 if (c != '+' && c != '-') {
2255                         if (cad.add_mask == 0 && cad.del_mask == 0)
2256                                 goto out; /* no attribute modifier given */
2257                         goto set_atts;
2258                 }
2259                 p = para_malloc(len);
2260                 memcpy(p, arg, len - 1);
2261                 p[len - 1] = '\0';
2262                 ret = get_attribute_bitnum_by_name(p, &bitnum);
2263                 free(p);
2264                 if (ret < 0) {
2265                         para_printf(&aca->pbout, "invalid argument: %s\n", arg);
2266                         goto out;
2267                 }
2268                 if (c == '+')
2269                         cad.add_mask |= (one << bitnum);
2270                 else
2271                         cad.del_mask |= (one << bitnum);
2272         }
2273         /* no pattern given */
2274         ret = -E_ATTR_SYNTAX;
2275         goto out;
2276 set_atts:
2277         pmd.input_skip = i;
2278         ret = for_each_matching_row(&pmd);
2279         if (ret >= 0 && pmd.num_matches == 0)
2280                 ret = -E_NO_MATCH;
2281 out:
2282         lls_free_parse_result(aca->lpr, cmd);
2283         return ret;
2284 }
2285
2286 static int com_setatt(struct command_context *cc, struct lls_parse_result *lpr)
2287 {
2288         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SETATT);
2289         char *errctx;
2290         int ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
2291
2292         if (ret < 0) {
2293                 send_errctx(cc, errctx);
2294                 return ret;
2295         }
2296         return send_lls_callback_request(com_setatt_callback, cmd, lpr, cc);
2297 }
2298 EXPORT_SERVER_CMD_HANDLER(setatt);
2299
2300 static int afs_stat_callback(struct afs_callback_arg *aca)
2301 {
2302         int *parser_friendly = aca->query.data;
2303         char *buf = *parser_friendly?
2304                 parser_friendly_status_items : status_items;
2305
2306         if (!buf)
2307                 return 0;
2308         return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, buf, strlen(buf));
2309 }
2310
2311 /**
2312  * Get the current afs status items from the afs process and send it.
2313  *
2314  * \param cc The command context, used e.g. for data encryption.
2315  * \param parser_friendly Whether parser-friendly output format should be used.
2316  *
2317  * As the contents of the afs status items change in time and the command
2318  * handler only has a COW version created at fork time, it can not send
2319  * up-to-date afs status items directly. Therefore the usual callback mechanism
2320  * is used to pass the status items from the afs process to the command handler
2321  * via a shared memory area and a pipe.
2322  *
2323  * \return The return value of the underlying call to \ref send_callback_request().
2324  */
2325 int send_afs_status(struct command_context *cc, int parser_friendly)
2326 {
2327         struct osl_object query = {.data = &parser_friendly,
2328                 .size = sizeof(parser_friendly)};
2329
2330         return send_callback_request(afs_stat_callback, &query,
2331                 afs_cb_result_handler, cc);
2332 }
2333
2334 /* returns success on non-fatal errors to keep the loop going */
2335 static int check_audio_file(struct osl_row *row, void *data)
2336 {
2337         char *path;
2338         struct para_buffer *pb = data;
2339         struct stat statbuf;
2340         int ret = get_audio_file_path_of_row(row, &path);
2341         struct afs_info afsi;
2342         char *blob_name;
2343
2344         if (ret < 0) {
2345                 para_printf(pb, "%s\n", para_strerror(-ret));
2346                 return ret;
2347         }
2348         if (stat(path, &statbuf) < 0)
2349                 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2350         else if (!S_ISREG(statbuf.st_mode))
2351                 para_printf(pb, "%s: not a regular file\n", path);
2352         ret = get_afsi_of_row(row, &afsi);
2353         if (ret < 0) {
2354                 para_printf(pb, "%s: %s\n", path, para_strerror(-ret));
2355                 return 1;
2356         }
2357         ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2358         if (ret < 0)
2359                 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2360                         para_strerror(-ret));
2361         ret = img_get_name_by_id(afsi.image_id, &blob_name);
2362         if (ret < 0)
2363                 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2364                         para_strerror(-ret));
2365         return 0;
2366 }
2367
2368 /**
2369  * Check the audio file table for inconsistencies.
2370  *
2371  * \param aca Only ->pbout is used for diagnostics.
2372  *
2373  * \return Standard. Inconsistencies are reported but not regarded as an error.
2374  *
2375  * \sa com_check().
2376  */
2377 int aft_check_callback(struct afs_callback_arg *aca)
2378 {
2379         para_printf(&aca->pbout, "checking audio file table...\n");
2380         return audio_file_loop(&aca->pbout, check_audio_file);
2381 }
2382
2383 struct aft_check_atts_data {
2384         uint64_t att_mask;
2385         struct para_buffer *pb;
2386 };
2387
2388 static int check_atts_of_audio_file(struct osl_row *row, void *data)
2389 {
2390         struct aft_check_atts_data *acad = data;
2391         int ret;
2392         struct afs_info afsi;
2393         char *path;
2394         uint64_t bad_bits;
2395
2396         ret = get_afsi_of_row(row, &afsi);
2397         if (ret < 0) {
2398                 para_printf(acad->pb, "cannot get afsi\n");
2399                 return ret;
2400         }
2401         bad_bits = afsi.attributes & ~acad->att_mask;
2402         if (bad_bits == 0) /* OK */
2403                 return 0;
2404         ret = get_audio_file_path_of_row(row, &path);
2405         if (ret < 0) {
2406                 para_printf(acad->pb, "cannot get path\n");
2407                 return ret;
2408         }
2409         para_printf(acad->pb, "invalid attribute bits (%" PRIu64 "): %s\n",
2410                 bad_bits, path);
2411         /* return success to keep looping */
2412         return 1;
2413 }
2414
2415 /**
2416  * Iterate over all audio files and check the attribute bit mask.
2417  *
2418  * \param att_mask The mask of all valid attributes.
2419  * \param pb Used for reporting inconsistencies.
2420  *
2421  * This reads the attribute bit mask of each audio file from the afs info
2422  * structure stored in the audio file table and verifies that all set bits are
2423  * also turned on in \a att_mask, i.e., correspond to an attribute of the
2424  * attribute table. Audio files for which this is not the case are reported via
2425  * \a pb.
2426  *
2427  * \return Standard. Inconsistencies are not regarded as errors.
2428  *
2429  * \sa \ref attribute_check_callback().
2430  */
2431 int aft_check_attributes(uint64_t att_mask, struct para_buffer *pb)
2432 {
2433         struct aft_check_atts_data acad = {.att_mask = att_mask, .pb = pb};
2434
2435         para_printf(pb, "checking attributes, mask: %" PRIx64 "\n", att_mask);
2436         return audio_file_loop(&acad, check_atts_of_audio_file);
2437 }
2438
2439 /**
2440  * Close the audio file table.
2441  *
2442  * \param flags Usual flags that are passed to osl_close_table().
2443  *
2444  * \sa osl_close_table().
2445  */
2446 static void aft_close(void)
2447 {
2448         osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2449         audio_file_table = NULL;
2450 }
2451
2452 /**
2453  * Open the audio file table.
2454  *
2455  * \param dir The database directory.
2456  *
2457  * \return Standard.
2458  *
2459  * \sa osl_open_table().
2460  */
2461 static int aft_open(const char *dir)
2462 {
2463         int ret;
2464
2465         audio_file_table_desc.dir = dir;
2466         ret = osl(osl_open_table(&audio_file_table_desc, &audio_file_table));
2467         if (ret >= 0) {
2468                 unsigned num;
2469                 osl_get_num_rows(audio_file_table, &num);
2470                 PARA_INFO_LOG("audio file table contains %u files\n", num);
2471                 return ret;
2472         }
2473         PARA_NOTICE_LOG("failed to open audio file table\n");
2474         audio_file_table = NULL;
2475         if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_NOENT))
2476                 return 1;
2477         return ret;
2478 }
2479
2480 static int aft_create(const char *dir)
2481 {
2482         audio_file_table_desc.dir = dir;
2483         return osl(osl_create_table(&audio_file_table_desc));
2484 }
2485
2486 static int clear_attribute(struct osl_row *row, void *data)
2487 {
2488         struct rmatt_event_data *red = data;
2489         struct afs_info afsi;
2490         struct osl_object obj;
2491         int ret = get_afsi_object_of_row(row, &obj);
2492         uint64_t mask = ~(1ULL << red->bitnum);
2493
2494         if (ret < 0)
2495                 return ret;
2496         ret = load_afsi(&afsi, &obj);
2497         if (ret < 0)
2498                 return ret;
2499         afsi.attributes &= mask;
2500         save_afsi(&afsi, &obj);
2501         return 1;
2502 }
2503
2504 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2505                 void *data)
2506 {
2507         int ret;
2508
2509         switch (event) {
2510         case ATTRIBUTE_REMOVE: {
2511                 const struct rmatt_event_data *red = data;
2512                 para_printf(pb, "clearing attribute %s (bit %u) from all "
2513                         "entries in the audio file table\n", red->name,
2514                         red->bitnum);
2515                 return audio_file_loop(data, clear_attribute);
2516         } case AFSI_CHANGE: {
2517                 struct afsi_change_event_data *aced = data;
2518                 uint64_t old_last_played = status_item_ls_data.afsi.last_played;
2519                 if (aced->aft_row != current_aft_row)
2520                         return 0;
2521                 ret = get_afsi_of_row(aced->aft_row, &status_item_ls_data.afsi);
2522                 if (ret < 0)
2523                         return ret;
2524                 status_item_ls_data.afsi.last_played = old_last_played;
2525                 make_status_items();
2526                 return 1;
2527         } case AFHI_CHANGE: {
2528                 if (data != current_aft_row)
2529                         return 0;
2530                 ret = get_afhi_of_row(data, &status_item_ls_data.afhi);
2531                 if (ret < 0)
2532                         return ret;
2533                 make_status_items();
2534                 return 1;
2535         } default:
2536                 return 0;
2537         }
2538 }
2539
2540 /**
2541  * Initialize the audio file table.
2542  *
2543  * \param t Pointer to the structure to be initialized.
2544  */
2545 void aft_init(struct afs_table *t)
2546 {
2547         t->open = aft_open;
2548         t->close = aft_close;
2549         t->create = aft_create;
2550         t->event_handler = aft_event_handler;
2551 }