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