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