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