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