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