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