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