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