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