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