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