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