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