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