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