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