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