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