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