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