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