]> git.tuebingen.mpg.de Git - paraslash.git/blob - aft.c
aft: Make make_status_items() static.
[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 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
631         time_t current_time, enum ls_listing_mode lm)
632 {
633         struct tm t;
634
635         if (!localtime_r((time_t *)seconds, &t))
636                 return -E_LOCALTIME;
637         if (lm == LS_MODE_MBOX) {
638                 if (!strftime(buf, size, "%c", &t))
639                         return -E_STRFTIME;
640                 return 1;
641         }
642         if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
643                 if (!strftime(buf, size, "%b %e %k:%M", &t))
644                         return -E_STRFTIME;
645                 return 1;
646         }
647         if (!strftime(buf, size, "%b %e  %Y", &t))
648                 return -E_STRFTIME;
649         return 1;
650 }
651
652 /** Compute the number of (decimal) digits of a number. */
653 #define GET_NUM_DIGITS(x, num) { \
654         typeof((x)) _tmp = PARA_ABS(x); \
655         *num = 1; \
656         if ((_tmp)) \
657                 while ((_tmp) > 9) { \
658                         (_tmp) /= 10; \
659                         (*num)++; \
660                 } \
661         }
662
663 static short unsigned get_duration_width(int seconds)
664 {
665         short unsigned width;
666         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
667
668         if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
669                 return 4 + (mins > 9);
670         /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
671         GET_NUM_DIGITS(hours, &width);
672         return width + 6;
673 }
674
675 static void get_duration_buf(int seconds, char *buf, struct ls_options *opts)
676 {
677         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
678         short unsigned max_width;
679
680         if (!hours) { /* m:ss or mm:ss */
681                 max_width = opts->mode == LS_MODE_LONG?
682                         opts->widths.duration_width : 4;
683                 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
684         } else { /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
685                 max_width = opts->mode == LS_MODE_LONG?
686                         opts->widths.duration_width : 7;
687                 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
688                         seconds % 60);
689         }
690 }
691
692 static char *make_attribute_lines(const char *att_bitmap, struct afs_info *afsi)
693 {
694         char *att_text, *att_lines;
695
696         get_attribute_text(&afsi->attributes, " ", &att_text);
697         if (!att_text)
698                 return para_strdup(att_bitmap);
699         att_lines = make_message("%s: %s\n%s: %s",
700                 status_item_list[SI_ATTRIBUTES_BITMAP], att_bitmap,
701                 status_item_list[SI_ATTRIBUTES_TXT], att_text);
702         free(att_text);
703         return att_lines;
704 }
705
706 static char *make_lyrics_lines(struct afs_info *afsi)
707 {
708         char *lyrics_name;
709
710         lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
711         return make_message("%s: %u\n%s: %s\n",
712                 status_item_list[SI_LYRICS_ID], afsi->lyrics_id,
713                 status_item_list[SI_LYRICS_NAME], lyrics_name?
714                         lyrics_name : "(none)");
715 }
716
717 static char *make_image_lines(struct afs_info *afsi)
718 {
719         char *image_name;
720         img_get_name_by_id(afsi->image_id, &image_name);
721         return make_message("%s: %u\n%s: %s\n",
722                 status_item_list[SI_IMAGE_ID], afsi->image_id,
723                 status_item_list[SI_IMAGE_NAME], image_name?
724                         image_name : "(none)");
725 }
726
727 static char *make_filename_lines(const char *path, unsigned flags)
728 {
729         char *dirname, *ret;
730         const char *basename;
731
732         if (!(flags & LS_FLAG_FULL_PATH))
733                 return make_message("%s: %s\n",
734                         status_item_list[SI_BASENAME], path);
735         basename = para_basename(path),
736         dirname = para_dirname(path);
737         ret = make_message("%s: %s\n%s: %s\n%s: %s\n",
738                 status_item_list[SI_PATH], path,
739                 status_item_list[SI_DIRECTORY], dirname? dirname : "?",
740                 status_item_list[SI_BASENAME], basename? basename : "?");
741         free(dirname);
742         return ret;
743 }
744
745 static int print_chunk_table(struct ls_data *d, struct para_buffer *b)
746 {
747         struct osl_object chunk_table_obj;
748         struct osl_row *aft_row;
749         int ret, i;
750         char *buf;
751
752         ret = aft_get_row_of_hash(d->hash, &aft_row);
753         if (ret < 0)
754                 return ret;
755         ret = osl_open_disk_object(audio_file_table, aft_row,
756                 AFTCOL_CHUNKS, &chunk_table_obj);
757         if (ret < 0)
758                 return ret;
759         ret = para_printf(b, "%s\n"
760                 "chunk_time: %lu:%lu\nchunk_offsets: ",
761                 d->path,
762                 (long unsigned) d->afhi.chunk_tv.tv_sec,
763                 (long unsigned) d->afhi.chunk_tv.tv_usec
764         );
765         if (ret < 0)
766                 goto out;
767         buf = chunk_table_obj.data;
768         for (i = 0; i <= d->afhi.chunks_total; i++) {
769                 ret = para_printf(b, "%u ", (unsigned) read_u32(buf + 4 * i));
770                 if (ret < 0)
771                         goto out;
772         }
773         ret = para_printf(b, "\n");
774 out:
775         osl_close_disk_object(&chunk_table_obj);
776         return ret;
777 }
778
779 static int print_list_item(struct ls_data *d, struct ls_options *opts,
780         struct para_buffer *b, time_t current_time)
781 {
782         int ret;
783         char att_buf[65];
784         char last_played_time[30];
785         char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
786         char score_buf[30] = "";
787         struct afs_info *afsi = &d->afsi;
788         struct afh_info *afhi = &d->afhi;
789         struct ls_widths *w = &opts->widths;
790         int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
791         char asc_hash[2 * HASH_SIZE + 1];
792         char *att_lines, *lyrics_lines, *image_lines, *filename_lines;
793
794         if (opts->mode == LS_MODE_SHORT) {
795                 ret = para_printf(b, "%s\n", d->path);
796                 goto out;
797         }
798         if (opts->mode == LS_MODE_CHUNKS) {
799                 ret = print_chunk_table(d, b);
800                 goto out;
801         }
802         get_attribute_bitmap(&afsi->attributes, att_buf);
803         ret = get_local_time(&afsi->last_played, last_played_time,
804                 sizeof(last_played_time), current_time, opts->mode);
805         if (ret < 0)
806                 goto out;
807         get_duration_buf(afhi->seconds_total, duration_buf, opts);
808         if (have_score) {
809                 if (opts->mode == LS_MODE_LONG)
810                         sprintf(score_buf, "%*li ", w->score_width, d->score);
811                 else
812                         sprintf(score_buf, "%li ", d->score);
813         }
814
815         if (opts->mode == LS_MODE_LONG) {
816                 ret = para_printf(b,
817                         "%s"    /* score */
818                         "%s "   /* attributes */
819                         "%*u "  /* amp */
820                         "%*d "  /* image_id  */
821                         "%*d "  /* lyrics_id */
822                         "%*d "  /* bitrate */
823                         "%s "   /* audio format */
824                         "%*d "  /* frequency */
825                         "%d "   /* channels */
826                         "%s "   /* duration */
827                         "%*d "  /* num_played */
828                         "%s "   /* last_played */
829                         "%s\n", /* path */
830                         score_buf,
831                         att_buf,
832                         w->amp_width, afsi->amp,
833                         w->image_id_width, afsi->image_id,
834                         w->lyrics_id_width, afsi->lyrics_id,
835                         w->bitrate_width, afhi->bitrate,
836                         audio_format_name(afsi->audio_format_id),
837                         w->frequency_width, afhi->frequency,
838                         afhi->channels,
839                         duration_buf,
840                         w->num_played_width, afsi->num_played,
841                         last_played_time,
842                         d->path
843                 );
844                 goto out;
845         }
846         hash_to_asc(d->hash, asc_hash);
847         att_lines = make_attribute_lines(att_buf, afsi);
848         lyrics_lines = make_lyrics_lines(afsi);
849         image_lines = make_image_lines(afsi);
850         filename_lines = make_filename_lines(d->path, opts->flags);
851         if (opts->mode == LS_MODE_MBOX) {
852                 const char *bn = para_basename(d->path);
853                 ret = para_printf(b,
854                         "From foo@localhost %s\n"
855                         "Received: from\nTo: bar\nFrom: a\n"
856                         "Subject: %s\n\n",
857                         last_played_time,
858                         bn? bn : "?");
859                 if (ret < 0)
860                         goto out;
861         }
862         ret = para_printf(b,
863                 "%s" /* filename stuff */
864                 "%s%s%s%s" /* score */
865                 "%s\n" /* attributes */
866                 "%s: %s\n" /* hash */
867                 "%s" /* image id, image name */
868                 "%s" /* lyrics */
869                 "%s: %dkbit/s\n" /* bitrate */
870                 "%s: %s\n" /* format */
871                 "%s: %dHz\n" /* frequency */
872                 "%s: %d\n" /* channels */
873                 "%s: %s\n" /* duration */
874                 "%s: %lu\n" /* seconds total */
875                 "%s: %s\n" /* last played time */
876                 "%s: %d\n" /* num_played */
877                 "%s: %u\n" /* ampplification */
878                 "%s" /* tag info */
879                 "%s: %lu\n" /* chunk time */
880                 "%s: %lu\n", /* num chunks */
881                 filename_lines,
882                 have_score? status_item_list[SI_SCORE] : "",
883                         have_score? ": " : "",
884                         score_buf,
885                         have_score? "\n" : "",
886                 att_lines,
887                 status_item_list[SI_HASH], asc_hash,
888                 image_lines,
889                 lyrics_lines,
890                 status_item_list[SI_BITRATE], afhi->bitrate,
891                 status_item_list[SI_FORMAT], audio_format_name(afsi->audio_format_id),
892                 status_item_list[SI_FREQUENCY], afhi->frequency,
893                 status_item_list[SI_CHANNELS], afhi->channels,
894                 status_item_list[SI_DURATION], duration_buf,
895                 status_item_list[SI_SECONDS_TOTAL], afhi->seconds_total,
896                 status_item_list[SI_LAST_PLAYED], last_played_time,
897                 status_item_list[SI_NUM_PLAYED], afsi->num_played,
898                 status_item_list[SI_AMPLIFICATION], afsi->amp,
899                 afhi->info_string,
900                 status_item_list[SI_CHUNK_TIME], tv2ms(&afhi->chunk_tv),
901                 status_item_list[SI_NUM_CHUNKS], afhi->chunks_total
902         );
903         if (ret < 0)
904                 goto out;
905         if (opts->mode == LS_MODE_MBOX) {
906                 struct osl_object lyrics_def;
907                 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
908                 if (lyrics_def.data) {
909                         ret = para_printf(b, "Lyrics:\n~~~~~~~\n%s",
910                                 (char *)lyrics_def.data);
911                         osl_close_disk_object(&lyrics_def);
912                 }
913         }
914         free(att_lines);
915         free(lyrics_lines);
916         free(image_lines);
917         free(filename_lines);
918 out:
919         free(afhi->info_string);
920         return ret;
921 }
922
923 /**
924  * Write a list of audio-file related status items with empty values.
925  *
926  * \param buf Result pointer.
927  *
928  * This is used by vss when currently no audio file is open.
929  */
930 void make_empty_status_items(char *buf)
931 {
932         sprintf(buf,
933                 "%s: \n" /* path */
934                 "%s: \n" /* dirname */
935                 "%s: \n" /* basename */
936                 "%s: \n" /* score */
937                 "%s: \n" /* attributes bitmap */
938                 "%s: \n" /* attributes txt */
939                 "%s: \n" /* hash */
940                 "%s: \n" /* image id */
941                 "%s: \n" /* image name */
942                 "%s: \n" /* lyrics id */
943                 "%s: \n" /* lyrics name */
944                 "%s: \n" /* bitrate */
945                 "%s: \n" /* format */
946                 "%s: \n" /* frequency */
947                 "%s: \n" /* channels */
948                 "%s: \n" /* duration */
949                 "%s: \n" /* seconds total */
950                 "%s: \n" /* num played */
951                 "%s: \n" /* last played */
952                 "%s: \n" /* audio file info */
953                 "%s: \n" /* taginfo1 */
954                 "%s: \n" /* taginfo2 */
955                 "%s: \n" /* amplification */
956                 ,
957                 status_item_list[SI_PATH],
958                 status_item_list[SI_DIRECTORY],
959                 status_item_list[SI_BASENAME],
960                 status_item_list[SI_SCORE],
961                 status_item_list[SI_ATTRIBUTES_BITMAP],
962                 status_item_list[SI_ATTRIBUTES_TXT],
963                 status_item_list[SI_HASH],
964                 status_item_list[SI_IMAGE_ID],
965                 status_item_list[SI_IMAGE_NAME],
966                 status_item_list[SI_LYRICS_ID],
967                 status_item_list[SI_LYRICS_NAME],
968                 status_item_list[SI_BITRATE],
969                 status_item_list[SI_FORMAT],
970                 status_item_list[SI_FREQUENCY],
971                 status_item_list[SI_CHANNELS],
972                 status_item_list[SI_DURATION],
973                 status_item_list[SI_SECONDS_TOTAL],
974                 status_item_list[SI_NUM_PLAYED],
975                 status_item_list[SI_LAST_PLAYED],
976                 status_item_list[SI_AUDIO_FILE_INFO],
977                 status_item_list[SI_TAGINFO1],
978                 status_item_list[SI_TAGINFO2],
979                 status_item_list[SI_AMPLIFICATION]
980         );
981 }
982
983 static int make_status_items(struct ls_data *d, struct para_buffer *pb)
984 {
985         struct ls_options opts = {
986                 .flags = LS_FLAG_FULL_PATH | LS_FLAG_ADMISSIBLE_ONLY,
987                 .mode = LS_MODE_VERBOSE,
988         };
989         time_t current_time;
990
991         time(&current_time);
992         return print_list_item(d, &opts, pb, current_time);
993 }
994
995 /**
996  * Mmap the given audio file and update statistics.
997  *
998  * \param aft_row Determines the audio file to be opened and updated.
999  * \param score The score of the audio file.
1000  * \param afd Result pointer.
1001  *
1002  * On success, the numplayed field of the audio file selector info is increased
1003  * and the lastplayed time is set to the current time. Finally, the score of
1004  * the audio file is updated.
1005  *
1006  * \return Positive shmid on success, negative on errors.
1007  */
1008 int open_and_update_audio_file(struct osl_row *aft_row, long score,
1009         struct audio_file_data *afd)
1010 {
1011         HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
1012         struct osl_object afsi_obj;
1013         struct afs_info old_afsi, new_afsi;
1014         int ret = get_hash_of_row(aft_row, &aft_hash);
1015         struct afsi_change_event_data aced;
1016         struct osl_object map, chunk_table_obj;
1017         char *path;
1018
1019         if (ret < 0)
1020                 return ret;
1021         ret = get_audio_file_path_of_row(aft_row, &path);
1022         if (ret < 0)
1023                 return ret;
1024         ret = get_afsi_object_of_row(aft_row, &afsi_obj);
1025         if (ret < 0)
1026                 return ret;
1027         ret = load_afsi(&old_afsi, &afsi_obj);
1028         if (ret < 0)
1029                 return ret;
1030         ret = get_afhi_of_row(aft_row, &afd->afhi);
1031         if (ret < 0)
1032                 return ret;
1033         afd->afhi.chunk_table = NULL;
1034         ret = osl_open_disk_object(audio_file_table, aft_row,
1035                 AFTCOL_CHUNKS, &chunk_table_obj);
1036         if (ret < 0)
1037                 goto err;
1038         ret = mmap_full_file(path, O_RDONLY, &map.data,
1039                 &map.size, &afd->fd);
1040         if (ret < 0)
1041                 goto err;
1042         hash_function(map.data, map.size, file_hash);
1043         ret = hash_compare(file_hash, aft_hash);
1044         para_munmap(map.data, map.size);
1045         if (ret) {
1046                 ret = -E_HASH_MISMATCH;
1047                 goto err;
1048         }
1049         new_afsi = old_afsi;
1050         new_afsi.num_played++;
1051         new_afsi.last_played = time(NULL);
1052         save_afsi(&new_afsi, &afsi_obj); /* in-place update */
1053
1054         load_chunk_table(&afd->afhi, chunk_table_obj.data);
1055         {
1056                 struct ls_data d = {
1057                         .afhi = afd->afhi, /* struct copy */
1058                         .afsi = old_afsi,
1059                         .path = path,
1060                         .score = score,
1061                         .hash = file_hash
1062                 };
1063                 struct para_buffer pb = {.max_size = VERBOSE_LS_OUTPUT_SIZE - 1};
1064                 ret = make_status_items(&d, &pb); /* frees info string */
1065                 afd->afhi.info_string = NULL;
1066                 if (ret < 0)
1067                         goto err;
1068                 strncpy(afd->verbose_ls_output, pb.buf, VERBOSE_LS_OUTPUT_SIZE);
1069                 afd->verbose_ls_output[VERBOSE_LS_OUTPUT_SIZE - 1] = '\0';
1070                 free(pb.buf);
1071         }
1072         aced.aft_row = aft_row;
1073         aced.old_afsi = &old_afsi;
1074         afs_event(AFSI_CHANGE, NULL, &aced);
1075         ret = save_afd(afd);
1076 err:
1077         free(afd->afhi.chunk_table);
1078         free(afd->afhi.info_string);
1079         osl_close_disk_object(&chunk_table_obj);
1080         return ret;
1081 }
1082
1083 static int ls_audio_format_compare(const void *a, const void *b)
1084 {
1085         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1086         return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
1087 }
1088
1089 static int ls_duration_compare(const void *a, const void *b)
1090 {
1091         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1092         return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
1093 }
1094
1095 static int ls_bitrate_compare(const void *a, const void *b)
1096 {
1097         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1098         return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
1099 }
1100
1101 static int ls_lyrics_id_compare(const void *a, const void *b)
1102 {
1103         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1104         return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
1105 }
1106
1107 static int ls_image_id_compare(const void *a, const void *b)
1108 {
1109         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1110         return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
1111 }
1112
1113 static int ls_channels_compare(const void *a, const void *b)
1114 {
1115         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1116         return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
1117 }
1118
1119 static int ls_frequency_compare(const void *a, const void *b)
1120 {
1121         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1122         return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
1123 }
1124
1125 static int ls_num_played_compare(const void *a, const void *b)
1126 {
1127         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1128         return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
1129 }
1130
1131 static int ls_last_played_compare(const void *a, const void *b)
1132 {
1133         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1134         return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
1135 }
1136
1137 static int ls_score_compare(const void *a, const void *b)
1138 {
1139         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1140         return NUM_COMPARE(d1->score, d2->score);
1141 }
1142
1143 static int ls_path_compare(const void *a, const void *b)
1144 {
1145         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1146         return strcmp(d1->path, d2->path);
1147 }
1148
1149 static int sort_matching_paths(struct ls_options *options)
1150 {
1151         size_t nmemb = options->num_matching_paths;
1152         size_t size = sizeof(*options->data_ptr);
1153         int (*compar)(const void *, const void *);
1154         int i;
1155
1156         options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
1157         for (i = 0; i < nmemb; i++)
1158                 options->data_ptr[i] = options->data + i;
1159
1160         /* In these cases the array is already sorted */
1161         if (options->sorting == LS_SORT_BY_PATH
1162                 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1163                 && (options->flags & LS_FLAG_FULL_PATH))
1164                 return 1;
1165         if (options->sorting == LS_SORT_BY_SCORE &&
1166                         options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1167                 return 1;
1168
1169         switch (options->sorting) {
1170         case LS_SORT_BY_PATH:
1171                 compar = ls_path_compare; break;
1172         case LS_SORT_BY_SCORE:
1173                 compar = ls_score_compare; break;
1174         case LS_SORT_BY_LAST_PLAYED:
1175                 compar = ls_last_played_compare; break;
1176         case LS_SORT_BY_NUM_PLAYED:
1177                 compar = ls_num_played_compare; break;
1178         case LS_SORT_BY_FREQUENCY:
1179                 compar = ls_frequency_compare; break;
1180         case LS_SORT_BY_CHANNELS:
1181                 compar = ls_channels_compare; break;
1182         case LS_SORT_BY_IMAGE_ID:
1183                 compar = ls_image_id_compare; break;
1184         case LS_SORT_BY_LYRICS_ID:
1185                 compar = ls_lyrics_id_compare; break;
1186         case LS_SORT_BY_BITRATE:
1187                 compar = ls_bitrate_compare; break;
1188         case LS_SORT_BY_DURATION:
1189                 compar = ls_duration_compare; break;
1190         case LS_SORT_BY_AUDIO_FORMAT:
1191                 compar = ls_audio_format_compare; break;
1192         default:
1193                 return -E_BAD_SORT;
1194         }
1195         qsort(options->data_ptr, nmemb, size, compar);
1196         return 1;
1197 }
1198
1199 /* row is either an aft_row or a row of the score table */
1200 /* TODO: Only compute widths if we need them */
1201 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1202 {
1203         int ret, i;
1204         struct ls_options *options = ls_opts;
1205         struct ls_data *d;
1206         struct ls_widths *w;
1207         unsigned short num_digits;
1208         unsigned tmp;
1209         struct osl_row *aft_row;
1210         long score;
1211         char *path;
1212
1213         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1214                 ret = get_score_and_aft_row(row, &score, &aft_row);
1215                 if (ret < 0)
1216                         return ret;
1217         } else
1218                 aft_row = row;
1219         ret = get_audio_file_path_of_row(aft_row, &path);
1220         if (ret < 0)
1221                 return ret;
1222         if (!(options->flags & LS_FLAG_FULL_PATH)) {
1223                 char *p = strrchr(path, '/');
1224                 if (p)
1225                         path = p + 1;
1226         }
1227         if (options->num_patterns) {
1228                 for (i = 0; i < options->num_patterns; i++) {
1229                         ret = fnmatch(options->patterns[i], path, 0);
1230                         if (!ret)
1231                                 break;
1232                         if (ret == FNM_NOMATCH)
1233                                 continue;
1234                         return -E_FNMATCH;
1235                 }
1236                 if (i >= options->num_patterns) /* no match */
1237                         return 1;
1238         }
1239         tmp = options->num_matching_paths++;
1240         if (options->num_matching_paths > options->array_size) {
1241                 options->array_size++;
1242                 options->array_size *= 2;
1243                 options->data = para_realloc(options->data, options->array_size
1244                         * sizeof(*options->data));
1245         }
1246         d = options->data + tmp;
1247         ret = get_afsi_of_row(aft_row, &d->afsi);
1248         if (ret < 0)
1249                 return ret;
1250         ret = get_afhi_of_row(aft_row, &d->afhi);
1251         if (ret < 0)
1252                 return ret;
1253         d->path = path;
1254         ret = get_hash_of_row(aft_row, &d->hash);
1255         if (ret < 0)
1256                 goto err;
1257         w = &options->widths;
1258         GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1259         w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1260         GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1261         w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1262         GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1263         w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1264         GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1265         w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1266         GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1267         w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1268         /* get the number of chars to print this amount of time */
1269         num_digits = get_duration_width(d->afhi.seconds_total);
1270         w->duration_width = PARA_MAX(w->duration_width, num_digits);
1271         GET_NUM_DIGITS(d->afsi.amp, &num_digits);
1272         w->amp_width = PARA_MAX(w->amp_width, num_digits);
1273         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1274                 GET_NUM_DIGITS(score, &num_digits);
1275                 num_digits++; /* add one for the sign (space or "-") */
1276                 w->score_width = PARA_MAX(w->score_width, num_digits);
1277                 d->score = score;
1278         }
1279         return 1;
1280 err:
1281         free(d->afhi.info_string);
1282         return ret;
1283 }
1284
1285 static void com_ls_callback(int fd, const struct osl_object *query)
1286 {
1287         struct ls_options *opts = query->data;
1288         char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1289         struct para_buffer b = {.max_size = SHMMAX,
1290                 .max_size_handler = pass_buffer_as_shm, .private_data = &fd};
1291         int i = 0, ret;
1292         time_t current_time;
1293
1294
1295         if (opts->num_patterns) {
1296                 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1297                 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1298                         opts->patterns[i] = p;
1299                         p += strlen(p) + 1;
1300                 }
1301         } else
1302                 opts->patterns = NULL;
1303         if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1304                 ret = admissible_file_loop(opts, prepare_ls_row);
1305         else
1306                 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1307                         prepare_ls_row);
1308         if (ret < 0)
1309                 goto out;
1310         if (!opts->num_matching_paths)
1311                 goto out;
1312         ret = sort_matching_paths(opts);
1313         if (ret < 0)
1314                 goto out;
1315         time(&current_time);
1316         if (opts->flags & LS_FLAG_REVERSE)
1317                 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1318                         ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1319                         if (ret < 0)
1320                                 goto out;
1321                 }
1322         else
1323                 for (i = 0; i < opts->num_matching_paths; i++) {
1324                         ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1325                         if (ret < 0)
1326                                 goto out;
1327                 }
1328 out:
1329         if (b.offset)
1330                 pass_buffer_as_shm(b.buf, b.offset, &fd);
1331         free(b.buf);
1332         free(opts->data);
1333         free(opts->data_ptr);
1334         free(opts->patterns);
1335 }
1336
1337 /*
1338  * TODO: flags -h (sort by hash)
1339  */
1340 int com_ls(int fd, int argc, char * const * const argv)
1341 {
1342         int i, ret;
1343         unsigned flags = 0;
1344         enum ls_sorting_method sort = LS_SORT_BY_PATH;
1345         enum ls_listing_mode mode = LS_MODE_SHORT;
1346         struct ls_options opts = {.patterns = NULL};
1347         struct osl_object query = {.data = &opts, .size = sizeof(opts)};
1348
1349         for (i = 1; i < argc; i++) {
1350                 const char *arg = argv[i];
1351                 if (arg[0] != '-')
1352                         break;
1353                 if (!strcmp(arg, "--")) {
1354                         i++;
1355                         break;
1356                 }
1357                 if (!strncmp(arg, "-l", 2)) {
1358                         if (!*(arg + 2)) {
1359                                 mode = LS_MODE_LONG;
1360                                 continue;
1361                         }
1362                         if (*(arg + 3))
1363                                 return -E_AFT_SYNTAX;
1364                         switch(*(arg + 2)) {
1365                         case 's':
1366                                 mode = LS_MODE_SHORT;
1367                                 continue;
1368                         case 'l':
1369                                 mode = LS_MODE_LONG;
1370                                 continue;
1371                         case 'v':
1372                                 mode = LS_MODE_VERBOSE;
1373                                 continue;
1374                         case 'm':
1375                                 mode = LS_MODE_MBOX;
1376                                 continue;
1377                         case 'c':
1378                                 mode = LS_MODE_CHUNKS;
1379                                 continue;
1380                         default:
1381                                 return -E_AFT_SYNTAX;
1382                         }
1383                 }
1384                 if (!strcmp(arg, "-p")) {
1385                         flags |= LS_FLAG_FULL_PATH;
1386                         continue;
1387                 }
1388                 if (!strcmp(arg, "-a")) {
1389                         flags |= LS_FLAG_ADMISSIBLE_ONLY;
1390                         continue;
1391                 }
1392                 if (!strcmp(arg, "-r")) {
1393                         flags |= LS_FLAG_REVERSE;
1394                         continue;
1395                 }
1396                 if (!strncmp(arg, "-s", 2)) {
1397                         if (!*(arg + 2) || *(arg + 3))
1398                                 return -E_AFT_SYNTAX;
1399                         switch(*(arg + 2)) {
1400                         case 'p':
1401                                 sort = LS_SORT_BY_PATH;
1402                                 continue;
1403                         case 's': /* -ss implies -a */
1404                                 sort = LS_SORT_BY_SCORE;
1405                                 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1406                                 continue;
1407                         case 'l':
1408                                 sort = LS_SORT_BY_LAST_PLAYED;
1409                                 continue;
1410                         case 'n':
1411                                 sort = LS_SORT_BY_NUM_PLAYED;
1412                                 continue;
1413                         case 'f':
1414                                 sort = LS_SORT_BY_FREQUENCY;
1415                                 continue;
1416                         case 'c':
1417                                 sort = LS_SORT_BY_CHANNELS;
1418                                 continue;
1419                         case 'i':
1420                                 sort = LS_SORT_BY_IMAGE_ID;
1421                                 continue;
1422                         case 'y':
1423                                 sort = LS_SORT_BY_LYRICS_ID;
1424                                 continue;
1425                         case 'b':
1426                                 sort = LS_SORT_BY_BITRATE;
1427                                 continue;
1428                         case 'd':
1429                                 sort = LS_SORT_BY_DURATION;
1430                                 continue;
1431                         case 'a':
1432                                 sort = LS_SORT_BY_AUDIO_FORMAT;
1433                                 continue;
1434                         default:
1435                                 return -E_AFT_SYNTAX;
1436                         }
1437                 }
1438                 return -E_AFT_SYNTAX;
1439         }
1440         opts.flags = flags;
1441         opts.sorting = sort;
1442         opts.mode = mode;
1443         opts.num_patterns = argc - i;
1444         ret = send_option_arg_callback_request(&query, opts.num_patterns,
1445                 argv + i, com_ls_callback, send_result, &fd);
1446         return ret;
1447 }
1448
1449 /**
1450  * Call the given function for each file in the audio file table.
1451  *
1452  * \param private_data An arbitrary data pointer, passed to \a func.
1453  * \param func The custom function to be called.
1454  *
1455  * \return The return value of the underlying call to osl_rbtree_loop().
1456  */
1457 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1458 {
1459         return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1460                 func);
1461 }
1462
1463 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1464 {
1465         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1466         struct osl_row *row;
1467
1468         osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1469         return row;
1470 }
1471
1472 /** The format of the data stored by save_audio_file_data(). */
1473 enum com_add_buffer_offsets {
1474         /** afhi (if present) starts here. */
1475         CAB_AFHI_OFFSET_POS = 0,
1476         /** Start of the chunk table (if present). */
1477         CAB_CHUNKS_OFFSET_POS = 2,
1478         /** Audio format id. */
1479         CAB_AUDIO_FORMAT_OFFSET = 4,
1480         /** Flags given to the add command. */
1481         CAB_FLAGS_OFFSET = 5,
1482         /** The hash of the audio file being added. */
1483         CAB_HASH_OFFSET = 9,
1484         /** Start of the path of the audio file. */
1485         CAB_PATH_OFFSET = (CAB_HASH_OFFSET + HASH_SIZE),
1486 };
1487
1488 /*
1489  * Store the given data to a single buffer. Doesn't need the audio file selector
1490  * info struct as the server knows it as well.
1491  *
1492  * It's OK to call this with afhi == NULL. In this case, the audio format
1493  * handler info won't be stored in the buffer.
1494  */
1495 static void save_add_callback_buffer(HASH_TYPE *hash, const char *path,
1496                 struct afh_info *afhi, uint32_t flags,
1497                 uint8_t audio_format_num, struct osl_object *obj)
1498 {
1499         size_t path_len = strlen(path) + 1;
1500         size_t afhi_size = sizeof_afhi_buf(afhi);
1501         size_t size = CAB_PATH_OFFSET + path_len + afhi_size
1502                 + sizeof_chunk_table(afhi);
1503         char *buf = para_malloc(size);
1504         uint16_t pos;
1505
1506         write_u8(buf + CAB_AUDIO_FORMAT_OFFSET, audio_format_num);
1507         write_u32(buf + CAB_FLAGS_OFFSET, flags);
1508
1509         memcpy(buf + CAB_HASH_OFFSET, hash, HASH_SIZE);
1510         strcpy(buf + CAB_PATH_OFFSET, path);
1511
1512         pos = CAB_PATH_OFFSET + path_len;
1513         PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1514         PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1515                 pos + afhi_size - 1);
1516         write_u16(buf + CAB_AFHI_OFFSET_POS, pos);
1517         save_afhi(afhi, buf + pos);
1518
1519         pos += afhi_size;
1520         PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1521         write_u16(buf + CAB_CHUNKS_OFFSET_POS, pos);
1522         if (afhi)
1523                 save_chunk_table(afhi, buf + pos);
1524         PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1525         obj->data = buf;
1526         obj->size = size;
1527 }
1528
1529 /*
1530
1531 Overview of the add command.
1532
1533 Input: What was passed to the callback by the command handler.
1534 ~~~~~~
1535 HS:     Hash sister. Whether an audio file with identical hash
1536         already exists in the osl database.
1537
1538 PB:     Path brother. Whether a file with the given path exists
1539         in the table.
1540
1541 F:      Force flag given. Whether add was called with -f.
1542
1543 output: Action performed by the callback.
1544 ~~~~~~~
1545 AFHI:   Whether afhi and chunk table are computed and sent.
1546 ACTION: Table modifications to be done by the callback.
1547
1548 +----+----+---+------+---------------------------------------------------+
1549 | HS | PB | F | AFHI | ACTION
1550 +----+----+---+------+---------------------------------------------------+
1551 | Y  |  Y | Y |  Y   | if HS != PB: remove PB. HS: force afhi update,
1552 |                    | update path, keep afsi
1553 +----+----+---+------+---------------------------------------------------+
1554 | Y  |  Y | N |  N   | if HS == PB: do not send callback request at all.
1555 |                    | otherwise: remove PB, HS: update path, keep afhi,
1556 |                    | afsi.
1557 +----+----+---+------+---------------------------------------------------+
1558 | Y  |  N | Y |  Y   | (rename) force afhi update of HS, update path of
1559 |                    | HS, keep afsi
1560 +----+----+---+------+---------------------------------------------------+
1561 | Y  |  N | N |  N   | (file rename) update path of HS, keep afsi, afhi
1562 +----+----+---+------+---------------------------------------------------+
1563 | N  |  Y | Y |  Y   | (file change) update afhi, hash, of PB, keep afsi
1564 |                    | (force has no effect)
1565 +----+----+---+------+---------------------------------------------------+
1566 | N  |  Y | N |  Y   | (file change) update afhi, hash of PB, keep afsi
1567 +----+----+---+------+---------------------------------------------------+
1568 | N  |  N | Y |  Y   | (new file) create new entry (force has no effect)
1569 +----+----+---+------+---------------------------------------------------+
1570 |  N |  N | N |  Y   | (new file) create new entry
1571 +----+----+---+------+---------------------------------------------------+
1572
1573 Notes:
1574
1575         afhi <=> force or no HS
1576         F => AFHI
1577
1578 */
1579
1580 /** Flags passed to the add command. */
1581 enum com_add_flags {
1582         /** Skip paths that exist already. */
1583         ADD_FLAG_LAZY = 1,
1584         /** Force adding. */
1585         ADD_FLAG_FORCE = 2,
1586         /** Print what is being done. */
1587         ADD_FLAG_VERBOSE = 4,
1588         /** Try to add files with unknown suffixes. */
1589         ADD_FLAG_ALL = 8,
1590 };
1591
1592 static void com_add_callback(int fd, const struct osl_object *query)
1593 {
1594         char *buf = query->data, *path;
1595         struct osl_row *pb, *aft_row;
1596         struct osl_row *hs;
1597         struct osl_object objs[NUM_AFT_COLUMNS];
1598         HASH_TYPE *hash;
1599         char asc[2 * HASH_SIZE + 1];
1600         int ret;
1601         char afsi_buf[AFSI_SIZE];
1602         uint32_t flags = read_u32(buf + CAB_FLAGS_OFFSET);
1603         struct afs_info default_afsi = {.last_played = 0};
1604         struct para_buffer msg = {.max_size = SHMMAX,
1605                 .max_size_handler = pass_buffer_as_shm, .private_data = &fd};
1606         uint16_t afhi_offset, chunks_offset;
1607
1608         hash = (HASH_TYPE *)buf + CAB_HASH_OFFSET;
1609         hash_to_asc(hash, asc);;
1610         objs[AFTCOL_HASH].data = buf + CAB_HASH_OFFSET;
1611         objs[AFTCOL_HASH].size = HASH_SIZE;
1612
1613         path = buf + CAB_PATH_OFFSET;
1614         objs[AFTCOL_PATH].data = path;
1615         objs[AFTCOL_PATH].size = strlen(path) + 1;
1616
1617         PARA_INFO_LOG("request to add %s\n", path);
1618         hs = find_hash_sister(hash);
1619         ret = aft_get_row_of_path(path, &pb);
1620         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1621                 goto out;
1622         if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1623                 if (flags & ADD_FLAG_VERBOSE)
1624                         ret = para_printf(&msg, "ignoring duplicate\n");
1625                 else
1626                         ret = 1;
1627                 goto out;
1628         }
1629         if (hs && hs != pb) {
1630                 struct osl_object obj;
1631                 if (pb) { /* hs trumps pb, remove pb */
1632                         if (flags & ADD_FLAG_VERBOSE) {
1633                                 ret = para_printf(&msg, "removing path brother\n");
1634                                 if (ret < 0)
1635                                         goto out;
1636                         }
1637                         ret = osl_del_row(audio_file_table, pb);
1638                         if (ret < 0)
1639                                 goto out;
1640                         pb = NULL;
1641                 }
1642                 /* file rename, update hs' path */
1643                 if (flags & ADD_FLAG_VERBOSE) {
1644                         ret = osl_get_object(audio_file_table, hs,
1645                                 AFTCOL_PATH, &obj);
1646                         if (ret < 0)
1647                                 goto out;
1648                         ret = para_printf(&msg, "renamed from %s\n", (char *)obj.data);
1649                         if (ret < 0)
1650                                 goto out;
1651                 }
1652                 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1653                         &objs[AFTCOL_PATH]);
1654                 if (ret < 0)
1655                         goto out;
1656                 afs_event(AUDIO_FILE_RENAME, &msg, hs);
1657                 if (!(flags & ADD_FLAG_FORCE))
1658                         goto out;
1659         }
1660         /* no hs or force mode, child must have sent afhi */
1661         afhi_offset = read_u16(buf + CAB_AFHI_OFFSET_POS);
1662         chunks_offset = read_u16(buf + CAB_CHUNKS_OFFSET_POS);
1663
1664         objs[AFTCOL_AFHI].data = buf + afhi_offset;
1665         objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1666         ret = -E_NO_AFHI;
1667         if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1668                 goto out;
1669         objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1670         objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1671         if (pb && !hs) { /* update pb's hash */
1672                 char old_asc[2 * HASH_SIZE + 1];
1673                 HASH_TYPE *old_hash;
1674                 ret = get_hash_of_row(pb, &old_hash);
1675                 if (ret < 0)
1676                         goto out;
1677                 hash_to_asc(old_hash, old_asc);
1678                 if (flags & ADD_FLAG_VERBOSE) {
1679                         ret = para_printf(&msg, "file change: %s -> %s\n",
1680                                 old_asc, asc);
1681                         if (ret < 0)
1682                                 goto out;
1683                 }
1684                 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1685                         &objs[AFTCOL_HASH]);
1686                 if (ret < 0)
1687                         goto out;
1688         }
1689         if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1690                 struct osl_row *row = pb? pb : hs;
1691                 /* update afhi and chunk_table */
1692                 if (flags & ADD_FLAG_VERBOSE) {
1693                         ret = para_printf(&msg, "updating afhi and chunk table\n");
1694                         if (ret < 0)
1695                                 goto out;
1696                 }
1697                 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1698                         &objs[AFTCOL_AFHI]);
1699                 if (ret < 0)
1700                         goto out;
1701                 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1702                         &objs[AFTCOL_CHUNKS]);
1703                 if (ret < 0)
1704                         goto out;
1705                 afs_event(AFHI_CHANGE, &msg, row);
1706                 goto out;
1707         }
1708         /* new entry, use default afsi */
1709         if (flags & ADD_FLAG_VERBOSE) {
1710                 ret = para_printf(&msg, "new file\n");
1711                 if (ret < 0)
1712                         goto out;
1713         }
1714         default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1715         default_afsi.audio_format_id = read_u8(buf + CAB_AUDIO_FORMAT_OFFSET);
1716
1717         objs[AFTCOL_AFSI].data = &afsi_buf;
1718         objs[AFTCOL_AFSI].size = AFSI_SIZE;
1719         save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1720         ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1721         afs_event(AUDIO_FILE_ADD, &msg, aft_row);
1722 out:
1723         if (ret < 0)
1724                 para_printf(&msg, "%s\n", para_strerror(-ret));
1725         if (msg.offset)
1726                 pass_buffer_as_shm(msg.buf, msg.offset, &fd);
1727         free(msg.buf);
1728 }
1729
1730 /** Used by com_add(). */
1731 struct private_add_data {
1732         /** The socket file descriptor. */
1733         int fd;
1734         /** The given add flags. */
1735         uint32_t flags;
1736 };
1737
1738 static void path_brother_callback(int fd, const struct osl_object *query)
1739 {
1740         char *path = query->data;
1741         struct osl_row *path_brother;
1742         int ret = aft_get_row_of_path(path, &path_brother);
1743         if (ret < 0)
1744                 return;
1745         pass_buffer_as_shm((char *)&path_brother, sizeof(path_brother), &fd);
1746 }
1747
1748 static void hash_sister_callback(int fd, const struct osl_object *query)
1749 {
1750         HASH_TYPE *hash = query->data;
1751         struct osl_row *hash_sister;
1752
1753         hash_sister = find_hash_sister(hash);
1754         if (!hash_sister)
1755                 return;
1756         pass_buffer_as_shm((char *)&hash_sister, sizeof(hash_sister), &fd);
1757 }
1758
1759 static int get_row_pointer_from_result(struct osl_object *result, void *private)
1760 {
1761         struct osl_row **row = private;
1762         *row = result->data;
1763         return 1;
1764 }
1765
1766 static int add_one_audio_file(const char *path, void *private_data)
1767 {
1768         int ret, send_ret = 1, fd;
1769         uint8_t format_num = -1;
1770         struct private_add_data *pad = private_data;
1771         struct afh_info afhi, *afhi_ptr = NULL;
1772         struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1773         struct osl_object map, obj = {.data = NULL}, query;
1774         HASH_TYPE hash[HASH_SIZE];
1775
1776         ret = guess_audio_format(path);
1777         if (ret < 0 && !(pad->flags & ADD_FLAG_ALL))
1778                 goto out_free;
1779         query.data = (char *)path;
1780         query.size = strlen(path) + 1;
1781         ret = send_callback_request(path_brother_callback, &query,
1782                 get_row_pointer_from_result, &pb);
1783         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1784                 goto out_free;
1785         ret = 1;
1786         if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1787                 if (pad->flags & ADD_FLAG_VERBOSE)
1788                         send_ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1789                 goto out_free;
1790         }
1791         /* We still want to add this file. Compute its hash. */
1792         ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, &fd);
1793         if (ret < 0)
1794                 goto out_free;
1795         hash_function(map.data, map.size, hash);
1796
1797         /* Check whether the database contains a file with the same hash. */
1798         query.data = hash;
1799         query.size = HASH_SIZE;
1800         ret = send_callback_request(hash_sister_callback, &query,
1801                 get_row_pointer_from_result, &hs);
1802         if (ret < 0)
1803                 goto out_unmap;
1804         /* Return success if we already know this file. */
1805         ret = 1;
1806         if (pb && hs && hs == pb && !(pad->flags & ADD_FLAG_FORCE)) {
1807                 if (pad->flags & ADD_FLAG_VERBOSE)
1808                         send_ret = send_va_buffer(pad->fd,
1809                                 "%s exists, not forcing update\n", path);
1810                 goto out_unmap;
1811         }
1812         /*
1813          * We won't recalculate the audio format info and the chunk table if
1814          * there is a hash sister and FORCE was not given.
1815          */
1816         if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1817                 ret = compute_afhi(path, map.data, map.size, fd, &afhi);
1818                 if (ret < 0)
1819                         goto out_unmap;
1820                 format_num = ret;
1821                 afhi_ptr = &afhi;
1822         }
1823         munmap(map.data, map.size);
1824         close(fd);
1825         if (pad->flags & ADD_FLAG_VERBOSE) {
1826                 send_ret = send_va_buffer(pad->fd, "adding %s\n", path);
1827                 if (send_ret < 0)
1828                         goto out_free;
1829         }
1830         save_add_callback_buffer(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1831         /* Ask afs to consider this entry for adding. */
1832         ret = send_callback_request(com_add_callback, &obj, send_result, &pad->fd);
1833         goto out_free;
1834
1835 out_unmap:
1836         close(fd);
1837         munmap(map.data, map.size);
1838 out_free:
1839         if (ret < 0 && send_ret >= 0)
1840                 send_ret = send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1841                         para_strerror(-ret));
1842         free(obj.data);
1843         if (afhi_ptr) {
1844                 free(afhi_ptr->chunk_table);
1845                 free(afhi_ptr->info_string);
1846         }
1847         /* Stop adding files only on send errors. */
1848         return send_ret;
1849 }
1850
1851 int com_add(int fd, int argc, char * const * const argv)
1852 {
1853         int i, ret;
1854         struct private_add_data pad = {.fd = fd, .flags = 0};
1855         struct stat statbuf;
1856
1857         for (i = 1; i < argc; i++) {
1858                 const char *arg = argv[i];
1859                 if (arg[0] != '-')
1860                         break;
1861                 if (!strcmp(arg, "--")) {
1862                         i++;
1863                         break;
1864                 }
1865                 if (!strcmp(arg, "-a")) {
1866                         pad.flags |= ADD_FLAG_ALL;
1867                         continue;
1868                 }
1869                 if (!strcmp(arg, "-l")) {
1870                         pad.flags |= ADD_FLAG_LAZY;
1871                         continue;
1872                 }
1873                 if (!strcmp(arg, "-f")) {
1874                         pad.flags |= ADD_FLAG_FORCE;
1875                         continue;
1876                 }
1877                 if (!strcmp(arg, "-v")) {
1878                         pad.flags |= ADD_FLAG_VERBOSE;
1879                         continue;
1880                 }
1881         }
1882         if (argc <= i)
1883                 return -E_AFT_SYNTAX;
1884         for (; i < argc; i++) {
1885                 char *path;
1886                 ret = verify_path(argv[i], &path);
1887                 if (ret < 0) {
1888                         ret = send_va_buffer(fd, "%s: %s\n", argv[i],
1889                                 para_strerror(-ret));
1890                         if (ret < 0)
1891                                 return ret;
1892                         continue;
1893                 }
1894                 ret = stat(path, &statbuf);
1895                 if (ret < 0) {
1896                         ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1897                                 strerror(errno));
1898                         free(path);
1899                         if (ret < 0)
1900                                 return ret;
1901                         continue;
1902                 }
1903                 if (S_ISDIR(statbuf.st_mode))
1904                         ret = for_each_file_in_dir(path, add_one_audio_file,
1905                                 &pad);
1906                 else
1907                         ret = add_one_audio_file(path, &pad);
1908                 if (ret < 0) {
1909                         send_va_buffer(fd, "%s: %s\n", path, para_strerror(-ret));
1910                         free(path);
1911                         return ret;
1912                 }
1913                 free(path);
1914         }
1915         return 1;
1916
1917 }
1918
1919 /**
1920  * Flags used by the touch command.
1921  *
1922  * \sa com_touch().
1923  */
1924 enum touch_flags {
1925         /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1926         TOUCH_FLAG_FNM_PATHNAME = 1,
1927         /** Activates verbose mode. */
1928         TOUCH_FLAG_VERBOSE = 2
1929 };
1930
1931 /** Options used by com_touch(). */
1932 struct com_touch_options {
1933         /** New num_played value. */
1934         int32_t num_played;
1935         /** New last played count. */
1936         int64_t last_played;
1937         /** New lyrics id. */
1938         int32_t lyrics_id;
1939         /** New image id. */
1940         int32_t image_id;
1941         /** New amplification value. */
1942         int32_t amp;
1943         /** Command line flags (see \ref touch_flags). */
1944         unsigned flags;
1945 };
1946
1947 /** Data passed to the action handler of com_touch(). */
1948 struct touch_action_data {
1949         /** Command line options (see \ref com_touch_options). */
1950         struct com_touch_options *cto;
1951         /** Message buffer. */
1952         struct para_buffer pb;
1953         /** How many audio files matched the given pattern. */
1954         unsigned num_matches;
1955 };
1956
1957 static int touch_audio_file(__a_unused struct osl_table *table,
1958                 struct osl_row *row, const char *name, void *data)
1959 {
1960         struct touch_action_data *tad = data;
1961         struct osl_object obj;
1962         struct afs_info old_afsi, new_afsi;
1963         int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1964                 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0 && tad->cto->amp < 0;
1965         struct afsi_change_event_data aced;
1966
1967         ret = get_afsi_object_of_row(row, &obj);
1968         if (ret < 0)
1969                 return para_printf(&tad->pb, "%s: %s\n", name, para_strerror(-ret));
1970         ret = load_afsi(&old_afsi, &obj);
1971         if (ret < 0)
1972                 return para_printf(&tad->pb, "%s: %s\n", name, para_strerror(-ret));
1973         new_afsi = old_afsi;
1974         if (no_options) {
1975                 new_afsi.num_played++;
1976                 new_afsi.last_played = time(NULL);
1977                 if (tad->cto->flags & TOUCH_FLAG_VERBOSE) {
1978                         ret = para_printf(&tad->pb, "%s: num_played = %u, "
1979                                 "last_played = now()\n", name,
1980                                 new_afsi.num_played);
1981                         if (ret < 0)
1982                                 return ret;
1983                 }
1984         } else {
1985                 if (tad->cto->flags & TOUCH_FLAG_VERBOSE) {
1986                         ret = para_printf(&tad->pb, "touching %s\n", name);
1987                         if (ret < 0)
1988                                 return ret;
1989                 }
1990                 if (tad->cto->lyrics_id >= 0)
1991                         new_afsi.lyrics_id = tad->cto->lyrics_id;
1992                 if (tad->cto->image_id >= 0)
1993                         new_afsi.image_id = tad->cto->image_id;
1994                 if (tad->cto->num_played >= 0)
1995                         new_afsi.num_played = tad->cto->num_played;
1996                 if (tad->cto->last_played >= 0)
1997                         new_afsi.last_played = tad->cto->last_played;
1998                 if (tad->cto->amp >= 0)
1999                         new_afsi.amp = tad->cto->amp;
2000         }
2001         tad->num_matches++;
2002         save_afsi(&new_afsi, &obj); /* in-place update */
2003         aced.aft_row = row;
2004         aced.old_afsi = &old_afsi;
2005         afs_event(AFSI_CHANGE, &tad->pb, &aced);
2006         return 1;
2007 }
2008
2009 static void com_touch_callback(int fd, const struct osl_object *query)
2010 {
2011         struct touch_action_data tad = {.cto = query->data,
2012                 .pb = {
2013                         .max_size = SHMMAX,
2014                         .private_data = &fd,
2015                         .max_size_handler = pass_buffer_as_shm
2016                 }
2017         };
2018         int ret, ret2 = 0;
2019         struct pattern_match_data pmd = {
2020                 .table = audio_file_table,
2021                 .loop_col_num = AFTCOL_HASH,
2022                 .match_col_num = AFTCOL_PATH,
2023                 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
2024                         .size = query->size - sizeof(*tad.cto)},
2025                 .data = &tad,
2026                 .action = touch_audio_file
2027         };
2028         if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
2029                 pmd.fnmatch_flags |= FNM_PATHNAME;
2030         ret = for_each_matching_row(&pmd);
2031         if (ret < 0)
2032                 ret2 = para_printf(&tad.pb, "%s\n", para_strerror(-ret));
2033         else
2034                 if (!tad.num_matches)
2035                         ret2 = para_printf(&tad.pb, "no matches\n");
2036         if (ret2 >= 0 && tad.pb.offset)
2037                 pass_buffer_as_shm(tad.pb.buf, tad.pb.offset, &fd);
2038         free(tad.pb.buf);
2039 }
2040
2041 int com_touch(int fd, int argc, char * const * const argv)
2042 {
2043         struct com_touch_options cto = {
2044                 .num_played = -1,
2045                 .last_played = -1,
2046                 .lyrics_id = -1,
2047                 .image_id = -1,
2048                 .amp = -1,
2049         };
2050         struct osl_object query = {.data = &cto, .size = sizeof(cto)};
2051         int i, ret;
2052
2053
2054         for (i = 1; i < argc; i++) {
2055                 const char *arg = argv[i];
2056                 if (arg[0] != '-')
2057                         break;
2058                 if (!strcmp(arg, "--")) {
2059                         i++;
2060                         break;
2061                 }
2062                 if (!strncmp(arg, "-n", 2)) {
2063                         ret = para_atoi32(arg + 2, &cto.num_played);
2064                         if (ret < 0)
2065                                 return ret;
2066                         continue;
2067                 }
2068                 if (!strncmp(arg, "-l", 2)) {
2069                         ret = para_atoi64(arg + 2, &cto.last_played);
2070                         if (ret < 0)
2071                                 return ret;
2072                         continue;
2073                 }
2074                 if (!strncmp(arg, "-y", 2)) {
2075                         ret = para_atoi32(arg + 2, &cto.lyrics_id);
2076                         if (ret < 0)
2077                                 return ret;
2078                         continue;
2079                 }
2080                 if (!strncmp(arg, "-i", 2)) {
2081                         ret = para_atoi32(arg + 2, &cto.image_id);
2082                         if (ret < 0)
2083                                 return ret;
2084                         continue;
2085                 }
2086                 if (!strncmp(arg, "-a", 2)) {
2087                         int32_t val;
2088                         ret = para_atoi32(arg + 2, &val);
2089                         if (ret < 0)
2090                                 return ret;
2091                         if (val < 0 || val > 255)
2092                                 return -ERRNO_TO_PARA_ERROR(EINVAL);
2093                         cto.amp = val;
2094                         continue;
2095                 }
2096                 if (!strcmp(arg, "-p")) {
2097                         cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
2098                         continue;
2099                 }
2100                 if (!strcmp(arg, "-v")) {
2101                         cto.flags |= TOUCH_FLAG_VERBOSE;
2102                         continue;
2103                 }
2104                 break; /* non-option starting with dash */
2105         }
2106         if (i >= argc)
2107                 return -E_AFT_SYNTAX;
2108         ret = send_option_arg_callback_request(&query, argc - i,
2109                 argv + i, com_touch_callback, send_result, &fd);
2110         if (ret < 0)
2111                 send_va_buffer(fd, "%s\n", para_strerror(-ret));
2112         return ret;
2113 }
2114
2115 /** Flags for com_rm(). */
2116 enum rm_flags {
2117         /** -v */
2118         RM_FLAG_VERBOSE = 1,
2119         /** -f */
2120         RM_FLAG_FORCE = 2,
2121         /** -p */
2122         RM_FLAG_FNM_PATHNAME = 4
2123 };
2124
2125 /** Data passed to the action handler of com_rm(). */
2126 struct com_rm_action_data {
2127         /** Command line flags ((see \ref rm_flags). */
2128         uint32_t flags;
2129         /** Message buffer. */
2130         struct para_buffer pb;
2131         /** Number of audio files removed. */
2132         unsigned num_removed;
2133 };
2134
2135 static int remove_audio_file(__a_unused struct osl_table *table,
2136                 struct osl_row *row, const char *name, void *data)
2137 {
2138         struct com_rm_action_data *crd = data;
2139         int ret;
2140
2141         if (crd->flags & RM_FLAG_VERBOSE) {
2142                 ret = para_printf(&crd->pb, "removing %s\n", name);
2143                 if (ret < 0)
2144                         return ret;
2145         }
2146         afs_event(AUDIO_FILE_REMOVE, &crd->pb, row);
2147         ret = osl_del_row(audio_file_table, row);
2148         if (ret < 0)
2149                 para_printf(&crd->pb, "%s: %s\n", name, para_strerror(-ret));
2150         else
2151                 crd->num_removed++;
2152         return ret;
2153 }
2154
2155 static void com_rm_callback(int fd, const struct osl_object *query)
2156 {
2157         struct com_rm_action_data crd = {.flags = *(uint32_t *)query->data,
2158                 .pb = {
2159                         .max_size = SHMMAX,
2160                         .private_data = &fd,
2161                         .max_size_handler = pass_buffer_as_shm
2162                 }
2163         };
2164         int ret;
2165         struct pattern_match_data pmd = {
2166                 .table = audio_file_table,
2167                 .loop_col_num = AFTCOL_HASH,
2168                 .match_col_num = AFTCOL_PATH,
2169                 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
2170                         .size = query->size - sizeof(uint32_t)},
2171                 .data = &crd,
2172                 .action = remove_audio_file
2173         };
2174         if (crd.flags & RM_FLAG_FNM_PATHNAME)
2175                 pmd.fnmatch_flags |= FNM_PATHNAME;
2176         ret = for_each_matching_row(&pmd);
2177         if (ret < 0) {
2178                 para_printf(&crd.pb, "%s\n", para_strerror(-ret));
2179                 return;
2180         }
2181         if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
2182                 ret = para_printf(&crd.pb, "no matches -- nothing removed\n");
2183         else {
2184                 if (crd.flags & RM_FLAG_VERBOSE)
2185                         ret = para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
2186         }
2187         if (ret >= 0 && crd.pb.offset)
2188                 pass_buffer_as_shm(crd.pb.buf, crd.pb.offset, &fd);
2189         free(crd.pb.buf);
2190 }
2191
2192 /* TODO options: -r (recursive) */
2193 int com_rm(int fd, int argc,  char * const * const argv)
2194 {
2195         uint32_t flags = 0;
2196         struct osl_object query = {.data = &flags, .size = sizeof(flags)};
2197         int i, ret;
2198
2199         for (i = 1; i < argc; i++) {
2200                 const char *arg = argv[i];
2201                 if (arg[0] != '-')
2202                         break;
2203                 if (!strcmp(arg, "--")) {
2204                         i++;
2205                         break;
2206                 }
2207                 if (!strcmp(arg, "-f")) {
2208                         flags |= RM_FLAG_FORCE;
2209                         continue;
2210                 }
2211                 if (!strcmp(arg, "-p")) {
2212                         flags |= RM_FLAG_FNM_PATHNAME;
2213                         continue;
2214                 }
2215                 if (!strcmp(arg, "-v")) {
2216                         flags |= RM_FLAG_VERBOSE;
2217                         continue;
2218                 }
2219                 break;
2220         }
2221         if (i >= argc)
2222                 return -E_AFT_SYNTAX;
2223         ret = send_option_arg_callback_request(&query, argc - i, argv + i,
2224                 com_rm_callback, send_result, &fd);
2225         if (ret < 0)
2226                 send_va_buffer(fd, "%s\n", para_strerror(-ret));
2227         return ret;
2228 }
2229
2230 /**
2231  * Flags used by the cpsi command.
2232  *
2233  * \sa com_cpsi().
2234  */
2235 enum cpsi_flags {
2236         /** Whether the lyrics id should be copied. */
2237         CPSI_FLAG_COPY_LYRICS_ID = 1,
2238         /** Whether the image id should be copied. */
2239         CPSI_FLAG_COPY_IMAGE_ID = 2,
2240         /** Whether the lastplayed time should be copied. */
2241         CPSI_FLAG_COPY_LASTPLAYED = 4,
2242         /** Whether the numplayed count should be copied. */
2243         CPSI_FLAG_COPY_NUMPLAYED = 8,
2244         /** Whether the attributes should be copied. */
2245         CPSI_FLAG_COPY_ATTRIBUTES = 16,
2246         /** Activates verbose mode. */
2247         CPSI_FLAG_VERBOSE = 32,
2248 };
2249
2250 /** Data passed to the action handler of com_cpsi(). */
2251 struct cpsi_action_data {
2252         /** command line flags (see \ref cpsi_flags). */
2253         unsigned flags;
2254         /** Number of audio files changed. */
2255         unsigned num_copied;
2256         /** Message buffer. */
2257         struct para_buffer pb;
2258         /** Values are copied from here. */
2259         struct afs_info source_afsi;
2260 };
2261
2262 static int copy_selector_info(__a_unused struct osl_table *table,
2263                 struct osl_row *row, const char *name, void *data)
2264 {
2265         struct cpsi_action_data *cad = data;
2266         struct osl_object target_afsi_obj;
2267         int ret;
2268         struct afs_info old_afsi, target_afsi;
2269         struct afsi_change_event_data aced;
2270
2271         ret = get_afsi_object_of_row(row, &target_afsi_obj);
2272         if (ret < 0)
2273                 return ret;
2274         load_afsi(&target_afsi, &target_afsi_obj);
2275         old_afsi = target_afsi;
2276         if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
2277                 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2278         if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
2279                 target_afsi.image_id = cad->source_afsi.image_id;
2280         if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
2281                 target_afsi.last_played = cad->source_afsi.last_played;
2282         if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
2283                 target_afsi.num_played = cad->source_afsi.num_played;
2284         if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
2285                 target_afsi.attributes = cad->source_afsi.attributes;
2286         save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2287         cad->num_copied++;
2288         if (cad->flags & CPSI_FLAG_VERBOSE) {
2289                 ret = para_printf(&cad->pb, "copied afsi to %s\n", name);
2290                 if (ret < 0)
2291                         return ret;
2292         }
2293         aced.aft_row = row;
2294         aced.old_afsi = &old_afsi;
2295         afs_event(AFSI_CHANGE, &cad->pb, &aced);
2296         return 1;
2297 }
2298
2299 static void com_cpsi_callback(int fd, const struct osl_object *query)
2300 {
2301         struct cpsi_action_data cad = {
2302                 .flags = *(unsigned *)query->data,
2303                 .pb = {
2304                         .max_size = SHMMAX,
2305                         .private_data = &fd,
2306                         .max_size_handler = pass_buffer_as_shm
2307                 }
2308         };
2309         int ret;
2310         char *source_path = (char *)query->data + sizeof(cad.flags);
2311         struct pattern_match_data pmd = {
2312                 .table = audio_file_table,
2313                 .loop_col_num = AFTCOL_HASH,
2314                 .match_col_num = AFTCOL_PATH,
2315                 .patterns = {.data = source_path + strlen(source_path) + 1,
2316                         .size = query->size - sizeof(cad.flags)
2317                                 - strlen(source_path) - 1},
2318                 .data = &cad,
2319                 .action = copy_selector_info
2320         };
2321
2322         ret = get_afsi_of_path(source_path, &cad.source_afsi);
2323         if (ret < 0)
2324                 goto out;
2325         ret = for_each_matching_row(&pmd);
2326 out:
2327         if (ret < 0)
2328                 para_printf(&cad.pb, "%s\n", para_strerror(-ret));
2329         else if (cad.flags & CPSI_FLAG_VERBOSE) {
2330                 if (cad.num_copied)
2331                         para_printf(&cad.pb, "copied requested afsi from %s "
2332                                 "to %u files\n", source_path, cad.num_copied);
2333                 else
2334                         para_printf(&cad.pb, "nothing copied\n");
2335         }
2336         if (cad.pb.offset)
2337                 pass_buffer_as_shm(cad.pb.buf, cad.pb.offset, &fd);
2338         free(cad.pb.buf);
2339 }
2340
2341 int com_cpsi(int fd, int argc,  char * const * const argv)
2342 {
2343         unsigned flags = 0;
2344         int i, ret;
2345         struct osl_object options = {.data = &flags, .size = sizeof(flags)};
2346
2347         for (i = 1; i < argc; i++) {
2348                 const char *arg = argv[i];
2349                 if (arg[0] != '-')
2350                         break;
2351                 if (!strcmp(arg, "--")) {
2352                         i++;
2353                         break;
2354                 }
2355                 if (!strcmp(arg, "-y")) {
2356                         flags |= CPSI_FLAG_COPY_LYRICS_ID;
2357                         continue;
2358                 }
2359                 if (!strcmp(arg, "-i")) {
2360                         flags |= CPSI_FLAG_COPY_IMAGE_ID;
2361                         continue;
2362                 }
2363                 if (!strcmp(arg, "-l")) {
2364                         flags |= CPSI_FLAG_COPY_LASTPLAYED;
2365                         continue;
2366                 }
2367                 if (!strcmp(arg, "-n")) {
2368                         flags |= CPSI_FLAG_COPY_NUMPLAYED;
2369                         continue;
2370                 }
2371                 if (!strcmp(arg, "-a")) {
2372                         flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2373                         continue;
2374                 }
2375                 if (!strcmp(arg, "-v")) {
2376                         flags |= CPSI_FLAG_VERBOSE;
2377                         continue;
2378                 }
2379                 break;
2380         }
2381         if (i + 1 >= argc) /* need at least souce file and pattern */
2382                 return -E_AFT_SYNTAX;
2383         if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2384                 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2385         ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2386                 com_cpsi_callback, send_result, &fd);
2387         if (ret < 0)
2388                 send_va_buffer(fd, "%s\n", para_strerror(-ret));
2389         return ret;
2390 }
2391
2392 /* TODO: optionally fix problems by removing offending rows */
2393 static int check_audio_file(struct osl_row *row, void *data)
2394 {
2395         char *path;
2396         struct para_buffer *pb = data;
2397         struct stat statbuf;
2398         int ret = get_audio_file_path_of_row(row, &path);
2399         struct afs_info afsi;
2400         char *blob_name;
2401
2402         if (ret < 0)
2403                 return para_printf(pb, "%s\n", para_strerror(-ret));
2404         if (stat(path, &statbuf) < 0) {
2405                 ret = para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2406                 if (ret < 0)
2407                         return ret;
2408         } else {
2409                 if (!S_ISREG(statbuf.st_mode)) {
2410                         ret = para_printf(pb, "%s: not a regular file\n", path);
2411                         if (ret < 0)
2412                                 return ret;
2413                 }
2414         }
2415         ret = get_afsi_of_row(row, &afsi);
2416         if (ret < 0)
2417                 return para_printf(pb, "%s: %s\n", path, para_strerror(-ret));
2418         ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2419         if (ret < 0) {
2420                 ret = para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2421                         para_strerror(-ret));
2422                 if (ret < 0)
2423                         return ret;
2424         }
2425         ret = img_get_name_by_id(afsi.image_id, &blob_name);
2426         if (ret < 0)
2427                 ret = para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2428                         para_strerror(-ret));
2429         return ret;
2430 }
2431
2432 /**
2433  * Check the audio file table for inconsistencies.
2434  *
2435  * \param fd The afs socket.
2436  * \param query Unused.
2437  *
2438  * This function always succeeds.
2439  *
2440  * \sa com_check().
2441  */
2442 void aft_check_callback(int fd, __a_unused const struct osl_object *query)
2443 {
2444         struct para_buffer pb = {
2445                 .max_size = SHMMAX,
2446                 .private_data = &fd,
2447                 .max_size_handler = pass_buffer_as_shm
2448         };
2449         int ret = para_printf(&pb, "checking audio file table...\n");
2450
2451         if (ret < 0)
2452                 return;
2453         audio_file_loop(&pb, check_audio_file);
2454         if (pb.offset)
2455                 pass_buffer_as_shm(pb.buf, pb.offset, &fd);
2456         free(pb.buf);
2457 }
2458
2459 /**
2460  * Close the audio file table.
2461  *
2462  * \param flags Usual flags that are passed to osl_close_table().
2463  *
2464  * \sa osl_close_table().
2465  */
2466 static void aft_close(void)
2467 {
2468         osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2469         audio_file_table = NULL;
2470 }
2471
2472 /**
2473  * Open the audio file table.
2474  *
2475  * \param dir The database directory.
2476  *
2477  * \return Standard.
2478  *
2479  * \sa osl_open_table().
2480  */
2481 static int aft_open(const char *dir)
2482 {
2483         int ret;
2484
2485         audio_file_table_desc.dir = dir;
2486         ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
2487         if (ret >= 0) {
2488                 unsigned num;
2489                 osl_get_num_rows(audio_file_table, &num);
2490                 PARA_INFO_LOG("audio file table contains %d files\n", num);
2491                 return ret;
2492         }
2493         PARA_INFO_LOG("failed to open audio file table\n");
2494         audio_file_table = NULL;
2495         if (ret >= 0 || is_errno(-ret, ENOENT))
2496                 return 1;
2497         return ret;
2498 }
2499
2500 static int aft_create(const char *dir)
2501 {
2502         audio_file_table_desc.dir = dir;
2503         return osl_create_table(&audio_file_table_desc);
2504 }
2505
2506 static int clear_attribute(struct osl_row *row, void *data)
2507 {
2508         struct rmatt_event_data *red = data;
2509         struct afs_info afsi;
2510         struct osl_object obj;
2511         int ret = get_afsi_object_of_row(row, &obj);
2512         uint64_t mask = ~(1ULL << red->bitnum);
2513
2514         if (ret < 0)
2515                 return ret;
2516         ret = load_afsi(&afsi, &obj);
2517         if (ret < 0)
2518                 return ret;
2519         afsi.attributes &= mask;
2520         save_afsi(&afsi, &obj);
2521         return 1;
2522 }
2523
2524 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2525                 void *data)
2526 {
2527         int ret;
2528
2529         switch(event) {
2530         case ATTRIBUTE_REMOVE: {
2531                 const struct rmatt_event_data *red = data;
2532                 ret = para_printf(pb, "clearing attribute %s (bit %u) from all "
2533                         "entries in the audio file table\n", red->name,
2534                         red->bitnum);
2535                 if (ret < 0)
2536                         return ret;
2537                 return audio_file_loop(data, clear_attribute);
2538                 }
2539         default:
2540                 return 1;
2541         }
2542 }
2543
2544 void aft_init(struct afs_table *t)
2545 {
2546         t->name = audio_file_table_desc.name;
2547         t->open = aft_open;
2548         t->close = aft_close;
2549         t->create = aft_create;
2550         t->event_handler = aft_event_handler;
2551 }