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