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