Add new ls option: -lc to print out the chunk table.
[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         buf = chunk_table_obj.data;
839         para_printf(b, "%s\n"
840                 "chunk_time: %lu:%lu\nchunk_offsets: ",
841                 d->path,
842                 (long unsigned) d->afhi.chunk_tv.tv_sec,
843                 (long unsigned) d->afhi.chunk_tv.tv_usec
844         );
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.size;
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                 ls_output;
1306
1307         for (i = 1; i < argc; i++) {
1308                 const char *arg = argv[i];
1309                 if (arg[0] != '-')
1310                         break;
1311                 if (!strcmp(arg, "--")) {
1312                         i++;
1313                         break;
1314                 }
1315                 if (!strncmp(arg, "-l", 2)) {
1316                         if (!*(arg + 2)) {
1317                                 mode = LS_MODE_LONG;
1318                                 continue;
1319                         }
1320                         if (*(arg + 3))
1321                                 return -E_AFT_SYNTAX;
1322                         switch(*(arg + 2)) {
1323                         case 's':
1324                                 mode = LS_MODE_SHORT;
1325                                 continue;
1326                         case 'l':
1327                                 mode = LS_MODE_LONG;
1328                                 continue;
1329                         case 'v':
1330                                 mode = LS_MODE_VERBOSE;
1331                                 continue;
1332                         case 'm':
1333                                 mode = LS_MODE_MBOX;
1334                                 continue;
1335                         case 'c':
1336                                 mode = LS_MODE_CHUNKS;
1337                                 continue;
1338                         default:
1339                                 return -E_AFT_SYNTAX;
1340                         }
1341                 }
1342                 if (!strcmp(arg, "-p")) {
1343                         flags |= LS_FLAG_FULL_PATH;
1344                         continue;
1345                 }
1346                 if (!strcmp(arg, "-a")) {
1347                         flags |= LS_FLAG_ADMISSIBLE_ONLY;
1348                         continue;
1349                 }
1350                 if (!strcmp(arg, "-r")) {
1351                         flags |= LS_FLAG_REVERSE;
1352                         continue;
1353                 }
1354                 if (!strncmp(arg, "-s", 2)) {
1355                         if (!*(arg + 2) || *(arg + 3))
1356                                 return -E_AFT_SYNTAX;
1357                         switch(*(arg + 2)) {
1358                         case 'p':
1359                                 sort = LS_SORT_BY_PATH;
1360                                 continue;
1361                         case 's': /* -ss implies -a */
1362                                 sort = LS_SORT_BY_SCORE;
1363                                 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1364                                 continue;
1365                         case 'l':
1366                                 sort = LS_SORT_BY_LAST_PLAYED;
1367                                 continue;
1368                         case 'n':
1369                                 sort = LS_SORT_BY_NUM_PLAYED;
1370                                 continue;
1371                         case 'f':
1372                                 sort = LS_SORT_BY_FREQUENCY;
1373                                 continue;
1374                         case 'c':
1375                                 sort = LS_SORT_BY_CHANNELS;
1376                                 continue;
1377                         case 'i':
1378                                 sort = LS_SORT_BY_IMAGE_ID;
1379                                 continue;
1380                         case 'y':
1381                                 sort = LS_SORT_BY_LYRICS_ID;
1382                                 continue;
1383                         case 'b':
1384                                 sort = LS_SORT_BY_BITRATE;
1385                                 continue;
1386                         case 'd':
1387                                 sort = LS_SORT_BY_DURATION;
1388                                 continue;
1389                         case 'a':
1390                                 sort = LS_SORT_BY_AUDIO_FORMAT;
1391                                 continue;
1392                         default:
1393                                 return -E_AFT_SYNTAX;
1394                         }
1395                 }
1396                 return -E_AFT_SYNTAX;
1397         }
1398         opts.flags = flags;
1399         opts.sorting = sort;
1400         opts.mode = mode;
1401         opts.num_patterns = argc - i;
1402         ret = send_option_arg_callback_request(&query, opts.num_patterns,
1403                 argv + i, com_ls_callback, &ls_output);
1404         if (ret > 0) {
1405                 ret = send_buffer(fd, (char *)ls_output.data);
1406                 free(ls_output.data);
1407         }
1408         return ret;
1409 }
1410
1411 /**
1412  * Call the given function for each file in the audio file table.
1413  *
1414  * \param private_data An arbitrary data pointer, passed to \a func.
1415  * \param func The custom function to be called.
1416  *
1417  * \return The return value of the underlying call to osl_rbtree_loop().
1418  */
1419 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1420 {
1421         return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1422                 func);
1423 }
1424
1425 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1426 {
1427         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1428         struct osl_row *row;
1429
1430         osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1431         return row;
1432 }
1433
1434 /** The format of the data stored by save_audio_file_data(). */
1435 enum com_add_buffer_offsets {
1436         /** afhi (if present) starts here. */
1437         CAB_AFHI_OFFSET_POS = 0,
1438         /** Start of the chunk table (if present). */
1439         CAB_CHUNKS_OFFSET_POS = 2,
1440         /** Audio format id. */
1441         CAB_AUDIO_FORMAT_OFFSET = 4,
1442         /** Flags given to the add command. */
1443         CAB_FLAGS_OFFSET = 5,
1444         /** The hash of the audio file being added. */
1445         CAB_HASH_OFFSET = 9,
1446         /** Start of the path of the audio file. */
1447         CAB_PATH_OFFSET = (CAB_HASH_OFFSET + HASH_SIZE),
1448 };
1449
1450 /*
1451  * Store the given data to a single buffer. Doesn't need the audio file selector
1452  * info struct as the server knows it as well.
1453  *
1454  * It's OK to call this with afhi == NULL. In this case, the audio format
1455  * handler info won't be stored in the buffer.
1456  */
1457 static void save_add_callback_buffer(HASH_TYPE *hash, const char *path,
1458                 struct afh_info *afhi, uint32_t flags,
1459                 uint8_t audio_format_num, struct osl_object *obj)
1460 {
1461         size_t path_len = strlen(path) + 1;
1462         size_t afhi_size = sizeof_afhi_buf(afhi);
1463         size_t size = CAB_PATH_OFFSET + path_len + afhi_size
1464                 + sizeof_chunk_table(afhi);
1465         char *buf = para_malloc(size);
1466         uint16_t pos;
1467
1468         write_u8(buf + CAB_AUDIO_FORMAT_OFFSET, audio_format_num);
1469         write_u32(buf + CAB_FLAGS_OFFSET, flags);
1470
1471         memcpy(buf + CAB_HASH_OFFSET, hash, HASH_SIZE);
1472         strcpy(buf + CAB_PATH_OFFSET, path);
1473
1474         pos = CAB_PATH_OFFSET + path_len;
1475         PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1476         PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1477                 pos + afhi_size - 1);
1478         write_u16(buf + CAB_AFHI_OFFSET_POS, pos);
1479         save_afhi(afhi, buf + pos);
1480
1481         pos += afhi_size;
1482         PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1483         write_u16(buf + CAB_CHUNKS_OFFSET_POS, pos);
1484         if (afhi)
1485                 save_chunk_table(afhi, buf + pos);
1486         PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1487         obj->data = buf;
1488         obj->size = size;
1489 }
1490
1491 /*
1492
1493 Overview of the add command.
1494
1495 Input: What was passed to the callback by the command handler.
1496 ~~~~~~
1497 HS:     Hash sister. Whether an audio file with identical hash
1498         already exists in the osl database.
1499
1500 PB:     Path brother. Whether a file with the given path exists
1501         in the table.
1502
1503 F:      Force flag given. Whether add was called with -f.
1504
1505 output: Action performed by the callback.
1506 ~~~~~~~
1507 AFHI:   Whether afhi and chunk table are computed and sent.
1508 ACTION: Table modifications to be done by the callback.
1509
1510 +----+----+---+------+---------------------------------------------------+
1511 | HS | PB | F | AFHI | ACTION
1512 +----+----+---+------+---------------------------------------------------+
1513 | Y  |  Y | Y |  Y   | if HS != PB: remove PB. HS: force afhi update,
1514 |                    | update path, keep afsi
1515 +----+----+---+------+---------------------------------------------------+
1516 | Y  |  Y | N |  N   | if HS == PB: do not send callback request at all.
1517 |                    | otherwise: remove PB, HS: update path, keep afhi,
1518 |                    | afsi.
1519 +----+----+---+------+---------------------------------------------------+
1520 | Y  |  N | Y |  Y   | (rename) force afhi update of HS, update path of
1521 |                    | HS, keep afsi
1522 +----+----+---+------+---------------------------------------------------+
1523 | Y  |  N | N |  N   | (file rename) update path of HS, keep afsi, afhi
1524 +----+----+---+------+---------------------------------------------------+
1525 | N  |  Y | Y |  Y   | (file change) update afhi, hash, of PB, keep afsi
1526 |                    | (force has no effect)
1527 +----+----+---+------+---------------------------------------------------+
1528 | N  |  Y | N |  Y   | (file change) update afhi, hash of PB, keep afsi
1529 +----+----+---+------+---------------------------------------------------+
1530 | N  |  N | Y |  Y   | (new file) create new entry (force has no effect)
1531 +----+----+---+------+---------------------------------------------------+
1532 |  N |  N | N |  Y   | (new file) create new entry
1533 +----+----+---+------+---------------------------------------------------+
1534
1535 Notes:
1536
1537         afhi <=> force or no HS
1538         F => AFHI
1539
1540 */
1541
1542 /** Flags passed to the add command. */
1543 enum com_add_flags {
1544         /** Skip paths that exist already. */
1545         ADD_FLAG_LAZY = 1,
1546         /** Force adding. */
1547         ADD_FLAG_FORCE = 2,
1548         /** Print what is being done. */
1549         ADD_FLAG_VERBOSE = 4,
1550         /** Try to add files with unknown suffixes. */
1551         ADD_FLAG_ALL = 8,
1552 };
1553
1554 static int com_add_callback(const struct osl_object *query,
1555                 struct osl_object *result)
1556 {
1557         char *buf = query->data, *path;
1558         struct osl_row *pb, *aft_row;
1559         struct osl_row *hs;
1560         struct osl_object objs[NUM_AFT_COLUMNS];
1561         HASH_TYPE *hash;
1562         char asc[2 * HASH_SIZE + 1];
1563         int ret;
1564         char afsi_buf[AFSI_SIZE];
1565         uint32_t flags = read_u32(buf + CAB_FLAGS_OFFSET);
1566         struct afs_info default_afsi = {.last_played = 0};
1567         struct para_buffer msg = {.buf = NULL};
1568
1569         hash = (HASH_TYPE *)buf + CAB_HASH_OFFSET;
1570         hash_to_asc(hash, asc);;
1571         objs[AFTCOL_HASH].data = buf + CAB_HASH_OFFSET;
1572         objs[AFTCOL_HASH].size = HASH_SIZE;
1573
1574         path = buf + CAB_PATH_OFFSET;
1575         objs[AFTCOL_PATH].data = path;
1576         objs[AFTCOL_PATH].size = strlen(path) + 1;
1577
1578         PARA_INFO_LOG("request to add %s\n", path);
1579         hs = find_hash_sister(hash);
1580         ret = aft_get_row_of_path(path, &pb);
1581         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1582                 return ret;
1583         if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1584                 if (flags & ADD_FLAG_VERBOSE)
1585                         para_printf(&msg, "ignoring duplicate\n");
1586                 ret = 1;
1587                 goto out;
1588         }
1589         if (hs && hs != pb) {
1590                 struct osl_object obj;
1591                 if (pb) { /* hs trumps pb, remove pb */
1592                         if (flags & ADD_FLAG_VERBOSE)
1593                                 para_printf(&msg, "removing path brother\n");
1594                         ret = osl_del_row(audio_file_table, pb);
1595                         if (ret < 0)
1596                                 goto out;
1597                         pb = NULL;
1598                 }
1599                 /* file rename, update hs' path */
1600                 if (flags & ADD_FLAG_VERBOSE) {
1601                         ret = osl_get_object(audio_file_table, hs,
1602                                 AFTCOL_PATH, &obj);
1603                         if (ret < 0)
1604                                 goto out;
1605                         para_printf(&msg, "renamed from %s\n", (char *)obj.data);
1606                 }
1607                 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1608                         &objs[AFTCOL_PATH]);
1609                 if (ret < 0)
1610                         goto out;
1611                 afs_event(AUDIO_FILE_RENAME, &msg, hs);
1612                 if (!(flags & ADD_FLAG_FORCE))
1613                         goto out;
1614         }
1615         /* no hs or force mode, child must have sent afhi */
1616         uint16_t afhi_offset = read_u16(buf + CAB_AFHI_OFFSET_POS);
1617         uint16_t chunks_offset = read_u16(buf + CAB_CHUNKS_OFFSET_POS);
1618
1619         objs[AFTCOL_AFHI].data = buf + afhi_offset;
1620         objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1621         ret = -E_NO_AFHI;
1622         if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1623                 goto out;
1624         objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1625         objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1626         if (pb && !hs) { /* update pb's hash */
1627                 char old_asc[2 * HASH_SIZE + 1];
1628                 HASH_TYPE *old_hash;
1629                 ret = get_hash_of_row(pb, &old_hash);
1630                 if (ret < 0)
1631                         goto out;
1632                 hash_to_asc(old_hash, old_asc);
1633                 if (flags & ADD_FLAG_VERBOSE)
1634                         para_printf(&msg, "file change: %s -> %s\n",
1635                                 old_asc, asc);
1636                 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1637                         &objs[AFTCOL_HASH]);
1638                 if (ret < 0)
1639                         goto out;
1640         }
1641         if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1642                 struct osl_row *row = pb? pb : hs;
1643                 /* update afhi and chunk_table */
1644                 if (flags & ADD_FLAG_VERBOSE)
1645                         para_printf(&msg, "updating afhi and chunk table\n");
1646                 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1647                         &objs[AFTCOL_AFHI]);
1648                 if (ret < 0)
1649                         goto out;
1650                 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1651                         &objs[AFTCOL_CHUNKS]);
1652                 if (ret < 0)
1653                         goto out;
1654                 afs_event(AFHI_CHANGE, &msg, row);
1655                 goto out;
1656         }
1657         /* new entry, use default afsi */
1658         if (flags & ADD_FLAG_VERBOSE)
1659                 para_printf(&msg, "new file\n");
1660         default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1661         default_afsi.audio_format_id = read_u8(buf + CAB_AUDIO_FORMAT_OFFSET);
1662
1663         objs[AFTCOL_AFSI].data = &afsi_buf;
1664         objs[AFTCOL_AFSI].size = AFSI_SIZE;
1665         save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1666         ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1667         afs_event(AUDIO_FILE_ADD, &msg, aft_row);
1668 out:
1669         if (ret < 0)
1670                 para_printf(&msg, "%s\n", para_strerror(-ret));
1671         if (!msg.buf)
1672                 return 0;
1673         result->data = msg.buf;
1674         result->size = msg.size;
1675         return 1;
1676 }
1677
1678 /** Used by com_add(). */
1679 struct private_add_data {
1680         /** The socket file descriptor. */
1681         int fd;
1682         /** The given add flags. */
1683         uint32_t flags;
1684 };
1685
1686 static int path_brother_callback(const struct osl_object *query,
1687                 struct osl_object *result)
1688 {
1689         char *path = query->data;
1690         struct osl_row *path_brother;
1691         int ret = aft_get_row_of_path(path, &path_brother);
1692         if (ret < 0)
1693                 return ret;
1694         result->data = para_malloc(sizeof(path_brother));
1695         result->size = sizeof(path_brother);
1696         *(struct osl_row **)(result->data) = path_brother;
1697         return 1;
1698 }
1699
1700 static int hash_sister_callback(const struct osl_object *query,
1701                 struct osl_object *result)
1702 {
1703         HASH_TYPE *hash = query->data;
1704         struct osl_row *hash_sister;
1705
1706         hash_sister = find_hash_sister(hash);
1707         if (!hash_sister)
1708                 return -E_RB_KEY_NOT_FOUND;
1709         result->data = para_malloc(sizeof(hash_sister));
1710         result->size = sizeof(hash_sister);
1711         *(struct osl_row **)(result->data) = hash_sister;
1712         return 1;
1713 }
1714
1715 static int add_one_audio_file(const char *path, const void *private_data)
1716 {
1717         int ret, send_ret = 1;
1718         uint8_t format_num = -1;
1719         const struct private_add_data *pad = private_data;
1720         struct afh_info afhi, *afhi_ptr = NULL;
1721         struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1722         struct osl_object map, obj = {.data = NULL}, query, result = {.data = NULL};
1723         HASH_TYPE hash[HASH_SIZE];
1724
1725         afhi.header_offset = 0;
1726         afhi.header_len = 0;
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, &result);
1733         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1734                 goto out_free;
1735         if (ret >= 0) {
1736                 pb = *(struct osl_row **)result.data;
1737                 free(result.data);
1738         }
1739         ret = 1;
1740         if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1741                 if (pad->flags & ADD_FLAG_VERBOSE)
1742                         send_ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1743                 goto out_free;
1744         }
1745         /* We still want to add this file. Compute its hash. */
1746         ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, NULL);
1747         if (ret < 0)
1748                 goto out_free;
1749         hash_function(map.data, map.size, hash);
1750
1751         /* Check whether the database contains a file with the same hash. */
1752         query.data = hash;
1753         query.size = HASH_SIZE;
1754         ret = send_callback_request(hash_sister_callback, &query, &result);
1755         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1756                 goto out_unmap;
1757         if (ret >= 0) {
1758                 hs = *(struct osl_row **)result.data;
1759                 free(result.data);
1760         }
1761         /* Return success if we already know this file. */
1762         ret = 1;
1763         if (pb && hs && hs == pb && !(pad->flags & ADD_FLAG_FORCE)) {
1764                 if (pad->flags & ADD_FLAG_VERBOSE)
1765                         send_ret = send_va_buffer(pad->fd,
1766                                 "%s exists, not forcing update\n", path);
1767                 goto out_unmap;
1768         }
1769         /*
1770          * We won't recalculate the audio format info and the chunk table if
1771          * there is a hash sister and FORCE was not given.
1772          */
1773         if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1774                 ret = compute_afhi(path, map.data, map.size, &afhi);
1775                 if (ret < 0)
1776                         goto out_unmap;
1777                 format_num = ret;
1778                 afhi_ptr = &afhi;
1779         }
1780         munmap(map.data, map.size);
1781         if (pad->flags & ADD_FLAG_VERBOSE) {
1782                 send_ret = send_va_buffer(pad->fd, "adding %s\n", path);
1783                 if (send_ret < 0)
1784                         goto out_free;
1785         }
1786         save_add_callback_buffer(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1787         /* Ask afs to consider this entry for adding. */
1788         ret = send_callback_request(com_add_callback, &obj, &result);
1789         if (ret > 0) {
1790                 send_ret = send_va_buffer(pad->fd, "%s", (char *)result.data);
1791                 free(result.data);
1792         }
1793         goto out_free;
1794
1795 out_unmap:
1796         munmap(map.data, map.size);
1797 out_free:
1798         if (ret < 0 && send_ret >= 0)
1799                 send_ret = send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1800                         para_strerror(-ret));
1801         free(obj.data);
1802         if (afhi_ptr)
1803                 free(afhi_ptr->chunk_table);
1804         /* Stop adding files only on send errors. */
1805         return send_ret;
1806 }
1807
1808 int com_add(int fd, int argc, char * const * const argv)
1809 {
1810         int i, ret;
1811         struct private_add_data pad = {.fd = fd, .flags = 0};
1812         struct stat statbuf;
1813
1814         for (i = 1; i < argc; i++) {
1815                 const char *arg = argv[i];
1816                 if (arg[0] != '-')
1817                         break;
1818                 if (!strcmp(arg, "--")) {
1819                         i++;
1820                         break;
1821                 }
1822                 if (!strcmp(arg, "-a")) {
1823                         pad.flags |= ADD_FLAG_ALL;
1824                         continue;
1825                 }
1826                 if (!strcmp(arg, "-l")) {
1827                         pad.flags |= ADD_FLAG_LAZY;
1828                         continue;
1829                 }
1830                 if (!strcmp(arg, "-f")) {
1831                         pad.flags |= ADD_FLAG_FORCE;
1832                         continue;
1833                 }
1834                 if (!strcmp(arg, "-v")) {
1835                         pad.flags |= ADD_FLAG_VERBOSE;
1836                         continue;
1837                 }
1838         }
1839         if (argc <= i)
1840                 return -E_AFT_SYNTAX;
1841         for (; i < argc; i++) {
1842                 char *path;
1843                 ret = verify_path(argv[i], &path);
1844                 if (ret < 0) {
1845                         ret = send_va_buffer(fd, "%s: %s\n", argv[i],
1846                                 para_strerror(-ret));
1847                         if (ret < 0)
1848                                 return ret;
1849                         continue;
1850                 }
1851                 ret = stat(path, &statbuf);
1852                 if (ret < 0) {
1853                         ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1854                                 strerror(errno));
1855                         free(path);
1856                         if (ret < 0)
1857                                 return ret;
1858                         continue;
1859                 }
1860                 if (S_ISDIR(statbuf.st_mode))
1861                         ret = for_each_file_in_dir(path, add_one_audio_file,
1862                                 &pad);
1863                 else
1864                         ret = add_one_audio_file(path, &pad);
1865                 if (ret < 0) {
1866                         send_va_buffer(fd, "%s: %s\n", path, para_strerror(-ret));
1867                         free(path);
1868                         return ret;
1869                 }
1870                 free(path);
1871         }
1872         return 1;
1873
1874 }
1875
1876 /**
1877  * Flags used by the touch command.
1878  *
1879  * \sa com_touch().
1880  */
1881 enum touch_flags {
1882         /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1883         TOUCH_FLAG_FNM_PATHNAME = 1,
1884         /** Activates verbose mode. */
1885         TOUCH_FLAG_VERBOSE = 2
1886 };
1887
1888 /** Options used by com_touch(). */
1889 struct com_touch_options {
1890         /** New num_played value. */
1891         int32_t num_played;
1892         /** New last played count. */
1893         int64_t last_played;
1894         /** new lyrics id. */
1895         int32_t lyrics_id;
1896         /** new image id. */
1897         int32_t image_id;
1898         /** command line flags (see \ref touch_flags). */
1899         unsigned flags;
1900 };
1901
1902 /** Data passed to the action handler of com_touch(). */
1903 struct touch_action_data {
1904         /** Command line options (see \ref com_touch_options). */
1905         struct com_touch_options *cto;
1906         /** Message buffer. */
1907         struct para_buffer pb;
1908         /** How many audio files matched the given pattern. */
1909         unsigned num_matches;
1910 };
1911
1912 static int touch_audio_file(__a_unused struct osl_table *table,
1913                 struct osl_row *row, const char *name, void *data)
1914 {
1915         struct touch_action_data *tad = data;
1916         struct osl_object obj;
1917         struct afs_info old_afsi, new_afsi;
1918         int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1919                 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
1920         struct afsi_change_event_data aced;
1921
1922         ret = get_afsi_object_of_row(row, &obj);
1923         if (ret < 0) {
1924                 para_printf(&tad->pb, "%s: %s\n", name, para_strerror(-ret));
1925                 return 1;
1926         }
1927         ret = load_afsi(&old_afsi, &obj);
1928         if (ret < 0) {
1929                 para_printf(&tad->pb, "%s: %s\n", name, para_strerror(-ret));
1930                 return 1;
1931         }
1932         new_afsi = old_afsi;
1933         if (no_options) {
1934                 new_afsi.num_played++;
1935                 new_afsi.last_played = time(NULL);
1936                 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1937                         para_printf(&tad->pb, "%s: num_played = %u, "
1938                                 "last_played = now()\n", name,
1939                                 new_afsi.num_played);
1940         } else {
1941                 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1942                         para_printf(&tad->pb, "touching %s\n", name);
1943                 if (tad->cto->lyrics_id >= 0)
1944                         new_afsi.lyrics_id = tad->cto->lyrics_id;
1945                 if (tad->cto->image_id >= 0)
1946                         new_afsi.image_id = tad->cto->image_id;
1947                 if (tad->cto->num_played >= 0)
1948                         new_afsi.num_played = tad->cto->num_played;
1949                 if (tad->cto->last_played >= 0)
1950                         new_afsi.last_played = tad->cto->last_played;
1951         }
1952         tad->num_matches++;
1953         save_afsi(&new_afsi, &obj); /* in-place update */
1954         aced.aft_row = row;
1955         aced.old_afsi = &old_afsi;
1956         afs_event(AFSI_CHANGE, &tad->pb, &aced);
1957         return 1;
1958 }
1959
1960 static int com_touch_callback(const struct osl_object *query,
1961                 struct osl_object *result)
1962 {
1963         struct touch_action_data tad = {.cto = query->data};
1964         int ret;
1965         struct pattern_match_data pmd = {
1966                 .table = audio_file_table,
1967                 .loop_col_num = AFTCOL_HASH,
1968                 .match_col_num = AFTCOL_PATH,
1969                 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
1970                         .size = query->size - sizeof(*tad.cto)},
1971                 .data = &tad,
1972                 .action = touch_audio_file
1973         };
1974         if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
1975                 pmd.fnmatch_flags |= FNM_PATHNAME;
1976         ret = for_each_matching_row(&pmd);
1977         if (ret < 0)
1978                 para_printf(&tad.pb, "%s\n", para_strerror(-ret));
1979         else
1980                 if (!tad.num_matches)
1981                         para_printf(&tad.pb, "no matches\n");
1982         if (tad.pb.buf) {
1983                 result->data = tad.pb.buf;
1984                 result->size = tad.pb.size;
1985                 return 1;
1986         }
1987         return ret < 0? ret : 0;
1988 }
1989
1990 int com_touch(int fd, int argc, char * const * const argv)
1991 {
1992         struct com_touch_options cto = {
1993                 .num_played = -1,
1994                 .last_played = -1,
1995                 .lyrics_id = -1,
1996                 .image_id = -1
1997         };
1998         struct osl_object query = {.data = &cto, .size = sizeof(cto)},
1999                 result;
2000         int i, ret;
2001
2002
2003         for (i = 1; i < argc; i++) {
2004                 const char *arg = argv[i];
2005                 if (arg[0] != '-')
2006                         break;
2007                 if (!strcmp(arg, "--")) {
2008                         i++;
2009                         break;
2010                 }
2011                 if (!strncmp(arg, "-n", 2)) {
2012                         ret = para_atoi32(arg + 2, &cto.num_played);
2013                         if (ret < 0)
2014                                 return ret;
2015                         continue;
2016                 }
2017                 if (!strncmp(arg, "-l", 2)) {
2018                         ret = para_atoi64(arg + 2, &cto.last_played);
2019                         if (ret < 0)
2020                                 return ret;
2021                         continue;
2022                 }
2023                 if (!strncmp(arg, "-y", 2)) {
2024                         ret = para_atoi32(arg + 2, &cto.lyrics_id);
2025                         if (ret < 0)
2026                                 return ret;
2027                         continue;
2028                 }
2029                 if (!strncmp(arg, "-i", 2)) {
2030                         ret = para_atoi32(arg + 2, &cto.image_id);
2031                         if (ret < 0)
2032                                 return ret;
2033                         continue;
2034                 }
2035                 if (!strcmp(arg, "-p")) {
2036                         cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
2037                         continue;
2038                 }
2039                 if (!strcmp(arg, "-v")) {
2040                         cto.flags |= TOUCH_FLAG_VERBOSE;
2041                         continue;
2042                 }
2043                 break; /* non-option starting with dash */
2044         }
2045         if (i >= argc)
2046                 return -E_AFT_SYNTAX;
2047         ret = send_option_arg_callback_request(&query, argc - i,
2048                 argv + i, com_touch_callback, &result);
2049         if (!ret)
2050                 return 0;
2051         if (ret < 0) {
2052                 send_va_buffer(fd, "%s\n", para_strerror(-ret));
2053                 return ret;
2054         }
2055         ret = send_buffer(fd, (char *)result.data);
2056         free(result.data);
2057         return ret;
2058 }
2059
2060 /** Flags for com_rm(). */
2061 enum rm_flags {
2062         /** -v */
2063         RM_FLAG_VERBOSE = 1,
2064         /** -f */
2065         RM_FLAG_FORCE = 2,
2066         /** -p */
2067         RM_FLAG_FNM_PATHNAME = 4
2068 };
2069
2070 /** Data passed to the action handler of com_rm(). */
2071 struct com_rm_action_data {
2072         /** Command line flags ((see \ref rm_flags). */
2073         uint32_t flags;
2074         /** Message buffer. */
2075         struct para_buffer pb;
2076         /** Number of audio files removed. */
2077         unsigned num_removed;
2078 };
2079
2080 static int remove_audio_file(__a_unused struct osl_table *table,
2081                 struct osl_row *row, const char *name, void *data)
2082 {
2083         struct com_rm_action_data *crd = data;
2084         int ret;
2085
2086         if (crd->flags & RM_FLAG_VERBOSE)
2087                 para_printf(&crd->pb, "removing %s\n", name);
2088         afs_event(AUDIO_FILE_REMOVE, &crd->pb, row);
2089         ret = osl_del_row(audio_file_table, row);
2090         if (ret < 0)
2091                 para_printf(&crd->pb, "%s: %s\n", name, para_strerror(-ret));
2092         else
2093                 crd->num_removed++;
2094         return 1;
2095 }
2096
2097 static int com_rm_callback(const struct osl_object *query,
2098                 __a_unused struct osl_object *result)
2099 {
2100         struct com_rm_action_data crd = {.flags = *(uint32_t *)query->data};
2101         int ret;
2102         struct pattern_match_data pmd = {
2103                 .table = audio_file_table,
2104                 .loop_col_num = AFTCOL_HASH,
2105                 .match_col_num = AFTCOL_PATH,
2106                 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
2107                         .size = query->size - sizeof(uint32_t)},
2108                 .data = &crd,
2109                 .action = remove_audio_file
2110         };
2111         if (crd.flags & RM_FLAG_FNM_PATHNAME)
2112                 pmd.fnmatch_flags |= FNM_PATHNAME;
2113         ret = for_each_matching_row(&pmd);
2114         if (ret < 0)
2115                 para_printf(&crd.pb, "%s\n", para_strerror(-ret));
2116         if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
2117                 para_printf(&crd.pb, "no matches -- nothing removed\n");
2118         else {
2119                 if (crd.flags & RM_FLAG_VERBOSE)
2120                         para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
2121         }
2122         if (crd.pb.buf) {
2123                 result->data = crd.pb.buf;
2124                 result->size = crd.pb.size;
2125                 return 1;
2126         }
2127         return ret < 0? ret : 0;
2128 }
2129
2130 /* TODO options: -r (recursive) */
2131 int com_rm(int fd, int argc,  char * const * const argv)
2132 {
2133         uint32_t flags = 0;
2134         struct osl_object query = {.data = &flags, .size = sizeof(flags)},
2135                 result;
2136         int i, ret;
2137
2138         for (i = 1; i < argc; i++) {
2139                 const char *arg = argv[i];
2140                 if (arg[0] != '-')
2141                         break;
2142                 if (!strcmp(arg, "--")) {
2143                         i++;
2144                         break;
2145                 }
2146                 if (!strcmp(arg, "-f")) {
2147                         flags |= RM_FLAG_FORCE;
2148                         continue;
2149                 }
2150                 if (!strcmp(arg, "-p")) {
2151                         flags |= RM_FLAG_FNM_PATHNAME;
2152                         continue;
2153                 }
2154                 if (!strcmp(arg, "-v")) {
2155                         flags |= RM_FLAG_VERBOSE;
2156                         continue;
2157                 }
2158                 break;
2159         }
2160         if (i >= argc)
2161                 return -E_AFT_SYNTAX;
2162         ret = send_option_arg_callback_request(&query, argc - i, argv + i,
2163                 com_rm_callback, &result);
2164         if (!ret)
2165                 return 0;
2166         if (ret < 0) {
2167                 send_va_buffer(fd, "%s\n", para_strerror(-ret));
2168                 return ret;
2169         }
2170         ret = send_buffer(fd, (char *)result.data);
2171         free(result.data);
2172         return ret;
2173 }
2174
2175 /**
2176  * Flags used by the cpsi command.
2177  *
2178  * \sa com_cpsi().
2179  */
2180 enum cpsi_flags {
2181         /** Whether the lyrics id should be copied. */
2182         CPSI_FLAG_COPY_LYRICS_ID = 1,
2183         /** Whether the image id should be copied. */
2184         CPSI_FLAG_COPY_IMAGE_ID = 2,
2185         /** Whether the lastplayed time should be copied. */
2186         CPSI_FLAG_COPY_LASTPLAYED = 4,
2187         /** Whether the numplayed count should be copied. */
2188         CPSI_FLAG_COPY_NUMPLAYED = 8,
2189         /** Whether the attributes should be copied. */
2190         CPSI_FLAG_COPY_ATTRIBUTES = 16,
2191         /** Activates verbose mode. */
2192         CPSI_FLAG_VERBOSE = 32,
2193 };
2194
2195 /** Data passed to the action handler of com_cpsi(). */
2196 struct cpsi_action_data {
2197         /** command line flags (see \ref cpsi_flags). */
2198         unsigned flags;
2199         /** Number of audio files changed. */
2200         unsigned num_copied;
2201         /** Message buffer. */
2202         struct para_buffer pb;
2203         /** Values are copied from here. */
2204         struct afs_info source_afsi;
2205 };
2206
2207 static int copy_selector_info(__a_unused struct osl_table *table,
2208                 struct osl_row *row, const char *name, void *data)
2209 {
2210         struct cpsi_action_data *cad = data;
2211         struct osl_object target_afsi_obj;
2212         int ret;
2213         struct afs_info old_afsi, target_afsi;
2214         struct afsi_change_event_data aced;
2215
2216         ret = get_afsi_object_of_row(row, &target_afsi_obj);
2217         if (ret < 0)
2218                 return ret;
2219         load_afsi(&target_afsi, &target_afsi_obj);
2220         old_afsi = target_afsi;
2221         if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
2222                 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2223         if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
2224                 target_afsi.image_id = cad->source_afsi.image_id;
2225         if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
2226                 target_afsi.last_played = cad->source_afsi.last_played;
2227         if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
2228                 target_afsi.num_played = cad->source_afsi.num_played;
2229         if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
2230                 target_afsi.attributes = cad->source_afsi.attributes;
2231         save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2232         cad->num_copied++;
2233         if (cad->flags & CPSI_FLAG_VERBOSE)
2234                 para_printf(&cad->pb, "copied afsi to %s\n", name);
2235         aced.aft_row = row;
2236         aced.old_afsi = &old_afsi;
2237         afs_event(AFSI_CHANGE, &cad->pb, &aced);
2238         return 1;
2239 }
2240
2241 static int com_cpsi_callback(const struct osl_object *query,
2242                 struct osl_object *result)
2243 {
2244         struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
2245         int ret;
2246         char *source_path = (char *)query->data + sizeof(cad.flags);
2247
2248         ret = get_afsi_of_path(source_path, &cad.source_afsi);
2249         if (ret < 0)
2250                 goto out;
2251         struct pattern_match_data pmd = {
2252                 .table = audio_file_table,
2253                 .loop_col_num = AFTCOL_HASH,
2254                 .match_col_num = AFTCOL_PATH,
2255                 .patterns = {.data = source_path + strlen(source_path) + 1,
2256                         .size = query->size - sizeof(cad.flags)
2257                                 - strlen(source_path) - 1},
2258                 .data = &cad,
2259                 .action = copy_selector_info
2260         };
2261         ret = for_each_matching_row(&pmd);
2262 out:
2263         if (ret < 0)
2264                 para_printf(&cad.pb, "%s\n", para_strerror(-ret));
2265         if (cad.flags & CPSI_FLAG_VERBOSE) {
2266                 if (cad.num_copied)
2267                         para_printf(&cad.pb, "copied requested afsi from %s "
2268                                 "to %u files\n",
2269                                 source_path, cad.num_copied);
2270                 else
2271                         para_printf(&cad.pb, "nothing copied\n");
2272         }
2273         if (cad.pb.buf) {
2274                 result->data = cad.pb.buf;
2275                 result->size = cad.pb.size;
2276                 return 1;
2277         }
2278         return ret < 0? ret : 0;
2279 }
2280
2281 int com_cpsi(int fd, int argc,  char * const * const argv)
2282 {
2283         unsigned flags = 0;
2284         int i, ret;
2285         struct osl_object options = {.data = &flags, .size = sizeof(flags)},
2286                 result;
2287
2288         for (i = 1; i < argc; i++) {
2289                 const char *arg = argv[i];
2290                 if (arg[0] != '-')
2291                         break;
2292                 if (!strcmp(arg, "--")) {
2293                         i++;
2294                         break;
2295                 }
2296                 if (!strcmp(arg, "-y")) {
2297                         flags |= CPSI_FLAG_COPY_LYRICS_ID;
2298                         continue;
2299                 }
2300                 if (!strcmp(arg, "-i")) {
2301                         flags |= CPSI_FLAG_COPY_IMAGE_ID;
2302                         continue;
2303                 }
2304                 if (!strcmp(arg, "-l")) {
2305                         flags |= CPSI_FLAG_COPY_LASTPLAYED;
2306                         continue;
2307                 }
2308                 if (!strcmp(arg, "-n")) {
2309                         flags |= CPSI_FLAG_COPY_NUMPLAYED;
2310                         continue;
2311                 }
2312                 if (!strcmp(arg, "-a")) {
2313                         flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2314                         continue;
2315                 }
2316                 if (!strcmp(arg, "-v")) {
2317                         flags |= CPSI_FLAG_VERBOSE;
2318                         continue;
2319                 }
2320                 break;
2321         }
2322         if (i + 1 >= argc) /* need at least souce file and pattern */
2323                 return -E_AFT_SYNTAX;
2324         if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2325                 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2326         ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2327                 com_cpsi_callback, &result);
2328         if (!ret)
2329                 return 0;
2330         if (ret < 0) {
2331                 send_va_buffer(fd, "%s\n", para_strerror(-ret));
2332                 return ret;
2333         }
2334         ret = send_buffer(fd, (char *)result.data);
2335         free(result.data);
2336         return ret;
2337 }
2338
2339 /* TODO: optionally fix problems by removing offending rows */
2340 static int check_audio_file(struct osl_row *row, void *data)
2341 {
2342         char *path;
2343         struct para_buffer *pb = data;
2344         struct stat statbuf;
2345         int ret = get_audio_file_path_of_row(row, &path);
2346         struct afs_info afsi;
2347         char *blob_name;
2348
2349         if (ret < 0) {
2350                 para_printf(pb, "%s\n", para_strerror(-ret));
2351                 return 1;
2352         }
2353         if (stat(path, &statbuf) < 0)
2354                 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2355         else {
2356                 if (!S_ISREG(statbuf.st_mode))
2357                         para_printf(pb, "%s: not a regular file\n", path);
2358         }
2359         ret = get_afsi_of_row(row, &afsi);
2360         if (ret < 0) {
2361                 para_printf(pb, "%s: %s\n", path, para_strerror(-ret));
2362                 return 1;
2363         }
2364         ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2365         if (ret < 0)
2366                 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2367                         para_strerror(-ret));
2368         ret = img_get_name_by_id(afsi.image_id, &blob_name);
2369         if (ret < 0)
2370                 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2371                         para_strerror(-ret));
2372         return 1;
2373 }
2374
2375 /**
2376  * Check the audio file table for inconsistencies.
2377  *
2378  * \param query Unused.
2379  * \param result Contains message string upon return.
2380  *
2381  * This function always succeeds.
2382  *
2383  * \sa com_check().
2384  */
2385 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
2386 {
2387         struct para_buffer pb = {.buf = NULL};
2388
2389         para_printf(&pb, "checking audio file table...\n");
2390         audio_file_loop(&pb, check_audio_file);
2391         result->data = pb.buf;
2392         result->size = pb.size;
2393         return 1;
2394
2395 }
2396
2397 /**
2398  * Close the audio file table.
2399  *
2400  * \param flags Usual flags that are passed to osl_close_table().
2401  *
2402  * \sa osl_close_table().
2403  */
2404 static void aft_close(void)
2405 {
2406         osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2407         audio_file_table = NULL;
2408 }
2409
2410 /**
2411  * Open the audio file table.
2412  *
2413  * \param dir The database directory.
2414  *
2415  * \return Standard.
2416  *
2417  * \sa osl_open_table().
2418  */
2419 static int aft_open(const char *dir)
2420 {
2421         int ret;
2422
2423         audio_file_table_desc.dir = dir;
2424         ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
2425         if (ret >= 0) {
2426                 unsigned num;
2427                 osl_get_num_rows(audio_file_table, &num);
2428                 PARA_INFO_LOG("audio file table contains %d files\n", num);
2429                 return ret;
2430         }
2431         PARA_INFO_LOG("failed to open audio file table\n");
2432         audio_file_table = NULL;
2433         if (ret >= 0 || is_errno(-ret, ENOENT))
2434                 return 1;
2435         return ret;
2436 }
2437
2438 static int aft_create(const char *dir)
2439 {
2440         audio_file_table_desc.dir = dir;
2441         return osl_create_table(&audio_file_table_desc);
2442 }
2443
2444 static int clear_attribute(struct osl_row *row, void *data)
2445 {
2446         struct rmatt_event_data *red = data;
2447         struct afs_info afsi;
2448         struct osl_object obj;
2449         int ret = get_afsi_object_of_row(row, &obj);
2450         uint64_t mask = ~(1ULL << red->bitnum);
2451
2452         if (ret < 0)
2453                 return ret;
2454         ret = load_afsi(&afsi, &obj);
2455         if (ret < 0)
2456                 return ret;
2457         afsi.attributes &= mask;
2458         save_afsi(&afsi, &obj);
2459         return 1;
2460 }
2461
2462 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2463                 void *data)
2464 {
2465         switch(event) {
2466         case ATTRIBUTE_REMOVE: {
2467                 const struct rmatt_event_data *red = data;
2468                 para_printf(pb, "clearing attribute %s (bit %u) from all "
2469                         "entries in the audio file table\n", red->name,
2470                         red->bitnum);
2471                 return audio_file_loop(data, clear_attribute);
2472                 }
2473         default:
2474                 return 1;
2475         }
2476 }
2477
2478 void aft_init(struct afs_table *t)
2479 {
2480         t->name = audio_file_table_desc.name;
2481         t->open = aft_open;
2482         t->close = aft_close;
2483         t->create = aft_create;
2484         t->event_handler = aft_event_handler;
2485 }