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