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