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