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