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