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