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