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