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