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