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