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