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