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