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