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