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