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