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