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