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