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