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