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