04846a7658e34979f6bdcab62669b2c1c826a1a6
[paraslash.git] / aft.c
1 #include "para.h"
2 #include "error.h"
3 #include <sys/mman.h>
4 #include <fnmatch.h>
5 #include "afh.h"
6 #include "afs.h"
7 #include "net.h"
8 #include "string.h"
9 #include "vss.h"
10
11 #define AFS_AUDIO_FILE_DIR "/home/mp3"
12
13 static struct osl_table *audio_file_table;
14
15 /**
16  * Describes the layout of the mmapped-afs info struct.
17  *
18  * \sa struct afs_info.
19  */
20 enum afsi_offsets {
21         /** Where .last_played is stored. */
22         AFSI_LAST_PLAYED_OFFSET = 0,
23         /** Storage position of the attributes bitmap. */
24         AFSI_ATTRIBUTES_OFFSET = 8,
25         /** Storage position of the .num_played field. */
26         AFSI_NUM_PLAYED_OFFSET = 16,
27         /** Storage position of the .image_id field. */
28         AFSI_IMAGE_ID_OFFSET = 20,
29         /** Storage position of the .lyrics_id field. */
30         AFSI_LYRICS_ID_OFFSET = 24,
31         /** Storage position of the .audio_format_id field. */
32         AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
33         /** On-disk storage space needed. */
34         AFSI_SIZE = 29
35 };
36
37 /**
38  * Convert a struct afs_info to an osl object.
39  *
40  * \param afsi Pointer to the audio file info to be converted.
41  * \param obj Result pointer.
42  *
43  * \sa load_afsi().
44  */
45 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
46 {
47         char *buf = obj->data;
48
49         write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
50         write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
51         write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
52         write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
53         write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
54         write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
55                 afsi->audio_format_id);
56 }
57
58 /**
59  *  Get the audio file selector info struct stored in an osl object.
60  *
61  * \param afsi Points to the audio_file info structure to be filled in.
62  * \param obj The osl object holding the data.
63  *
64  * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
65  *
66  * \sa save_afsi().
67  */
68 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
69 {
70         char *buf = obj->data;
71         if (obj->size < AFSI_SIZE)
72                 return -E_BAD_AFS;
73         afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
74         afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
75         afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
76         afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
77         afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
78         afsi->audio_format_id = read_u8(buf +
79                 AFSI_AUDIO_FORMAT_ID_OFFSET);
80         return 1;
81 }
82
83 /** The columns of the audio file table. */
84 enum audio_file_table_columns {
85         /** The hash on the content of the audio file. */
86         AFTCOL_HASH,
87         /** The full path in the filesystem. */
88         AFTCOL_PATH,
89         /** The audio file selector info. */
90         AFTCOL_AFSI,
91         /** The audio format handler info. */
92         AFTCOL_AFHI,
93         /** The chunk table info and the chunk table of the audio file. */
94         AFTCOL_CHUNKS,
95         /** The number of columns of this table. */
96         NUM_AFT_COLUMNS
97 };
98
99 static struct osl_column_description aft_cols[] = {
100         [AFTCOL_HASH] = {
101                 .storage_type = OSL_MAPPED_STORAGE,
102                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
103                 .name = "hash",
104                 .compare_function = osl_hash_compare,
105                 .data_size = HASH_SIZE
106         },
107         [AFTCOL_PATH] = {
108                 .storage_type = OSL_MAPPED_STORAGE,
109                 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
110                 .name = "path",
111                 .compare_function = string_compare,
112         },
113         [AFTCOL_AFSI] = {
114                 .storage_type = OSL_MAPPED_STORAGE,
115                 .storage_flags = OSL_FIXED_SIZE,
116                 .name = "afs_info",
117                 .data_size = AFSI_SIZE
118         },
119         [AFTCOL_AFHI] = {
120                 .storage_type = OSL_MAPPED_STORAGE,
121                 .name = "afh_info",
122         },
123         [AFTCOL_CHUNKS] = {
124                 .storage_type = OSL_DISK_STORAGE,
125                 .name = "chunks",
126         }
127 };
128
129 static struct osl_table_description audio_file_table_desc = {
130         .name = "audio_files",
131         .num_columns = NUM_AFT_COLUMNS,
132         .flags = OSL_LARGE_TABLE,
133         .column_descriptions = aft_cols
134 };
135
136 static char *prefix_path(const char *prefix, int len, const char *path)
137 {
138         int speclen;
139         char *n;
140
141         for (;;) {
142                 char c;
143                 if (*path != '.')
144                         break;
145                 c = path[1];
146                 /* "." */
147                 if (!c) {
148                         path++;
149                         break;
150                 }
151                 /* "./" */
152                 if (c == '/') {
153                         path += 2;
154                         continue;
155                 }
156                 if (c != '.')
157                         break;
158                 c = path[2];
159                 if (!c)
160                         path += 2;
161                 else if (c == '/')
162                         path += 3;
163                 else
164                         break;
165                 /* ".." and "../" */
166                 /* Remove last component of the prefix */
167                 do {
168                         if (!len)
169                                 return NULL;
170                         len--;
171                 } while (len && prefix[len-1] != '/');
172                 continue;
173         }
174         if (!len)
175                 return para_strdup(path);
176         speclen = strlen(path);
177         n = para_malloc(speclen + len + 1);
178         memcpy(n, prefix, len);
179         memcpy(n + len, path, speclen+1);
180         return n;
181 }
182
183 /*
184  * We fundamentally don't like some paths: we don't want
185  * dot or dot-dot anywhere.
186  *
187  * Also, we don't want double slashes or slashes at the
188  * end that can make pathnames ambiguous.
189  */
190 static int verify_dotfile(const char *rest)
191 {
192         /*
193          * The first character was '.', but that has already been discarded, we
194          * now test the rest.
195          */
196         switch (*rest) {
197         /* "." is not allowed */
198         case '\0': case '/':
199                 return 1;
200
201         case '.':
202                 if (rest[1] == '\0' || rest[1] == '/')
203                         return -1;
204         }
205         return 1;
206 }
207
208 static int verify_path(const char *orig_path, char **resolved_path)
209 {
210         char c;
211         const char prefix[] = AFS_AUDIO_FILE_DIR "/";
212         const char *path = orig_path;
213         const size_t prefix_len = strlen(prefix);
214
215         c = *path++;
216         if (!c)
217                 goto bad_path;
218         while (c) {
219                 if (c == '/') {
220                         c = *path++;
221                         switch (c) {
222                         default:
223                                 continue;
224                         case '/': /* double slash */
225                                 goto bad_path;
226                         case '.':
227                                 if (verify_dotfile(path) < 0)
228                                         goto bad_path;
229                         }
230                 }
231                 c = *path++;
232         }
233         if (*orig_path != '/')
234                 *resolved_path = prefix_path(prefix, prefix_len, orig_path);
235         else
236                 *resolved_path = para_strdup(orig_path);
237         return 1;
238 bad_path:
239         return -E_BAD_PATH;
240 }
241
242 enum afhi_offsets {
243         AFHI_SECONDS_TOTAL_OFFSET = 0,
244         AFHI_BITRATE_OFFSET = 4,
245         AFHI_FREQUENCY_OFFSET = 8,
246         AFHI_CHANNELS_OFFSET = 12,
247         AFHI_INFO_STRING_OFFSET = 13,
248         MIN_AFHI_SIZE = 14
249 };
250
251 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
252 {
253         if (!afhi)
254                 return 0;
255         return strlen(afhi->info_string) + MIN_AFHI_SIZE;
256 }
257
258 static void save_afhi(struct audio_format_info *afhi, char *buf)
259 {
260         if (!afhi)
261                 return;
262         write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
263                 afhi->seconds_total);
264         write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
265         write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
266         write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
267         strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
268         PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
269 }
270
271 static void load_afhi(const char *buf, struct audio_format_info *afhi)
272 {
273         afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
274         afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
275         afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
276         afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
277         strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
278 }
279
280 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
281 {
282         if (!afhi)
283                 return 0;
284         return 4 * afhi->chunks_total + 20;
285
286 }
287
288 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
289 enum chunk_info_offsets{
290         /** The total number of chunks (4 bytes). */
291         CHUNKS_TOTAL_OFFSET = 0,
292         /** The length of the audio file header (4 bytes). */
293         HEADER_LEN_OFFSET = 4,
294         /** The start of the audio file header (4 bytes). */
295         HEADER_OFFSET_OFFSET = 8,
296         /** The seconds part of the chunk time (4 bytes). */
297         CHUNK_TV_TV_SEC_OFFSET = 12,
298         /** The microseconds part of the chunk time (4 bytes). */
299         CHUNK_TV_TV_USEC = 16,
300         /** Chunk table entries start here. */
301         CHUNK_TABLE_OFFSET = 20,
302 };
303
304 /* TODO: audio format handlers could just produce this */
305 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
306 {
307         int i;
308
309         if (!afhi)
310                 return;
311         write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
312         write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
313         write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
314         write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
315         write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
316         for (i = 0; i < afhi->chunks_total; i++)
317                 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
318 }
319
320 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
321 {
322         char *buf = obj->data;
323         int i;
324
325         if (obj->size < CHUNK_TABLE_OFFSET)
326                 return -E_BAD_DATA_SIZE;
327
328         afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
329         afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
330         afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
331         afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
332         afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
333
334         if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
335                 return -E_BAD_DATA_SIZE;
336         afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
337         for (i = 0; i < afhi->chunks_total; i++)
338                 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
339         return 1;
340 }
341
342 /**
343  * Get the row of the audio file table corresponding to the given path.
344  *
345  * \param path The full path of the audio file.
346  * \param row Result pointer.
347  *
348  * \return The return value of the underlying call to osl_get_row().
349  */
350 int aft_get_row_of_path(char *path, struct osl_row **row)
351 {
352         struct osl_object obj = {.data = path, .size = strlen(path) + 1};
353
354         return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
355 }
356
357 /**
358  * Get the row of the audio file table corresponding to the given hash value.
359  *
360  * \param hash The hash value of the desired audio file.
361  * \param row resul pointer.
362  *
363  * \return The return value of the underlying call to osl_get_row().
364  */
365 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
366 {
367         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
368         return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
369 }
370
371 /**
372  * Get the osl object holding the audio file selector info of a row.
373  *
374  * \param row Pointer to a row in the audio file table.
375  * \param obj Result pointer.
376  *
377  * \return The return value of the underlying call to osl_get_object().
378  */
379 int get_afsi_object_of_row(const void *row, struct osl_object *obj)
380 {
381         return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
382 }
383
384 /**
385  * Get the osl object holding the audio file selector info, given a path.
386  *
387  *
388  * \param path The full path of the audio file.
389  * \param obj Result pointer.
390  *
391  * \return Positive on success, negative on errors.
392  */
393 int get_afsi_object_of_path(char *path, struct osl_object *obj)
394 {
395         struct osl_row *row;
396         int ret = aft_get_row_of_path(path, &row);
397         if (ret < 0)
398                 return ret;
399         return get_afsi_object_of_row(row, obj);
400 }
401
402 /**
403  * Get the audio file selector info, given a row of the audio file table.
404  *
405  * \param row Pointer to a row in the audio file table.
406  * \param afsi Result pointer.
407  *
408  * \return Positive on success, negative on errors.
409  */
410 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
411 {
412         struct osl_object obj;
413         int ret = get_afsi_object_of_row(row, &obj);
414         if (ret < 0)
415                 return ret;
416         return load_afsi(afsi, &obj);
417 }
418
419 /**
420  * Get the path of an audio file, given a row of the audio file table.
421  *
422  * \param row Pointer to a row in the audio file table.
423  * \param path Result pointer.
424  *
425  * \return Positive on success, negative on errors.
426  */
427 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
428 {
429         struct osl_object path_obj;
430         int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
431                 &path_obj);
432         if (ret < 0)
433                 return ret;
434         *path = path_obj.data;
435         return 1;
436 }
437
438 /**
439  * Get the object containing the hash value of an audio file, given a row.
440  *
441  * \param row Pointer to a row of the audio file table.
442  * \param obj Result pointer.
443  *
444  * \return The return value of the underlying call to osl_get_object().
445  *
446  * \sa get_hash_of_row().
447  */
448 int get_hash_object_of_aft_row(const void *row, struct osl_object *obj)
449 {
450         return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
451 }
452
453 /**
454  * Get the hash value of an audio file, given a row of the audio file table.
455  *
456  * \param row Pointer to a row of the audio file table.
457  * \param hash Result pointer.
458  *
459  * \a hash points to mapped data and must not be freed by the caller.
460  *
461  * \return The return value of the underlying call to
462  * get_hash_object_of_aft_row().
463  */
464 static int get_hash_of_row(const void *row, HASH_TYPE **hash)
465 {
466         struct osl_object obj;
467         int ret = get_hash_object_of_aft_row(row, &obj);
468
469         if (ret < 0)
470                 return ret;
471         *hash = obj.data;
472         return 1;
473 }
474
475 /**
476  * Get the audio format handler info, given a row of the audio file table.
477  *
478  * \param row Pointer to a row of the audio file table.
479  * \param afhi Result pointer.
480  *
481  * \return The return value of the underlying call to osl_get_object().
482  *
483  * \sa get_chunk_table_of_row().
484  */
485 int get_afhi_of_row(const void *row, struct audio_format_info *afhi)
486 {
487         struct osl_object obj;
488         int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
489                 &obj);
490         if (ret < 0)
491                 return ret;
492         load_afhi(obj.data, afhi);
493         return 1;
494 }
495
496 /**
497  * Get the chunk table of an audio file, given a row of the audio file table.
498  *
499  * \param row Pointer to a row of the audio file table.
500  * \param afhi Result pointer.
501  *
502  * \return The return value of the underlying call to osl_open_disk_object().
503  *
504  * \sa get_afhi_of_row().
505  */
506 int get_chunk_table_of_row(const void *row, struct audio_format_info *afhi)
507 {
508         struct osl_object obj;
509         int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
510                 &obj);
511         if (ret < 0)
512                 return ret;
513         ret = load_chunk_info(&obj, afhi);
514         osl_close_disk_object(&obj);
515         return ret;
516 }
517
518 /**
519  * Mmap the given audio file and update statistics.
520  *
521  * \param aft_row Determines the audio file to be opened and updated.
522  * \param afd Result pointer.
523  *
524  * On success, the numplayed field of the audio file selector info is increased
525  * and the lastplayed time is set to the current time. Finally, the score of
526  * the audio file is updated.
527  *
528  * \return Positive on success, negative on errors.
529  */
530 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
531 {
532         HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
533         struct osl_object afsi_obj;
534         struct afs_info new_afsi;
535         int ret = get_hash_of_row(aft_row, &aft_hash);
536
537         if (ret < 0)
538                 return ret;
539         ret = get_audio_file_path_of_row(aft_row, &afd->path);
540         if (ret < 0)
541                 return ret;
542         ret = get_afsi_object_of_row(aft_row, &afsi_obj);
543         if (ret < 0)
544                 return ret;
545         ret = load_afsi(&afd->afsi, &afsi_obj);
546         if (ret < 0)
547                 return ret;
548         ret = get_afhi_of_row(aft_row, &afd->afhi);
549         if (ret < 0)
550                 return ret;
551         ret = get_chunk_table_of_row(aft_row, &afd->afhi);
552         if (ret < 0)
553                 return ret;
554         ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
555         if (ret < 0)
556                 goto err;
557         hash_function(afd->map.data, afd->map.size, file_hash);
558         ret = -E_HASH_MISMATCH;
559         if (hash_compare(file_hash, aft_hash))
560                 goto err;
561         new_afsi = afd->afsi;
562         new_afsi.num_played++;
563         new_afsi.last_played = time(NULL);
564         save_afsi(&new_afsi, &afsi_obj); /* in-place update */
565         if (afd->current_play_mode == PLAY_MODE_PLAYLIST)
566                 ret = playlist_update_audio_file(aft_row);
567         else
568                 ret = mood_update_audio_file(aft_row, &afd->afsi);
569         return ret;
570 err:
571         free(afd->afhi.chunk_table);
572         return ret;
573 }
574
575 time_t now;
576
577 static int get_local_time(uint64_t *seconds, char *buf, size_t size)
578 {
579         struct tm t;
580
581         if (!localtime_r((time_t *)seconds, &t))
582                 return -E_LOCALTIME;
583         if (*seconds + 6 * 30 * 24 * 3600 > now) {
584                 if (!strftime(buf, size, "%b %e %k:%M", &t))
585                         return -E_STRFTIME;
586                 return 1;
587         }
588         if (!strftime(buf, size, "%b %e  %Y", &t))
589                 return -E_STRFTIME;
590         return 1;
591 }
592
593 #define GET_NUM_DIGITS(x, num) { \
594         typeof((x)) _tmp = PARA_ABS(x); \
595         *num = 1; \
596         if ((x)) \
597                 while ((_tmp) > 9) { \
598                         (_tmp) /= 10; \
599                         (*num)++; \
600                 } \
601         }
602
603 static short unsigned get_duration(int seconds_total, char *buf, short unsigned max_width)
604 {
605         short unsigned width;
606         int s = seconds_total;
607         unsigned hours = s / 3600, mins = (s % 3600) / 60, secs = s % 60;
608
609         if (s < 3600) { /* less than one hour => m:ss or mm:ss */
610                 GET_NUM_DIGITS(mins, &width); /* 1 or 2 */
611                 width += 3; /* 4 or 5 */
612                 if (buf)
613                         sprintf(buf, "%*u:%02u", max_width - width + 1, mins, secs);
614                 return width;
615         }
616         /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
617         GET_NUM_DIGITS(hours, &width);
618         width += 6;
619         if (buf)
620                 sprintf(buf, "%*u:%02u:%02u", max_width - width + 1, hours, mins, secs);
621         return width;
622 }
623
624 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
625 {
626         char *att_text, *att_line;
627
628         get_attribute_text(&afsi->attributes, " ", &att_text);
629         if (!att_text)
630                 return para_strdup(att_bitmap);
631         att_line = make_message("%s (%s)", att_bitmap, att_text);
632         free(att_text);
633         return att_line;
634 }
635
636 static char *make_lyrics_line(struct afs_info *afsi)
637 {
638         char *lyrics_name;
639         lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
640         if (!lyrics_name)
641                 return make_message("%u", afsi->lyrics_id);
642         return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
643 }
644
645 static char *make_image_line(struct afs_info *afsi)
646 {
647         char *image_name;
648         img_get_name_by_id(afsi->image_id, &image_name);
649         if (!image_name)
650                 return make_message("%u", afsi->image_id);
651         return make_message("%u (%s)", afsi->image_id, image_name);
652 }
653
654 static int print_list_item(struct ls_data *d, struct ls_options *opts,
655         struct para_buffer *b)
656 {
657         int ret;
658         char att_buf[65];
659         char last_played_time[30];
660         char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
661         char score_buf[30] = "";
662         struct afs_info *afsi = &d->afsi;
663         struct audio_format_info *afhi = &d->afhi;
664         struct ls_widths *w = &opts->widths;
665         int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
666
667         if (opts->mode == LS_MODE_SHORT) {
668                 para_printf(b, "%s\n", d->path);
669                 return 1;
670         }
671         get_attribute_bitmap(&afsi->attributes, att_buf);
672         ret = get_local_time(&afsi->last_played, last_played_time,
673                 sizeof(last_played_time));
674         if (ret < 0)
675                 return ret;
676         get_duration(afhi->seconds_total, duration_buf, w->duration_width);
677         if (have_score) {
678                 if (opts->mode == LS_MODE_LONG)
679                         sprintf(score_buf, "%*li ", w->score_width, d->score);
680                 else
681                         sprintf(score_buf, "%li ", d->score);
682         }
683
684         if (opts->mode == LS_MODE_LONG) {
685                 para_printf(b,
686                         "%s"    /* score */
687                         "%s "   /* attributes */
688                         "%*d "  /* image_id  */
689                         "%*d "  /* lyrics_id */
690                         "%*d "  /* bitrate */
691                         "%s "   /* audio format */
692                         "%*d "  /* frequency */
693                         "%d "   /* channels */
694                         "%s "   /* duration */
695                         "%*d "  /* num_played */
696                         "%s "   /* last_played */
697                         "%s\n", /* path */
698                         score_buf,
699                         att_buf,
700                         w->image_id_width, afsi->image_id,
701                         w->lyrics_id_width, afsi->lyrics_id,
702                         w->bitrate_width, afhi->bitrate,
703                         audio_format_name(afsi->audio_format_id),
704                         w->frequency_width, afhi->frequency,
705                         afhi->channels,
706                         duration_buf,
707                         w->num_played_width, afsi->num_played,
708                         last_played_time,
709                         d->path
710                 );
711                 return 1;
712         }
713         if (opts->mode == LS_MODE_VERBOSE) {
714                 char asc_hash[2 * HASH_SIZE + 1];
715                 char *att_line, *lyrics_line, *image_line;
716
717                 hash_to_asc(d->hash, asc_hash);
718                 att_line = make_attribute_line(att_buf, afsi);
719                 lyrics_line = make_lyrics_line(afsi);
720                 image_line = make_image_line(afsi);
721                 para_printf(b,
722                         "%s: %s\n" /* path */
723                         "%s%s%s" /* score */
724                         "attributes: %s\n"
725                         "hash: %s\n"
726                         "image_id: %s\n"
727                         "lyrics_id: %s\n"
728                         "bitrate: %dkbit/s\n"
729                         "format: %s\n"
730                         "frequency: %dHz\n"
731                         "channels: %d\n"
732                         "duration: %s\n"
733                         "num_played: %d\n"
734                         "last_played: %s\n\n",
735                         (opts->flags & LS_FLAG_FULL_PATH)?
736                                 "path" : "file", d->path,
737                         have_score? "score: " : "", score_buf,
738                                 have_score? "\n" : "",
739                         att_line,
740                         asc_hash,
741                         image_line,
742                         lyrics_line,
743                         afhi->bitrate,
744                         audio_format_name(afsi->audio_format_id),
745                         afhi->frequency,
746                         afhi->channels,
747                         duration_buf,
748                         afsi->num_played,
749                         last_played_time
750                 );
751                 free(att_line);
752                 free(lyrics_line);
753                 free(image_line);
754                 return 1;
755         }
756         return 1;
757 }
758
759 static int ls_audio_format_compare(const void *a, const void *b)
760 {
761         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
762         return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
763 }
764
765 static int ls_duration_compare(const void *a, const void *b)
766 {
767         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
768         return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
769 }
770
771 static int ls_bitrate_compare(const void *a, const void *b)
772 {
773         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
774         return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
775 }
776
777 static int ls_lyrics_id_compare(const void *a, const void *b)
778 {
779         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
780         return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
781 }
782
783 static int ls_image_id_compare(const void *a, const void *b)
784 {
785         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
786         return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
787 }
788
789 static int ls_channels_compare(const void *a, const void *b)
790 {
791         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
792         return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
793 }
794
795 static int ls_frequency_compare(const void *a, const void *b)
796 {
797         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
798         return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
799 }
800
801 static int ls_num_played_compare(const void *a, const void *b)
802 {
803         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
804         return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
805 }
806
807 static int ls_last_played_compare(const void *a, const void *b)
808 {
809         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
810         return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
811 }
812
813 static int ls_score_compare(const void *a, const void *b)
814 {
815         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
816         return NUM_COMPARE(d1->score, d2->score);
817 }
818
819 static int ls_path_compare(const void *a, const void *b)
820 {
821         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
822         return strcmp(d1->path, d2->path);
823 }
824
825 static int sort_matching_paths(struct ls_options *options)
826 {
827         size_t nmemb = options->num_matching_paths;
828         size_t size = sizeof(uint32_t);
829         int (*compar)(const void *, const void *);
830         int i;
831
832         options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
833         for (i = 0; i < nmemb; i++)
834                 options->data_ptr[i] = options->data + i;
835
836         /* In these cases the array is already sorted */
837         if (options->sorting == LS_SORT_BY_PATH
838                 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
839                 && (options->flags & LS_FLAG_FULL_PATH))
840                 return 1;
841         if (options->sorting == LS_SORT_BY_SCORE &&
842                         options->flags & LS_FLAG_ADMISSIBLE_ONLY)
843                 return 1;
844
845         switch (options->sorting) {
846         case LS_SORT_BY_PATH:
847                 compar = ls_path_compare; break;
848         case LS_SORT_BY_SCORE:
849                 compar = ls_score_compare; break;
850         case LS_SORT_BY_LAST_PLAYED:
851                 compar = ls_last_played_compare; break;
852         case LS_SORT_BY_NUM_PLAYED:
853                 compar = ls_num_played_compare; break;
854         case LS_SORT_BY_FREQUENCY:
855                 compar = ls_frequency_compare; break;
856         case LS_SORT_BY_CHANNELS:
857                 compar = ls_channels_compare; break;
858         case LS_SORT_BY_IMAGE_ID:
859                 compar = ls_image_id_compare; break;
860         case LS_SORT_BY_LYRICS_ID:
861                 compar = ls_lyrics_id_compare; break;
862         case LS_SORT_BY_BITRATE:
863                 compar = ls_bitrate_compare; break;
864         case LS_SORT_BY_DURATION:
865                 compar = ls_duration_compare; break;
866         case LS_SORT_BY_AUDIO_FORMAT:
867                 compar = ls_audio_format_compare; break;
868         default:
869                 return -E_BAD_SORT;
870         }
871         qsort(options->data_ptr, nmemb, size, compar);
872         return 1;
873 }
874
875 /* row is either an aft_row or a row of the score table */
876 /* TODO: Only compute widths if we need them */
877 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
878 {
879         int ret, i;
880         struct ls_options *options = ls_opts;
881         struct ls_data *d;
882         struct ls_widths *w;
883         unsigned short num_digits;
884         unsigned tmp;
885         struct osl_row *aft_row;
886         long score;
887         char *path;
888
889         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
890                 ret = get_score_and_aft_row(row, &score, &aft_row);
891                 if (ret < 0)
892                         return ret;
893         } else
894                 aft_row = row;
895         ret = get_audio_file_path_of_row(aft_row, &path);
896         if (ret < 0)
897                 return ret;
898         if (!(options->flags & LS_FLAG_FULL_PATH)) {
899                 char *p = strrchr(path, '/');
900                 if (p)
901                         path = p + 1;
902         }
903         if (options->num_patterns) {
904                 for (i = 0; i < options->num_patterns; i++) {
905                         ret = fnmatch(options->patterns[i], path, FNM_PATHNAME);
906                         if (!ret)
907                                 break;
908                         if (ret == FNM_NOMATCH)
909                                 continue;
910                         return -E_FNMATCH;
911                 }
912                 if (i >= options->num_patterns) /* no match */
913                         return 1;
914         }
915         tmp = options->num_matching_paths++;
916         if (options->num_matching_paths > options->array_size) {
917                 options->array_size++;
918                 options->array_size *= 2;
919                 options->data = para_realloc(options->data, options->array_size
920                         * sizeof(*options->data));
921         }
922         d = options->data + tmp;
923         ret = get_afsi_of_row(aft_row, &d->afsi);
924         if (ret < 0)
925                 return ret;
926         ret = get_afhi_of_row(aft_row, &d->afhi);
927         if (ret < 0)
928                 return ret;
929         d->path = path;
930         ret = get_hash_of_row(aft_row, &d->hash);
931         if (ret < 0)
932                 return ret;
933         w = &options->widths;
934         GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
935         w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
936         GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
937         w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
938         GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
939         w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
940         GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
941         w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
942         GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
943         w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
944         /* just get the number of chars to print this amount of time */
945         tmp = get_duration(d->afhi.seconds_total, NULL, 0);
946         w->duration_width = PARA_MAX(w->duration_width, tmp);
947         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
948                 GET_NUM_DIGITS(score, &num_digits);
949                 num_digits++; /* add one for the sign (space or "-") */
950                 w->score_width = PARA_MAX(w->score_width, num_digits);
951                 d->score = score;
952         }
953         return 1;
954 }
955
956 static int com_ls_callback(const struct osl_object *query,
957                 struct osl_object *ls_output)
958 {
959         struct ls_options *opts = query->data;
960         char *p, *pattern_start = (char *)query->data + sizeof(*opts);
961         struct para_buffer b = {.buf = NULL, .size = 0};
962         int i = 0, ret;
963
964         PARA_NOTICE_LOG("%d patterns\n", opts->num_patterns);
965         if (opts->num_patterns) {
966                 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
967                 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
968                         opts->patterns[i] = p;
969                         p += strlen(p) + 1;
970                         PARA_NOTICE_LOG("pattern %d: %s\n", i, opts->patterns[i]);
971                 }
972         } else
973                 opts->patterns = NULL;
974         if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
975                 ret = admissible_file_loop(opts, prepare_ls_row);
976         else
977                 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
978                         prepare_ls_row);
979         if (ret < 0)
980                 goto out;
981         ret = opts->num_patterns? -E_NO_MATCH : 0;
982         if (!opts->num_matching_paths) {
983                 PARA_NOTICE_LOG("no match, ret: %d\n", ret);
984                 goto out;
985         }
986         ret = sort_matching_paths(opts);
987         if (ret < 0)
988                 goto out;
989         if (opts->flags & LS_FLAG_REVERSE)
990                 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
991                         ret = print_list_item(opts->data_ptr[i], opts, &b);
992                         if (ret < 0)
993                                 break;
994                 }
995         else
996                 for (i = 0; i < opts->num_matching_paths; i++) {
997                         ret = print_list_item(opts->data_ptr[i], opts, &b);
998                         if (ret < 0)
999                                 break;
1000                 }
1001         ret = 1;
1002 out:
1003         ls_output->data = b.buf;
1004         PARA_NOTICE_LOG("ls_outoute.data: %p\n", ls_output->data);
1005         ls_output->size = b.size;
1006         free(opts->data);
1007         free(opts->data_ptr);
1008         free(opts->patterns);
1009         return ret;
1010 }
1011
1012 /*
1013  * TODO: flags -h (sort by hash)
1014  *
1015  * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1016  * full list: list everything, including afsi, afhi, atts as clear text
1017  *
1018  * */
1019 int com_afs_ls(int fd, int argc, char * const * const argv)
1020 {
1021         int i, ret;
1022         unsigned flags = 0;
1023         enum ls_sorting_method sort = LS_SORT_BY_PATH;
1024         enum ls_listing_mode mode = LS_MODE_SHORT;
1025         struct ls_options opts = {.patterns = NULL};
1026         struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1027                 ls_output;
1028
1029         for (i = 1; i < argc; i++) {
1030                 const char *arg = argv[i];
1031                 if (arg[0] != '-')
1032                         break;
1033                 if (!strcmp(arg, "--")) {
1034                         i++;
1035                         break;
1036                 }
1037                 if (!strncmp(arg, "-l", 2)) {
1038                         if (!*(arg + 2)) {
1039                                 mode = LS_MODE_LONG;
1040                                 continue;
1041                         }
1042                         if (*(arg + 3))
1043                                 return -E_AFT_SYNTAX;
1044                         switch(*(arg + 2)) {
1045                         case 's':
1046                                 mode = LS_MODE_SHORT;
1047                                 continue;
1048                         case 'l':
1049                                 mode = LS_MODE_LONG;
1050                                 continue;
1051                         case 'v':
1052                                 mode = LS_MODE_VERBOSE;
1053                                 continue;
1054                         case 'm':
1055                                 mode = LS_MODE_MBOX;
1056                                 continue;
1057                         default:
1058                                 return -E_AFT_SYNTAX;
1059                         }
1060                 }
1061                 if (!strcmp(arg, "-p")) {
1062                         flags |= LS_FLAG_FULL_PATH;
1063                         continue;
1064                 }
1065                 if (!strcmp(arg, "-a")) {
1066                         flags |= LS_FLAG_ADMISSIBLE_ONLY;
1067                         continue;
1068                 }
1069                 if (!strcmp(arg, "-r")) {
1070                         flags |= LS_FLAG_REVERSE;
1071                         continue;
1072                 }
1073                 if (!strncmp(arg, "-s", 2)) {
1074                         if (!*(arg + 2) || *(arg + 3))
1075                                 return -E_AFT_SYNTAX;
1076                         switch(*(arg + 2)) {
1077                         case 'p':
1078                                 sort = LS_SORT_BY_PATH;
1079                                 continue;
1080                         case 's': /* -ss implies -a */
1081                                 sort = LS_SORT_BY_SCORE;
1082                                 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1083                                 continue;
1084                         case 'l':
1085                                 sort = LS_SORT_BY_LAST_PLAYED;
1086                                 continue;
1087                         case 'n':
1088                                 sort = LS_SORT_BY_NUM_PLAYED;
1089                                 continue;
1090                         case 'f':
1091                                 sort = LS_SORT_BY_FREQUENCY;
1092                                 continue;
1093                         case 'c':
1094                                 sort = LS_SORT_BY_CHANNELS;
1095                                 continue;
1096                         case 'i':
1097                                 sort = LS_SORT_BY_IMAGE_ID;
1098                                 continue;
1099                         case 'y':
1100                                 sort = LS_SORT_BY_LYRICS_ID;
1101                                 continue;
1102                         case 'b':
1103                                 sort = LS_SORT_BY_BITRATE;
1104                                 continue;
1105                         case 'd':
1106                                 sort = LS_SORT_BY_DURATION;
1107                                 continue;
1108                         case 'a':
1109                                 sort = LS_SORT_BY_AUDIO_FORMAT;
1110                                 continue;
1111                         default:
1112                                 return -E_AFT_SYNTAX;
1113                         }
1114                 }
1115                 return -E_AFT_SYNTAX;
1116         }
1117         time(&now);
1118         opts.flags = flags;
1119         opts.sorting = sort;
1120         opts.mode = mode;
1121         opts.num_patterns = argc - i;
1122         ret = send_option_arg_callback_request(&query, opts.num_patterns,
1123                 argv + i, com_ls_callback, &ls_output);
1124         if (ret > 0) {
1125                 ret = send_buffer(fd, (char *)ls_output.data);
1126                 free(ls_output.data);
1127         }
1128         return ret;
1129 }
1130
1131 /**
1132  * Call the given function for each file in the audio file table.
1133  *
1134  * \param private_data An arbitrary data pointer, passed to \a func.
1135  * \param func The custom function to be called.
1136  *
1137  * \return The return value of the underlying call to osl_rbtree_loop().
1138  */
1139 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1140 {
1141         return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1142                 func);
1143 }
1144
1145 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1146 {
1147         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1148         struct osl_row *row;
1149
1150         osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1151         return row;
1152 }
1153
1154 enum aft_row_offsets {
1155         AFTROW_AFHI_OFFSET_POS = 0,
1156         AFTROW_CHUNKS_OFFSET_POS = 2,
1157         AFTROW_AUDIO_FORMAT_OFFSET = 4,
1158         AFTROW_FLAGS_OFFSET = 5,
1159         AFTROW_HASH_OFFSET = 9,
1160         AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1161 };
1162
1163 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1164  * In this case, afhi won't be stored in the buffer  */
1165 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1166                 struct audio_format_info *afhi, uint32_t flags,
1167                 uint8_t audio_format_num, struct osl_object *obj)
1168 {
1169         size_t path_len = strlen(path) + 1;
1170         size_t afhi_size = sizeof_afhi_buf(afhi);
1171         size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1172                 + sizeof_chunk_info_buf(afhi);
1173         char *buf = para_malloc(size);
1174         uint16_t pos;
1175
1176         write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1177         write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1178
1179         memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1180         strcpy(buf + AFTROW_PATH_OFFSET, path);
1181
1182         pos = AFTROW_PATH_OFFSET + path_len;
1183         PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1184         PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1185                 pos + afhi_size - 1);
1186         write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1187         save_afhi(afhi, buf + pos);
1188
1189         pos += afhi_size;
1190         PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1191         write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1192         save_chunk_info(afhi, buf + pos);
1193         PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1194         obj->data = buf;
1195         obj->size = size;
1196 }
1197
1198 /*
1199 input:
1200 ~~~~~~
1201 HS:     hash sister
1202 PB:     path brother
1203 F:      force flag given
1204
1205 output:
1206 ~~~~~~~
1207 AFHI:   whether afhi and chunk table are computed and sent
1208 ACTION: table modifications to be performed
1209
1210 +---+----+-----+------+---------------------------------------------------+
1211 | HS | PB | F  | AFHI | ACTION
1212 +---+----+-----+------+---------------------------------------------------+
1213 | Y |  Y |  Y  |  Y   | if HS != PB: remove PB. HS: force afhi update,
1214 |                     | update path, keep afsi
1215 +---+----+-----+------+---------------------------------------------------+
1216 | Y |  Y |  N  |  N   | if HS == PB: do not send callback request at all.
1217 |                     | otherwise: remove PB, HS: update path, keep afhi,
1218 |                     | afsi.
1219 +---+----+-----+------+---------------------------------------------------+
1220 | Y |  N |  Y  |  Y   | (rename) force afhi update of HS, update path of
1221 |                     | HS, keep afsi
1222 +---+----+-----+------+---------------------------------------------------+
1223 | Y |  N |  N  |  N   | (file rename) update path of HS, keep afsi, afhi
1224 +---+----+-----+------+---------------------------------------------------+
1225 | N |  Y |  Y  |  Y   | (file change) update afhi, hash, of PB, keep afsi
1226 |                     | (force has no effect)
1227 +---+----+-----+------+---------------------------------------------------+
1228 | N |  Y |  N  |  Y   | (file change) update afhi, hash of PB, keep afsi
1229 +---+----+-----+------+---------------------------------------------------+
1230 | N |  N |  Y  |  Y   | (new file) create new entry (force has no effect)
1231 +---+----+-----+------+---------------------------------------------------+
1232 | N |  N |  N  |  Y   | (new file) create new entry
1233 +---+----+-----+------+---------------------------------------------------+
1234
1235 afhi <=> force or no HS
1236
1237 */
1238
1239
1240 #define ADD_FLAG_LAZY 1
1241 #define ADD_FLAG_FORCE 2
1242 #define ADD_FLAG_VERBOSE 4
1243
1244 /* TODO: change log messages so that they get written to the result buffer */
1245
1246 static int com_add_callback(const struct osl_object *query,
1247                 __a_unused struct osl_object *result)
1248 {
1249         char *buf = query->data, *path;
1250         struct osl_row *pb, *aft_row;
1251         const struct osl_row *hs;
1252         struct osl_object objs[NUM_AFT_COLUMNS];
1253         HASH_TYPE *hash;
1254         char asc[2 * HASH_SIZE + 1];
1255         int ret;
1256         char afsi_buf[AFSI_SIZE];
1257         uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1258         struct afs_info default_afsi = {.last_played = 0};
1259
1260         hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1261         hash_to_asc(hash, asc);;
1262         objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1263         objs[AFTCOL_HASH].size = HASH_SIZE;
1264
1265         path = buf + AFTROW_PATH_OFFSET;
1266         objs[AFTCOL_PATH].data = path;
1267         objs[AFTCOL_PATH].size = strlen(path) + 1;
1268
1269         PARA_DEBUG_LOG("request to add %s with hash %s\n", path, asc);
1270         hs = find_hash_sister(hash);
1271         ret = aft_get_row_of_path(path, &pb);
1272         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1273                 return ret;
1274         if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1275                 if (flags & ADD_FLAG_VERBOSE)
1276                         PARA_NOTICE_LOG("ignoring duplicate %p\n", path);
1277                 return 1;
1278         }
1279         if (hs && hs != pb) {
1280                 struct osl_object obj;
1281                 if (pb) { /* hs trumps pb, remove pb */
1282                         if (flags & ADD_FLAG_VERBOSE)
1283                                 PARA_NOTICE_LOG("removing path brother\n");
1284                         ret = osl_del_row(audio_file_table, pb);
1285                         if (ret < 0)
1286                                 return ret;
1287                         pb = NULL;
1288                 }
1289                 /* file rename, update hs' path */
1290                 ret = osl_get_object(audio_file_table, hs, AFTCOL_PATH, &obj);
1291                 if (flags & ADD_FLAG_VERBOSE)
1292                         PARA_NOTICE_LOG("rename %s -> %s\n", (char *)obj.data, path);
1293                 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1294                         &objs[AFTCOL_PATH]);
1295                 if (ret < 0)
1296                         return ret;
1297                 if (!(flags & ADD_FLAG_FORCE))
1298                         return ret;
1299         }
1300         /* no hs or force mode, child must have sent afhi */
1301         uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1302         uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1303
1304         objs[AFTCOL_AFHI].data = buf + afhi_offset;
1305         objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1306         if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1307                 return -E_NO_AFHI;
1308         objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1309         objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1310         if (pb && !hs) { /* update pb's hash */
1311                 char old_asc[2 * HASH_SIZE + 1];
1312                 HASH_TYPE *old_hash;
1313                 ret = get_hash_of_row(pb, &old_hash);
1314                 if (ret < 0)
1315                         return ret;
1316                 hash_to_asc(old_hash, old_asc);
1317                 if (flags & ADD_FLAG_VERBOSE)
1318                         PARA_NOTICE_LOG("file change: %s %s -> %s\n", path,
1319                                 old_asc, asc);
1320                 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1321                         &objs[AFTCOL_HASH]);
1322                 if (ret < 0)
1323                         return ret;
1324         }
1325         if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1326                 const void *row = pb? pb : hs;
1327                 /* update afhi and chunk_table */
1328                 if (flags & ADD_FLAG_VERBOSE)
1329                         PARA_NOTICE_LOG("updating audio format handler info (%zd bytes)\n",
1330                                 objs[AFTCOL_AFHI].size);
1331                 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1332                         &objs[AFTCOL_AFHI]);
1333                 if (ret < 0)
1334                         return ret;
1335                 if (flags & ADD_FLAG_VERBOSE)
1336                         PARA_NOTICE_LOG("updating chunk table\n");
1337                 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1338                         &objs[AFTCOL_CHUNKS]);
1339                 if (ret < 0)
1340                         return ret;
1341                 ret = mood_update_audio_file(row, NULL);
1342                 if (ret < 0)
1343                         return ret;
1344         }
1345         /* new entry, use default afsi */
1346         default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1347         default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1348
1349         objs[AFTCOL_AFSI].data = &afsi_buf;
1350         objs[AFTCOL_AFSI].size = AFSI_SIZE;
1351         save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1352         ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1353         if (ret < 0)
1354                 return ret;
1355         return mood_update_audio_file(aft_row, NULL);
1356 }
1357
1358 struct private_add_data {
1359         int fd;
1360         uint32_t flags;
1361 };
1362
1363 static int path_brother_callback(const struct osl_object *query,
1364                 struct osl_object *result)
1365 {
1366         char *path = query->data;
1367         struct osl_row *path_brother;
1368         int ret = aft_get_row_of_path(path, &path_brother);
1369         if (ret < 0)
1370                 return ret;
1371         result->data = para_malloc(sizeof(path_brother));
1372         result->size = sizeof(path_brother);
1373         *(struct osl_row **)(result->data) = path_brother;
1374         return 1;
1375 }
1376
1377 static int hash_sister_callback(const struct osl_object *query,
1378                 struct osl_object *result)
1379 {
1380         HASH_TYPE *hash = query->data;
1381         struct osl_row *hash_sister;
1382
1383         hash_sister = find_hash_sister(hash);
1384         if (!hash_sister)
1385                 return -E_RB_KEY_NOT_FOUND;
1386         result->data = para_malloc(sizeof(hash_sister));
1387         result->size = sizeof(hash_sister);
1388         *(struct osl_row **)(result->data) = hash_sister;
1389         return 1;
1390 }
1391
1392 static int add_one_audio_file(const char *arg, const void *private_data)
1393 {
1394         int ret;
1395         uint8_t format_num = -1;
1396         const struct private_add_data *pad = private_data;
1397         struct audio_format_info afhi, *afhi_ptr = NULL;
1398         struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1399         struct osl_object map, obj = {.data = NULL}, query, result;
1400         char *path = NULL;
1401         HASH_TYPE hash[HASH_SIZE];
1402
1403         afhi.header_offset = 0;
1404         afhi.header_len = 0;
1405         ret = verify_path(arg, &path);
1406         if (ret < 0)
1407                 goto out_free;
1408         query.data = path;
1409         query.size = strlen(path) + 1;
1410         ret = send_callback_request(path_brother_callback, &query, &result);
1411         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1412                 goto out_free;
1413         if (ret >= 0) {
1414                 pb = *(struct osl_row **)result.data;
1415                 free(result.data);
1416         }
1417         ret = 1;
1418         if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1419                 if (pad->flags & ADD_FLAG_VERBOSE)
1420                         ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1421                 goto out_free;
1422         }
1423         /* We still want to add this file. Compute its hash. */
1424         ret = mmap_full_file(path, O_RDONLY, &map);
1425         if (ret < 0)
1426                 goto out_free;
1427         hash_function(map.data, map.size, hash);
1428
1429         /* Check whether database contains file with the same hash. */
1430         query.data = hash;
1431         query.size = HASH_SIZE;
1432         ret = send_callback_request(hash_sister_callback, &query, &result);
1433         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1434                 goto out_free;
1435         if (ret >= 0) {
1436                 hs = *(struct osl_row **)result.data;
1437                 free(result.data);
1438         }
1439         /* Return success if we already know this file. */
1440         ret = 1;
1441         if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1442                 if (pad->flags & ADD_FLAG_VERBOSE)
1443                         ret = send_va_buffer(pad->fd,
1444                                 "not forcing update: %s\n", path);
1445                 goto out_unmap;
1446         }
1447         /*
1448          * we won't recalculate the audio format info and the chunk table if
1449          * there is a hash sister unless in FORCE mode.
1450          */
1451         if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1452                 ret = compute_afhi(path, map.data, map.size, &afhi);
1453                 if (ret < 0)
1454                         goto out_unmap;
1455                 format_num = ret;
1456                 afhi_ptr = &afhi;
1457         }
1458         if (pad->flags & ADD_FLAG_VERBOSE)
1459                 send_va_buffer(pad->fd, "adding %s\n", path);
1460         munmap(map.data, map.size);
1461         save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1462         /* Ask afs to consider this entry for adding. */
1463         ret = send_callback_request(com_add_callback, &obj, NULL);
1464         goto out_free;
1465
1466 out_unmap:
1467         munmap(map.data, map.size);
1468 out_free:
1469         if (ret < 0)
1470                 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path?
1471                         path : arg, PARA_STRERROR(-ret));
1472         free(obj.data);
1473         free(path);
1474         if (afhi_ptr)
1475                 free(afhi_ptr->chunk_table);
1476         return 1; /* it's not an error if not all files could be added */
1477 }
1478
1479 int com_add(int fd, int argc, char * const * const argv)
1480 {
1481         int i, ret;
1482         struct private_add_data pad = {.fd = fd, .flags = 0};
1483         struct stat statbuf;
1484
1485         for (i = 1; i < argc; i++) {
1486                 const char *arg = argv[i];
1487                 if (arg[0] != '-')
1488                         break;
1489                 if (!strcmp(arg, "--")) {
1490                         i++;
1491                         break;
1492                 }
1493                 if (!strcmp(arg, "-l")) {
1494                         pad.flags |= ADD_FLAG_LAZY;
1495                         continue;
1496                 }
1497                 if (!strcmp(arg, "-f")) {
1498                         pad.flags |= ADD_FLAG_FORCE;
1499                         continue;
1500                 }
1501                 if (!strcmp(arg, "-v")) {
1502                         pad.flags |= ADD_FLAG_VERBOSE;
1503                         continue;
1504                 }
1505         }
1506         if (argc <= i)
1507                 return -E_AFT_SYNTAX;
1508         for (; i < argc; i++) {
1509                 char *path = para_strdup(argv[i]);
1510                 size_t len = strlen(path);
1511                 while (len > 1 && path[--len] == '/')
1512                         path[len] = '\0';
1513                 ret = stat(path, &statbuf);
1514                 if (ret < 0)
1515                         PARA_NOTICE_LOG("failed to stat %s (%s)", path,
1516                                 strerror(errno));
1517                 else
1518                         if (S_ISDIR(statbuf.st_mode))
1519                                 for_each_file_in_dir(path, add_one_audio_file,
1520                                         &pad);
1521                         else
1522                                 add_one_audio_file(path, &pad);
1523                 free(path);
1524         }
1525         ret = 1;
1526         return ret;
1527
1528 }
1529
1530 struct com_touch_options {
1531         long num_played;
1532         long last_played;
1533         long lyrics_id;
1534         long image_id;
1535 };
1536
1537 static int com_touch_callback(const struct osl_object *query,
1538                 __a_unused struct osl_object *result)
1539 {
1540         struct com_touch_options *cto = query->data;
1541         char *p = (char *)query->data + sizeof(*cto);
1542         size_t len;
1543         int ret, no_options = cto->num_played < 0 && cto->last_played < 0 &&
1544                 cto->lyrics_id < 0 && cto->image_id < 0;
1545
1546         for (;p < (char *)query->data + query->size; p += len + 1) {
1547                 struct afs_info old_afsi, new_afsi;
1548                 struct osl_object obj;
1549                 struct osl_row *row;
1550
1551                 len = strlen(p);
1552                 ret = aft_get_row_of_path(p, &row);
1553                 if (ret < 0)
1554                         return ret;
1555                 ret = get_afsi_object_of_row(row, &obj);
1556                 if (ret < 0)
1557                         return ret;
1558                 ret = load_afsi(&old_afsi, &obj);
1559                 if (ret < 0)
1560                         return ret;
1561                 new_afsi = old_afsi;
1562                 if (no_options) {
1563                         new_afsi.num_played++;
1564                         new_afsi.last_played = time(NULL);
1565                 } else {
1566                         if (cto->lyrics_id >= 0)
1567                                 new_afsi.lyrics_id = cto->lyrics_id;
1568                         if (cto->image_id >= 0)
1569                                 new_afsi.image_id = cto->image_id;
1570                         if (cto->num_played >= 0)
1571                                 new_afsi.num_played = cto->num_played;
1572                         if (cto->last_played >= 0)
1573                                 new_afsi.last_played = cto->last_played;
1574                 }
1575                 save_afsi(&new_afsi, &obj); /* in-place update */
1576                 ret = mood_update_audio_file(row, &old_afsi);
1577                 if (ret < 0)
1578                         return ret;
1579         }
1580         return 1;
1581 }
1582
1583 int com_touch(__a_unused int fd, int argc, char * const * const argv)
1584 {
1585         struct com_touch_options cto = {
1586                 .num_played = -1,
1587                 .last_played = -1,
1588                 .lyrics_id = -1,
1589                 .image_id = -1
1590         };
1591         struct osl_object options = {.data = &cto, .size = sizeof(cto)};
1592         int i, ret;
1593
1594
1595         for (i = 1; i < argc; i++) {
1596                 const char *arg = argv[i];
1597                 if (arg[0] != '-')
1598                         break;
1599                 if (!strcmp(arg, "--")) {
1600                         i++;
1601                         break;
1602                 }
1603                 if (!strncmp(arg, "-n", 2)) {
1604                         ret = para_atol(arg + 2, &cto.num_played);
1605                         if (ret < 0)
1606                                 goto err;
1607                         continue;
1608                 }
1609                 if (!strncmp(arg, "-l", 2)) {
1610                         ret = para_atol(arg + 2, &cto.last_played);
1611                         if (ret < 0)
1612                                 goto err;
1613                         continue;
1614                 }
1615                 if (!strncmp(arg, "-y", 2)) {
1616                         ret = para_atol(arg + 2, &cto.lyrics_id);
1617                         if (ret < 0)
1618                                 goto err;
1619                         continue;
1620                 }
1621                 if (!strncmp(arg, "-i", 2)) {
1622                         ret = para_atol(arg + 2, &cto.image_id);
1623                         if (ret < 0)
1624                                 goto err;
1625                         continue;
1626                 }
1627         }
1628         ret = -E_AFT_SYNTAX;
1629         if (i >= argc)
1630                 goto err;
1631         return send_option_arg_callback_request(&options, argc - i,
1632                 argv + i, com_touch_callback, NULL);
1633 err:
1634         return ret;
1635 }
1636
1637 struct com_rm_options {
1638         uint32_t flags;
1639 };
1640
1641 static int com_rm_callback(const struct osl_object *query,
1642                 __a_unused struct osl_object *result)
1643 {
1644         struct com_rm_options *cro = query->data;
1645         char *p = (char *)query->data + sizeof(*cro);
1646         size_t len;
1647         int ret;
1648
1649         for (;p < (char *)query->data + query->size; p += len + 1) {
1650                 struct osl_row *row;
1651
1652                 len = strlen(p);
1653                 ret = aft_get_row_of_path(p, &row);
1654                 if (ret < 0)
1655                         return ret;
1656                 ret = mood_delete_audio_file(row);
1657                 if (ret < 0)
1658                         return ret;
1659                 ret = osl_del_row(audio_file_table, row);
1660                 if (ret < 0)
1661                         return ret;
1662         }
1663         return 1;
1664 }
1665
1666 /*
1667  * TODO options: -v verbose, -f dont stop if file not found
1668  * -h remove by hash, use fnmatch
1669  *
1670  * */
1671
1672 int com_afs_rm(__a_unused int fd, int argc,  char * const * const argv)
1673 {
1674         struct com_rm_options cro = {.flags = 0};
1675         struct osl_object options = {.data = &cro, .size = sizeof(cro)};
1676         int i, ret;
1677
1678         for (i = 1; i < argc; i++) {
1679                 const char *arg = argv[i];
1680                 if (arg[0] != '-')
1681                         break;
1682                 if (!strcmp(arg, "--")) {
1683                         i++;
1684                         break;
1685                 }
1686         }
1687         ret = -E_AFT_SYNTAX;
1688         if (i >= argc)
1689                 goto err;
1690         return send_option_arg_callback_request(&options, argc - i,
1691                 argv + i, com_rm_callback, NULL);
1692 err:
1693         return ret;
1694 }
1695
1696 /**
1697  * Close the audio file table.
1698  *
1699  * \param flags Ususal flags that are passed to osl_close_table().
1700  *
1701  * \sa osl_close_table().
1702  */
1703 void aft_shutdown(enum osl_close_flags flags)
1704 {
1705         osl_close_table(audio_file_table, flags);
1706 }
1707
1708 /**
1709  * Open the audio file table.
1710  *
1711  * \param ti Gets initialized by this function.
1712  * \param db The database directory.
1713  *
1714  * \return Positive on success, negative on errors.
1715  *
1716  * \sa osl_open_table().
1717  */
1718 int aft_init(struct table_info *ti, const char *db)
1719 {
1720         int ret;
1721
1722         audio_file_table_desc.dir = db;
1723         ti->desc = &audio_file_table_desc;
1724         ret = osl_open_table(ti->desc, &ti->table);
1725         if (ret >= 0) {
1726                 unsigned num;
1727                 audio_file_table = ti->table;
1728                 osl_get_num_rows(audio_file_table, &num);
1729                 PARA_INFO_LOG("audio file table contains %d files\n", num);
1730                 return ret;
1731         }
1732         PARA_INFO_LOG("failed to open audio file table\n");
1733         audio_file_table = NULL;
1734         return ret == -E_NOENT? 1 : ret;
1735 }