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