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