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