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