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