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