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