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