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