chiark / gitweb /
server/gstdecode.c: Add `-s' option to omit DisOrder's usual framing.
[disorder] / lib / trackdb.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2005-2008 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file lib/trackdb.c
19  * @brief Track database
20  *
21  * This file is getting in desparate need of splitting up...
22  */
23
24 #include "common.h"
25
26 #include <db.h>
27 #include <sys/socket.h>
28 #include <pcre.h>
29 #include <unistd.h>
30 #include <errno.h>
31 #include <stddef.h>
32 #include <sys/time.h>
33 #include <sys/resource.h>
34 #include <time.h>
35 #include <arpa/inet.h>
36 #include <dirent.h>
37 #include <sys/stat.h>
38 #include <gcrypt.h>
39
40 #include "event.h"
41 #include "mem.h"
42 #include "kvp.h"
43 #include "log.h"
44 #include "vector.h"
45 #include "rights.h"
46 #include "trackdb.h"
47 #include "configuration.h"
48 #include "syscalls.h"
49 #include "wstat.h"
50 #include "printf.h"
51 #include "filepart.h"
52 #include "trackname.h"
53 #include "trackdb-int.h"
54 #include "logfd.h"
55 #include "cache.h"
56 #include "eventlog.h"
57 #include "hash.h"
58 #include "unicode.h"
59 #include "unidata.h"
60 #include "base64.h"
61 #include "sendmail.h"
62 #include "validity.h"
63
64 #define RESCAN "disorder-rescan"
65 #define DEADLOCK "disorder-deadlock"
66
67 static const char *getpart(const char *track,
68                            const char *context,
69                            const char *part,
70                            const struct kvp *p,
71                            int *used_db);
72 static char **trackdb_new_tid(int *ntracksp,
73                               int maxtracks,
74                               DB_TXN *tid);
75 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid);
76 static char *normalize_tag(const char *s, size_t ns);
77
78 const struct cache_type cache_files_type = { 86400 };
79 unsigned long cache_files_hits, cache_files_misses;
80
81 /** @brief Set by trackdb_open() */
82 int trackdb_existing_database;
83
84 /* setup and teardown ********************************************************/
85
86 /** @brief Database home directory
87  *
88  * All database files live below here.  It had better never change.
89  */
90 static const char *home;
91
92 /** @brief Database environment */
93 DB_ENV *trackdb_env;
94
95 /** @brief The tracks database
96  * - Keys are UTF-8(NFC(unicode(path name)))
97  * - Values are encoded key-value pairs
98  * - Data is reconstructable data about tracks that currently exist
99  */
100 DB *trackdb_tracksdb;
101
102 /** @brief The preferences database
103  *
104  * - Keys are UTF-8(NFC(unicode(path name)))
105  * - Values are encoded key-value pairs
106  * - Data is user data about tracks (that might not exist any more)
107  * and cannot be reconstructed
108  */
109 DB *trackdb_prefsdb;
110
111 /** @brief The search database
112  *
113  * - Keys are UTF-8(NFKC(casefold(search term)))
114  * - Values are UTF-8(NFC(unicode(path name)))
115  * - There can be more than one value per key
116  * - Presence of key,value means that path matches the search terms
117  * - Only tracks fond in @ref trackdb_tracksdb are represented here
118  * - This database can be reconstructed, it contains no user data
119  */
120 DB *trackdb_searchdb;
121
122 /** @brief The tags database
123  *
124  * - Keys are UTF-8(NFKC(casefold(tag)))
125  * - Values are UTF-8(NFC(unicode(path name)))
126  * - There can be more than one value per key
127  * - Presence of key,value means that path matches the tag
128  * - This is always in sync with the tags preference
129  * - This database can be reconstructed, it contains no user data
130  */
131 DB *trackdb_tagsdb;                     /* the tags database */
132
133 /** @brief The global preferences database
134  * - Keys are UTF-8(NFC(preference))
135  * - Values are global preference values
136  * - Data is user data and cannot be reconstructed
137  */
138 DB *trackdb_globaldb;                   /* global preferences */
139
140 /** @brief The noticed database
141  * - Keys are 64-bit big-endian timestamps
142  * - Values are UTF-8(NFC(unicode(path name)))
143  * - There can be more than one value per key
144  * - Presence of key,value means that path was added at the given time
145  * - Data cannot be reconstructed (but isn't THAT important)
146  */
147 DB *trackdb_noticeddb;                   /* when track noticed */
148
149 /** @brief The schedule database
150  *
151  * - Keys are ID strings, generated at random
152  * - Values are encoded key-value pairs
153  * - There can be more than one value per key
154  * - Data cannot be reconstructed
155  *
156  * See @ref server/schedule.c for further information.
157  */
158 DB *trackdb_scheduledb;
159
160 /** @brief The user database
161  * - Keys are usernames
162  * - Values are encoded key-value pairs
163  * - Data is user data and cannot be reconstructed
164  */
165 DB *trackdb_usersdb;
166
167 /** @brief The playlists database
168  * - Keys are playlist names
169  * - Values are encoded key-value pairs
170  * - Data is user data and cannot be reconstructed
171  */
172 DB *trackdb_playlistsdb;
173
174 /** @brief Deadlock manager PID */
175 static pid_t db_deadlock_pid = -1;
176
177 /** @brief Rescanner PID */
178 static pid_t rescan_pid = -1;
179
180 /** @brief Set when the database environment exists */
181 static int initialized;
182
183 /** @brief Set when databases are open */
184 static int opened;
185
186 /** @brief Current stats subprocess PIDs */
187 static hash *stats_pids;
188
189 /** @brief PID of current random track chooser (disorder-choose) */
190 static pid_t choose_pid = -1;
191
192 /** @brief Our end of pipe from disorder-choose */
193 static int choose_fd;
194
195 /** @brief Callback to supply random track to */
196 static random_callback *choose_callback;
197
198 /** @brief Accumulator for output from disorder-choose */
199 static struct dynstr choose_output;
200
201 /** @brief Current completion status of disorder-choose
202  * A bitmap of @ref CHOOSE_READING and @ref CHOOSE_RUNNING.
203  */
204 static unsigned choose_complete;
205
206 /* @brief Exit status from disorder-choose */
207 static int choose_status;
208
209 /** @brief disorder-choose process is running */
210 #define CHOOSE_RUNNING 1
211
212 /** @brief disorder-choose pipe is still open */
213 #define CHOOSE_READING 2
214
215 /** @brief Comparison function for filename-based keys */
216 static int compare(DB attribute((unused)) *db_,
217                    const DBT *a, const DBT *b) {
218   return compare_path_raw(a->data, a->size, b->data, b->size);
219 }
220
221 /** @brief Test whether the track database can be read
222  * @return 1 if it can, 0 if it cannot
223  */
224 int trackdb_readable(void) {
225   char *usersdb;
226
227   byte_xasprintf(&usersdb, "%s/users.db", config->home);
228   return access(usersdb, R_OK) == 0;
229 }
230
231 /** @brief Open database environment
232  * @param flags Flags word
233  *
234  * Flags should be one of:
235  * - @ref TRACKDB_NO_RECOVER
236  * - @ref TRACKDB_NORMAL_RECOVER
237  * - @ref TRACKDB_FATAL_RECOVER
238  * - @ref TRACKDB_MAY_CREATE
239  */
240 void trackdb_init(int flags) {
241   int err;
242   const int recover = flags & TRACKDB_RECOVER_MASK;
243   static int recover_type[] = { 0, DB_RECOVER, DB_RECOVER_FATAL };
244
245   /* sanity checks */
246   assert(initialized == 0);
247   ++initialized;
248   if(home) {
249     if(strcmp(home, config->home))
250       disorder_fatal(0, "cannot change db home without server restart");
251     home = config->home;
252   }
253
254   if(flags & TRACKDB_MAY_CREATE) {
255     DIR *dp;
256     struct dirent *de;
257     struct stat st;
258     char *p;
259
260     /* Remove world/group permissions on any regular files already in the
261      * database directory.  Actually we don't care about all of them but it's
262      * easier to just do the lot.  This can be revisited if it's a serious
263      * practical inconvenience for anyone.
264      *
265      * The socket, not being a regular file, is excepted.
266      */
267     if(!(dp = opendir(config->home)))
268       disorder_fatal(errno, "error reading %s", config->home);
269     while((de = readdir(dp))) {
270       byte_xasprintf(&p, "%s/%s", config->home, de->d_name);
271       if(lstat(p, &st) == 0
272          && S_ISREG(st.st_mode)
273          && (st.st_mode & 077)) {
274         if(chmod(p, st.st_mode & 07700) < 0)
275           disorder_fatal(errno, "cannot chmod %s", p);
276       }
277       xfree(p);
278     }
279     closedir(dp);
280   }
281
282   /* create environment */
283   if((err = db_env_create(&trackdb_env, 0)))
284     disorder_fatal(0, "db_env_create: %s", db_strerror(err));
285   if((err = trackdb_env->set_alloc(trackdb_env,
286                                    xmalloc_noptr, xrealloc_noptr, xfree)))
287     disorder_fatal(0, "trackdb_env->set_alloc: %s", db_strerror(err));
288   if((err = trackdb_env->set_lk_max_locks(trackdb_env, 10000)))
289     disorder_fatal(0, "trackdb_env->set_lk_max_locks: %s", db_strerror(err));
290   if((err = trackdb_env->set_lk_max_objects(trackdb_env, 10000)))
291     disorder_fatal(0, "trackdb_env->set_lk_max_objects: %s", db_strerror(err));
292   if((err = trackdb_env->open(trackdb_env, config->home,
293                               DB_INIT_LOG
294                               |DB_INIT_LOCK
295                               |DB_INIT_MPOOL
296                               |DB_INIT_TXN
297                               |DB_CREATE
298                               |recover_type[recover],
299                               0600)))
300     disorder_fatal(0, "trackdb_env->open %s: %s",
301                    config->home, db_strerror(err));
302   trackdb_env->set_errpfx(trackdb_env, "DB");
303   trackdb_env->set_errfile(trackdb_env, stderr);
304   trackdb_env->set_verbose(trackdb_env, DB_VERB_DEADLOCK, 1);
305   trackdb_env->set_verbose(trackdb_env, DB_VERB_RECOVERY, 1);
306   trackdb_env->set_verbose(trackdb_env, DB_VERB_REPLICATION, 1);
307   D(("initialized database environment"));
308 }
309
310 /** @brief Called when deadlock manager terminates */
311 static int reap_db_deadlock(ev_source attribute((unused)) *ev,
312                             pid_t attribute((unused)) pid,
313                             int status,
314                             const struct rusage attribute((unused)) *rusage,
315                             void attribute((unused)) *u) {
316   db_deadlock_pid = -1;
317   if(initialized)
318     disorder_fatal(0, "deadlock manager unexpectedly terminated: %s",
319                    wstat(status));
320   else
321     D(("deadlock manager terminated: %s", wstat(status)));
322   return 0;
323 }
324
325 /** @brief Start a subprogram
326  * @param ev Event loop
327  * @param outputfd File descriptor to redirect @c stdout to, or -1
328  * @param prog Program name
329  * @param ... Arguments
330  * @return PID
331  *
332  * Starts a subprocess.  Adds the following arguments:
333  * - @c --config to ensure the right config file is used
334  * - @c --debug or @c --no-debug to match debug settings
335  * - @c --syslog or @c --no-syslog to match log settings
336  */
337 static pid_t subprogram(ev_source *ev, int outputfd, const char *prog,
338                         ...) {
339   pid_t pid;
340   va_list ap;
341   const char *args[1024], **argp, *a;
342
343   argp = args;
344   *argp++ = prog;
345   *argp++ = "--config";
346   *argp++ = configfile;
347   *argp++ = debugging ? "--debug" : "--no-debug";
348   *argp++ = log_default == &log_syslog ? "--syslog" : "--no-syslog";
349   va_start(ap, prog);
350   while((a = va_arg(ap, const char *)))
351     *argp++ = a;
352   va_end(ap);
353   *argp = 0;
354   /* If we're in the background then trap subprocess stdout/stderr */
355   if(!(pid = xfork())) {
356     exitfn = _exit;
357     if(ev)
358       ev_signal_atfork(ev);
359     signal(SIGPIPE, SIG_DFL);
360     if(outputfd != -1) {
361       xdup2(outputfd, 1);
362       xclose(outputfd);
363     }
364     /* ensure we don't leak privilege anywhere */
365     if(setuid(geteuid()) < 0)
366       disorder_fatal(errno, "error calling setuid");
367     /* If we were negatively niced, undo it.  We don't bother checking for 
368     * error, it's not that important. */
369     setpriority(PRIO_PROCESS, 0, 0);
370     execvp(prog, (char **)args);
371     disorder_fatal(errno, "error invoking %s", prog);
372   }
373   return pid;
374 }
375
376 /** @brief Start deadlock manager
377  * @param ev Event loop
378  *
379  * Called from the main server (only).
380  */
381 void trackdb_master(ev_source *ev) {
382   assert(db_deadlock_pid == -1);
383   db_deadlock_pid = subprogram(ev, -1, DEADLOCK, (char *)0);
384   ev_child(ev, db_deadlock_pid, 0, reap_db_deadlock, 0);
385   D(("started deadlock manager"));
386 }
387
388 /** @brief Kill a subprocess and wait for it to terminate
389  * @param ev Event loop or NULL
390  * @param pid Process ID or -1
391  * @param what Description of subprocess
392  *
393  * Used during trackdb_deinit().  This function blocks so don't use it for
394  * normal teardown as that will hang the server.
395  */
396 static void terminate_and_wait(ev_source *ev,
397                                pid_t pid,
398                                const char *what) {
399   int err;
400
401   if(pid == -1)
402     return;
403   if(kill(pid, SIGTERM) < 0)
404     disorder_fatal(errno, "error killing %s", what);
405   /* wait for the rescanner to finish */
406   while(waitpid(pid, &err, 0) == -1 && errno == EINTR)
407     ;
408   if(ev)
409     ev_child_cancel(ev, pid);
410 }
411
412 /** @brief Close database environment
413  * @param ev Event loop
414  */
415 void trackdb_deinit(ev_source *ev) {
416   int err;
417
418   /* sanity checks */
419   assert(initialized == 1);
420   --initialized;
421
422   /* close the environment */
423   if((err = trackdb_env->close(trackdb_env, 0)))
424     disorder_fatal(0, "trackdb_env->close: %s", db_strerror(err));
425
426   terminate_and_wait(ev, rescan_pid, "disorder-rescan");
427   rescan_pid = -1;
428   terminate_and_wait(ev, choose_pid, "disorder-choose");
429   choose_pid = -1;
430
431   if(stats_pids) {
432     char **ks = hash_keys(stats_pids);
433
434     while(*ks) {
435       pid_t pid = atoi(*ks++);
436       terminate_and_wait(ev, pid, "disorder-stats");
437     }
438     stats_pids = NULL;
439   }
440
441   terminate_and_wait(ev, db_deadlock_pid, "disorder-deadlock");
442   db_deadlock_pid = -1;
443   D(("deinitialized database environment"));
444 }
445
446 /** @brief Open a specific database
447  * @param path Relative path to database
448  * @param dbflags Database flags: DB_DUP, DB_DUPSORT, etc
449  * @param dbtype Database type: DB_HASH, DB_BTREE, etc
450  * @param openflags Open flags: DB_RDONLY, DB_CREATE, etc
451  * @param mode Permission mask: usually 0666
452  * @return Database handle
453  */
454 static DB *open_db(const char *path,
455                    u_int32_t dbflags,
456                    DBTYPE dbtype,
457                    u_int32_t openflags,
458                    int mode) {
459   int err, err2;
460   DB *db;
461
462   D(("open %s", path));
463   path = config_get_file(path);
464   if((err = db_create(&db, trackdb_env, 0)))
465     disorder_fatal(0, "db_create %s: %s", path, db_strerror(err));
466   if(dbflags)
467     if((err = db->set_flags(db, dbflags)))
468       disorder_fatal(0, "db->set_flags %s: %s", path, db_strerror(err));
469   if(dbtype == DB_BTREE)
470     if((err = db->set_bt_compare(db, compare)))
471       disorder_fatal(0, "db->set_bt_compare %s: %s", path, db_strerror(err));
472   if((err = db->open(db, 0, path, 0, dbtype,
473                      openflags | DB_AUTO_COMMIT, mode))) {
474     if((openflags & DB_CREATE) || errno != ENOENT) {
475       if((err2 = db->close(db, 0)))
476         disorder_error(0, "db->close: %s", db_strerror(err2));
477       trackdb_close();
478       trackdb_env->close(trackdb_env,0);
479       trackdb_env = 0;
480       disorder_fatal(0, "db->open %s: %s", path, db_strerror(err));
481     }
482     db->close(db, 0);
483     db = 0;
484   }
485   return db;
486 }
487
488 /** @brief Open track databases
489  * @param flags Flags flags word
490  *
491  * @p flags should have one of:
492  * - @p TRACKDB_NO_UPGRADE, if no upgrade should be attempted
493  * - @p TRACKDB_CAN_UPGRADE, if an upgrade may be attempted
494  * - @p TRACKDB_OPEN_FOR_UPGRADE, if this is disorder-dbupgrade
495  * Also it may have:
496  * - @p TRACKDB_READ_ONLY, read only access
497  */
498 void trackdb_open(int flags) {
499   int err;
500   pid_t pid;
501   uint32_t dbflags = flags & TRACKDB_READ_ONLY ? DB_RDONLY : DB_CREATE;
502
503   /* sanity checks */
504   assert(opened == 0);
505   ++opened;
506   /* check the database version first */
507   trackdb_globaldb = open_db("global.db", 0, DB_HASH, DB_RDONLY, 0666);
508   if(trackdb_globaldb) {
509     /* This is an existing database */
510     const char *s;
511     long oldversion;
512
513     s = trackdb_get_global("_dbversion");
514     /* Close the database again,  we'll open it property below */
515     if((err = trackdb_globaldb->close(trackdb_globaldb, 0)))
516       disorder_fatal(0, "error closing global.db: %s", db_strerror(err));
517     trackdb_globaldb = 0;
518     /* Convert version string to an integer */
519     oldversion = s ? atol(s) : 1;
520     if(oldversion > config->dbversion) {
521       /* Database is from the future; we never allow this. */
522       disorder_fatal(0, "this version of DisOrder is too old for database version %ld",
523                      oldversion);
524     }
525     if(oldversion < config->dbversion) {
526       /* Database version is out of date */
527       switch(flags & TRACKDB_UPGRADE_MASK) {
528       case TRACKDB_NO_UPGRADE:
529         /* This database needs upgrading but this is not permitted */
530         disorder_fatal(0, "database needs upgrading from %ld to %ld",
531                        oldversion, config->dbversion);
532       case TRACKDB_CAN_UPGRADE:
533         /* This database needs upgrading */
534         disorder_info("invoking disorder-dbupgrade to upgrade from %ld to %ld",
535              oldversion, config->dbversion);
536         pid = subprogram(0, -1, "disorder-dbupgrade", (char *)0);
537         while(waitpid(pid, &err, 0) == -1 && errno == EINTR)
538           ;
539         if(err)
540           disorder_fatal(0, "disorder-dbupgrade %s", wstat(err));
541         disorder_info("disorder-dbupgrade succeeded");
542         break;
543       case TRACKDB_OPEN_FOR_UPGRADE:
544         break;
545       default:
546         abort();
547       }
548     }
549     if(oldversion == config->dbversion && (flags & TRACKDB_OPEN_FOR_UPGRADE)) {
550       /* This doesn't make any sense */
551       disorder_fatal(0, "database is already at current version");
552     }
553     trackdb_existing_database = 1;
554   } else {
555     if(flags & TRACKDB_OPEN_FOR_UPGRADE) {
556       /* Cannot upgrade a new database */
557       disorder_fatal(0, "cannot upgrade a database that does not exist");
558     }
559     /* This is a brand new database */
560     trackdb_existing_database = 0;
561   }
562   /* open the databases */
563   if(!(trackdb_usersdb = open_db("users.db",
564                                  0, DB_HASH, dbflags, 0600)))
565     disorder_fatal(0, "cannot open users.db");
566   trackdb_tracksdb = open_db("tracks.db",
567                              DB_RECNUM, DB_BTREE, dbflags, 0666);
568   trackdb_searchdb = open_db("search.db",
569                              DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
570   trackdb_tagsdb = open_db("tags.db",
571                            DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
572   trackdb_prefsdb = open_db("prefs.db", 0, DB_HASH, dbflags, 0666);
573   trackdb_globaldb = open_db("global.db", 0, DB_HASH, dbflags, 0666);
574   trackdb_noticeddb = open_db("noticed.db",
575                              DB_DUPSORT, DB_BTREE, dbflags, 0666);
576   trackdb_scheduledb = open_db("schedule.db", 0, DB_HASH, dbflags, 0666);
577   trackdb_playlistsdb = open_db("playlists.db", 0, DB_HASH, dbflags, 0666);
578   if(!trackdb_existing_database && !(flags & TRACKDB_READ_ONLY)) {
579     /* Stash the database version */
580     char buf[32];
581
582     assert(!(flags & TRACKDB_OPEN_FOR_UPGRADE));
583     snprintf(buf, sizeof buf, "%ld", config->dbversion);
584     trackdb_set_global("_dbversion", buf, 0);
585   }
586   D(("opened databases"));
587 }
588
589 /** @brief Close track databases */
590 void trackdb_close(void) {
591   int err;
592
593   /* sanity checks */
594   assert(opened == 1);
595   --opened;
596 #define CLOSE(N, V) do {                                                \
597   if(V && (err = V->close(V, 0)))                                       \
598     disorder_fatal(0, "error closing %s: %s", N, db_strerror(err));     \
599   V = 0;                                                                \
600 } while(0)
601   CLOSE("tracks.db", trackdb_tracksdb);
602   CLOSE("search.db", trackdb_searchdb);
603   CLOSE("tags.db", trackdb_tagsdb);
604   CLOSE("prefs.db", trackdb_prefsdb);
605   CLOSE("global.db", trackdb_globaldb);
606   CLOSE("noticed.db", trackdb_noticeddb);
607   CLOSE("schedule.db", trackdb_scheduledb);
608   CLOSE("users.db", trackdb_usersdb);
609   CLOSE("playlists.db", trackdb_playlistsdb);
610   D(("closed databases"));
611 }
612
613 /* generic db routines *******************************************************/
614
615 /** @brief Fetch and decode a database entry
616  * @param db Database
617  * @param track Track name
618  * @param kp Where to put decoded list (or NULL if you don't care)
619  * @param tid Owning transaction
620  * @return 0, @c DB_NOTFOUND or @c DB_LOCK_DEADLOCK
621  */
622 int trackdb_getdata(DB *db,
623                     const char *track,
624                     struct kvp **kp,
625                     DB_TXN *tid) {
626   int err;
627   DBT key, data;
628
629   switch(err = db->get(db, tid, make_key(&key, track),
630                        prepare_data(&data), 0)) {
631   case 0:
632     if(kp)
633       *kp = kvp_urldecode(data.data, data.size);
634     return 0;
635   case DB_NOTFOUND:
636     if(kp)
637       *kp = 0;
638     return err;
639   case DB_LOCK_DEADLOCK:
640     disorder_error(0, "error querying database: %s", db_strerror(err));
641     return err;
642   default:
643     disorder_fatal(0, "error querying database: %s", db_strerror(err));
644   }
645 }
646
647 /** @brief Encode and store a database entry
648  * @param db Database
649  * @param track Track name
650  * @param k List of key/value pairs to store
651  * @param tid Owning transaction
652  * @param flags DB flags e.g. DB_NOOVERWRITE
653  * @return 0, DB_KEYEXIST or DB_LOCK_DEADLOCK
654  */
655 int trackdb_putdata(DB *db,
656                     const char *track,
657                     const struct kvp *k,
658                     DB_TXN *tid,
659                     u_int32_t flags) {
660   int err;
661   DBT key, data;
662
663   switch(err = db->put(db, tid, make_key(&key, track),
664                        encode_data(&data, k), flags)) {
665   case 0:
666   case DB_KEYEXIST:
667     return err;
668   case DB_LOCK_DEADLOCK:
669     disorder_error(0, "error updating database: %s", db_strerror(err));
670     return err;
671   default:
672     disorder_fatal(0, "error updating database: %s", db_strerror(err));
673   }
674 }
675
676 /** @brief Delete a database entry
677  * @param db Database
678  * @param track Key to delete
679  * @param tid Transaction ID
680  * @return 0, DB_NOTFOUND or DB_LOCK_DEADLOCK
681  */
682 int trackdb_delkey(DB *db,
683                    const char *track,
684                    DB_TXN *tid) {
685   int err;
686
687   DBT key;
688   switch(err = db->del(db, tid, make_key(&key, track), 0)) {
689   case 0:
690   case DB_NOTFOUND:
691     return 0;
692   case DB_LOCK_DEADLOCK:
693     disorder_error(0, "error updating database: %s", db_strerror(err));
694     return err;
695   default:
696     disorder_fatal(0, "error updating database: %s", db_strerror(err));
697   }
698 }
699
700 /** @brief Open a database cursor
701  * @param db Database
702  * @param tid Owning transaction
703  * @return Cursor
704  */
705 DBC *trackdb_opencursor(DB *db, DB_TXN *tid) {
706   int err;
707   DBC *c;
708
709   switch(err = db->cursor(db, tid, &c, 0)) {
710   case 0: break;
711   default: disorder_fatal(0, "error creating cursor: %s", db_strerror(err));
712   }
713   return c;
714 }
715
716 /** @brief Close a database cursor
717  * @param c Cursor
718  * @return 0 or DB_LOCK_DEADLOCK
719  */
720 int trackdb_closecursor(DBC *c) {
721   int err;
722
723   if(!c) return 0;
724   switch(err = c->c_close(c)) {
725   case 0:
726     return err;
727   case DB_LOCK_DEADLOCK:
728     disorder_error(0, "error closing cursor: %s", db_strerror(err));
729     return err;
730   default:
731     disorder_fatal(0, "error closing cursor: %s", db_strerror(err));
732   }
733 }
734
735 /** @brief Delete a key/data pair
736  * @param db Database
737  * @param word Key
738  * @param track Data
739  * @param tid Owning transaction
740  * @return 0, DB_NOTFOUND or DB_LOCK_DEADLOCK
741  *
742  * Used by the search and tags databases, hence the odd parameter names.
743  * See also register_word().
744  */
745 int trackdb_delkeydata(DB *db,
746                        const char *word,
747                        const char *track,
748                        DB_TXN *tid) {
749   int err;
750   DBC *c;
751   DBT key, data;
752
753   c = trackdb_opencursor(db, tid);
754   switch(err = c->c_get(c, make_key(&key, word),
755                         make_key(&data, track), DB_GET_BOTH)) {
756   case 0:
757     switch(err = c->c_del(c, 0)) {
758     case 0:
759       break;
760     case DB_KEYEMPTY:
761       err = 0;
762       break;
763     case DB_LOCK_DEADLOCK:
764       disorder_error(0, "error updating database: %s", db_strerror(err));
765       break;
766     default:
767       disorder_fatal(0, "c->c_del: %s", db_strerror(err));
768     }
769     break;
770   case DB_NOTFOUND:
771     break;
772   case DB_LOCK_DEADLOCK:
773     disorder_error(0, "error updating database: %s", db_strerror(err));
774     break;
775   default:
776     disorder_fatal(0, "c->c_get: %s", db_strerror(err));
777   }
778   if(trackdb_closecursor(c)) err = DB_LOCK_DEADLOCK;
779   return err;
780 }
781
782 /** @brief Start a transaction
783  * @return Transaction
784  */
785 DB_TXN *trackdb_begin_transaction(void) {
786   DB_TXN *tid;
787   int err;
788
789   if((err = trackdb_env->txn_begin(trackdb_env, 0, &tid, 0)))
790     disorder_fatal(0, "trackdb_env->txn_begin: %s", db_strerror(err));
791   return tid;
792 }
793
794 /** @brief Abort transaction
795  * @param tid Transaction (or NULL)
796  *
797  * If @p tid is NULL then nothing happens.
798  */
799 void trackdb_abort_transaction(DB_TXN *tid) {
800   int err;
801
802   if(tid)
803     if((err = tid->abort(tid)))
804       disorder_fatal(0, "tid->abort: %s", db_strerror(err));
805 }
806
807 /** @brief Commit transaction
808  * @param tid Transaction (must not be NULL)
809  */
810 void trackdb_commit_transaction(DB_TXN *tid) {
811   int err;
812
813   if((err = tid->commit(tid, 0)))
814     disorder_fatal(0, "tid->commit: %s", db_strerror(err));
815 }
816
817 /* search/tags shared code ***************************************************/
818
819 /** @brief Comparison function used by dedupe()
820  * @param a Pointer to first key
821  * @param b Pointer to second key
822  * @return -1, 0 or 1
823  *
824  * Passed to qsort().
825  */
826 static int wordcmp(const void *a, const void *b) {
827   return strcmp(*(const char **)a, *(const char **)b);
828 }
829
830 /** @brief Sort and de-duplicate @p vec
831  * @param vec Vector to sort
832  * @param nvec Length of @p vec
833  * @return @p vec
834  *
835  * The returned vector is NULL-terminated, and there must be room for this NULL
836  * even if there are no duplicates (i.e. it must have more than @p nvec
837  * elements.)
838  */
839 static char **dedupe(char **vec, int nvec) {
840   int m, n;
841
842   qsort(vec, nvec, sizeof (char *), wordcmp);
843   m = 0;
844   if(nvec) {
845     vec[m++] = vec[0];
846     for(n = 1; n < nvec; ++n)
847       if(strcmp(vec[n], vec[m - 1]))
848         vec[m++] = vec[n];
849   }
850   vec[m] = 0;
851   return vec;
852 }
853
854 /** @brief Store a key/data pair
855  * @param db Database
856  * @param what Description
857  * @param track Data
858  * @param word Key
859  * @param tid Owning transaction
860  * @return 0 or DB_DEADLOCK
861  *
862  * Used by the search and tags databases, hence the odd parameter names.
863  * See also trackdb_delkeydata().
864  */
865 static int register_word(DB *db, const char *what,
866                          const char *track, const char *word,
867                          DB_TXN *tid) {
868   int err;
869   DBT key, data;
870
871   switch(err = db->put(db, tid, make_key(&key, word),
872                        make_key(&data, track), DB_NODUPDATA)) {
873   case 0:
874   case DB_KEYEXIST:
875     return 0;
876   case DB_LOCK_DEADLOCK:
877     disorder_error(0, "error updating %s.db: %s", what, db_strerror(err));
878     return err;
879   default:
880     disorder_fatal(0, "error updating %s.db: %s", what,  db_strerror(err));
881   }
882 }
883
884 /* search primitives *********************************************************/
885
886 /** @brief Return true iff @p name is a trackname_display_ pref
887  * @param name Preference name
888  * @return Non-zero iff @p name is a trackname_display_ pref
889  */
890 static int is_display_pref(const char *name) {
891   static const char prefix[] = "trackname_display_";
892   return !strncmp(name, prefix, (sizeof prefix) - 1);
893 }
894
895 /** @brief Word_Break property tailor that treats underscores as spaces
896  * @param c Code point
897  * @return Tailored property or -1 to use standard value
898  *
899  * Passed to utf32_word_split() when splitting a track name into words.
900  * See word_split() and @ref unicode_property_tailor.
901  */
902 static int tailor_underscore_Word_Break_Other(uint32_t c) {
903   switch(c) {
904   default:
905     return -1;
906   case 0x005F: /* LOW LINE (SPACING UNDERSCORE) */
907     return unicode_Word_Break_Other;
908   }
909 }
910
911 /** @brief Remove all combining characters in-place
912  * @param s Pointer to start of string
913  * @param ns Length of string
914  * @return New, possiblby reduced, length
915  */
916 static size_t remove_combining_chars(uint32_t *s, size_t ns) {
917   uint32_t *start = s, *t = s, *end = s + ns;
918
919   while(s < end) {
920     const uint32_t c = *s++;
921     if(!utf32_combining_class(c))
922       *t++ = c;
923   }
924   return t - start;
925 }
926
927 /** @brief Normalize and split a string using a given tailoring
928  * @param v Where to store words from string
929  * @param s Input string
930  * @param pt Word_Break property tailor, or NULL
931  *
932  * The output words will be:
933  * - case-folded
934  * - have any combination characters stripped
935  * - not include any word break code points (as tailored)
936  *
937  * Used by track_to_words(), with @p pt set to @ref
938  * tailor_underscore_Word_Break_Other, and by normalize_tag() with no
939  * tailoring.
940  */
941 static void word_split(struct vector *v,
942                        const char *s,
943                        unicode_property_tailor *pt) {
944   size_t nw, nt32, i;
945   uint32_t *t32, **w32;
946
947   /* Convert to UTF-32 */
948   if(!(t32 = utf8_to_utf32(s, strlen(s), &nt32)))
949     return;
950   /* Erase case distinctions */
951   if(!(t32 = utf32_casefold_compat(t32, nt32, &nt32)))
952     return;
953   /* Drop combining characters */
954   nt32 = remove_combining_chars(t32, nt32);
955   /* Split into words, treating _ as a space */
956   w32 = utf32_word_split(t32, nt32, &nw, pt);
957   /* Convert words back to UTF-8 and append to result */
958   for(i = 0; i < nw; ++i)
959     vector_append(v, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
960 }
961
962 /** @brief Normalize a tag
963  * @param s Tag
964  * @param ns Length of tag
965  * @return Normalized string or NULL on error
966  *
967  * The return value will be:
968  * - case-folded
969  * - have no leading or trailing space
970  * - have no combining characters
971  * - all spacing between words will be a single U+0020 SPACE
972  */
973 static char *normalize_tag(const char *s, size_t ns) {
974   uint32_t *s32, **w32;
975   size_t ns32, nw32, i;
976   struct dynstr d[1];
977
978   if(!(s32 = utf8_to_utf32(s, ns, &ns32)))
979     return 0;
980   if(!(s32 = utf32_casefold_compat(s32, ns32, &ns32))) /* ->NFKD */
981     return 0;
982   ns32 = remove_combining_chars(s32, ns32);
983   /* Split into words, no Word_Break tailoring */
984   w32 = utf32_word_split(s32, ns32, &nw32, 0);
985   /* Compose back into a string */
986   dynstr_init(d);
987   for(i = 0; i < nw32; ++i) {
988     if(i)
989       dynstr_append(d, ' ');
990     dynstr_append_string(d, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
991   }
992   dynstr_terminate(d);
993   return d->vec;
994 }
995
996 /** @brief Compute the words of a track name
997  * @param track Track name
998  * @param p Preferences (for display prefs)
999  * @return NULL-terminated, de-duplicated list or words
1000  */
1001 static char **track_to_words(const char *track,
1002                              const struct kvp *p) {
1003   struct vector v;
1004   const char *rootless = track_rootless(track);
1005
1006   if(!rootless)
1007     rootless = track;                   /* bodge */
1008   vector_init(&v);
1009   rootless = strip_extension(rootless);
1010   word_split(&v, strip_extension(rootless), tailor_underscore_Word_Break_Other);
1011   for(; p; p = p->next)
1012     if(is_display_pref(p->name))
1013       word_split(&v, p->value, 0);
1014   vector_terminate(&v);
1015   return dedupe(v.vec, v.nvec);
1016 }
1017
1018 /** @brief Test for a stopword
1019  * @param word Word
1020  * @return Non-zero if @p word is a stopword
1021  */
1022 static int stopword(const char *word) {
1023   int n;
1024
1025   for(n = 0; n < config->stopword.n
1026         && strcmp(word, config->stopword.s[n]); ++n)
1027     ;
1028   return n < config->stopword.n;
1029 }
1030
1031 /** @brief Register a search term
1032  * @param track Track name
1033  * @param word A word that appears in the name of @p track
1034  * @param tid Owning transaction
1035  * @return  0 or DB_LOCK_DEADLOCK
1036  */
1037 static int register_search_word(const char *track, const char *word,
1038                                 DB_TXN *tid) {
1039   if(stopword(word)) return 0;
1040   return register_word(trackdb_searchdb, "search", track, word, tid);
1041 }
1042
1043 /* Tags **********************************************************************/
1044
1045 /** @brief Test for tag characters
1046  * @param c Character
1047  * @return Non-zero if @p c is a tag character
1048  *
1049  * The current rule is that commas and the control characters 0-31 are not
1050  * allowed but anything else is permitted.  This is arguably a bit loose.
1051  */
1052 static int tagchar(int c) {
1053   switch(c) {
1054   case ',':
1055     return 0;
1056   default:
1057     return c >= ' ';
1058   }
1059 }
1060
1061 /** @brief Parse a tag list
1062  * @param s Tag list or NULL (equivalent to "")
1063  * @return Parsed tag list
1064  *
1065  * The tags will be normalized (as per normalize_tag()) and de-duplicated.
1066  */
1067 char **parsetags(const char *s) {
1068   const char *t;
1069   struct vector v;
1070
1071   vector_init(&v);
1072   if(s) {
1073     /* skip initial separators */
1074     while(*s && (!tagchar(*s) || *s == ' '))
1075       ++s;
1076     while(*s) {
1077       /* find the extent of the tag */
1078       t = s;
1079       while(*s && tagchar(*s))
1080         ++s;
1081       /* strip trailing spaces */
1082       while(s > t && s[-1] == ' ')
1083         --s;
1084       /* add tag to list */
1085       vector_append(&v, normalize_tag(t, (size_t)(s - t)));
1086       /* skip intermediate and trailing separators */
1087       while(*s && (!tagchar(*s) || *s == ' '))
1088         ++s;
1089     }
1090   }
1091   vector_terminate(&v);
1092   return dedupe(v.vec, v.nvec);
1093 }
1094
1095 /** @brief Register a tag
1096  * @param track Track name
1097  * @param tag Tag name
1098  * @param tid Owning transaction
1099  * @return 0 or DB_LOCK_DEADLOCK
1100  */
1101 static int register_tag(const char *track, const char *tag, DB_TXN *tid) {
1102   return register_word(trackdb_tagsdb, "tags", track, tag, tid);
1103 }
1104
1105 /* aliases *******************************************************************/
1106
1107 /** @brief Compute an alias
1108  * @param aliasp Where to put alias (gets NULL if none)
1109  * @param track Track to find alias for
1110  * @param p Prefs for @p track
1111  * @param tid Owning transaction
1112  * @return 0 or DB_LOCK_DEADLOCK
1113  *
1114  * This function looks up the track name parts for @p track.  By default these
1115  * amount to the original values from the track name but are overridden by
1116  * preferences.
1117  *
1118  * These values are then substituted into the pattern defined by the @b alias
1119  * command; see disorder_config(5) for the syntax.
1120  *
1121  * The track is only considered to have an alias if all of the following are
1122  * true:
1123  * - a preference was used for at least one name part
1124  * - the result differs from the original track name
1125  * - the result does not match any existing track or alias
1126  */
1127 static int compute_alias(char **aliasp,
1128                          const char *track,
1129                          const struct kvp *p,
1130                          DB_TXN *tid) {
1131   struct dynstr d;
1132   const char *s = config->alias, *t, *expansion, *part;
1133   int c, used_db = 0, slash_prefix, err;
1134   struct kvp *at;
1135   const char *const root = find_track_root(track);
1136
1137   if(!root) {
1138     /* Bodge for tracks with no root */
1139     *aliasp = 0;
1140     return 0;
1141   }
1142   dynstr_init(&d);
1143   dynstr_append_string(&d, root);
1144   while((c = (unsigned char)*s++)) {
1145     if(c != '{') {
1146       dynstr_append(&d, c);
1147       continue;
1148     }
1149     if((slash_prefix = (*s == '/')))
1150       s++;
1151     t = strchr(s, '}');
1152     assert(t != 0);                     /* validated at startup */
1153     part = xstrndup(s, t - s);
1154     expansion = getpart(track, "display", part, p, &used_db);
1155     if(*expansion) {
1156       if(slash_prefix) dynstr_append(&d, '/');
1157       dynstr_append_string(&d, expansion);
1158     }
1159     s = t + 1;                          /* skip {part} */
1160   }
1161   /* only admit to the alias if we used the db... */
1162   if(!used_db) {
1163     *aliasp = 0;
1164     return 0;
1165   }
1166   dynstr_terminate(&d);
1167   /* ...and the answer differs from the original... */
1168   if(!strcmp(track, d.vec)) {
1169     *aliasp = 0;
1170     return 0;
1171   }
1172   /* ...and there isn't already a different track with that name (including as
1173    * an alias) */
1174   switch(err = trackdb_getdata(trackdb_tracksdb, d.vec, &at, tid)) {
1175   case 0:
1176     if((s = kvp_get(at, "_alias_for"))
1177        && !strcmp(s, track)) {
1178     case DB_NOTFOUND:
1179       *aliasp = d.vec;
1180     } else {
1181       *aliasp = 0;
1182     }
1183     return 0;
1184   default:
1185     *aliasp = 0;
1186     return err;
1187   }
1188 }
1189
1190 /** @brief Assert that no alias is allowed for gettrackdata() */
1191 #define GTD_NOALIAS 0x0001
1192
1193 /** @brief Get all track data
1194  * @param track Track to look up; aliases allowed unless @ref GTD_NOALIAS
1195  * @param tp Where to put track data (if not NULL)
1196  * @param pp Where to put preferences (if not NULL)
1197  * @param actualp Where to put real (i.e. non-alias) path (if not NULL)
1198  * @param flags Flag values, see below
1199  * @param tid Owning transaction
1200  * @return 0, DB_NOTFOUND (track doesn't exist) or DB_LOCK_DEADLOCK
1201  *
1202  * Possible flags values are:
1203  * - @ref GTD_NOALIAS to assert that an alias is not allowed
1204  *
1205  * The return values are always set (even if to NULL).
1206  */
1207 static int gettrackdata(const char *track,
1208                         struct kvp **tp,
1209                         struct kvp **pp,
1210                         const char **actualp,
1211                         unsigned flags,
1212                         DB_TXN *tid) {
1213   int err;
1214   const char *actual = track;
1215   struct kvp *t = 0, *p = 0;
1216
1217   if((err = trackdb_getdata(trackdb_tracksdb, track, &t, tid))) goto done;
1218   if((actual = kvp_get(t, "_alias_for"))) {
1219     if(flags & GTD_NOALIAS) {
1220       disorder_error(0,
1221                      "alias passed to gettrackdata where real path required");
1222       abort();
1223     }
1224     if((err = trackdb_getdata(trackdb_tracksdb, actual, &t, tid))) goto done;
1225   } else
1226     actual = track;
1227   assert(actual != 0);
1228   if(pp) {
1229     if((err = trackdb_getdata(trackdb_prefsdb, actual, &p, tid)) == DB_LOCK_DEADLOCK)
1230       goto done;
1231   }
1232   err = 0;
1233 done:
1234   if(actualp) *actualp = actual;
1235   if(tp) *tp = t;
1236   if(pp) *pp = p;
1237   return err;
1238 }
1239
1240 /* trackdb_notice() **********************************************************/
1241
1242 /** @brief Notice a possibly new track
1243  * @param track NFC UTF-8 track name
1244  * @param path Raw path name (i.e. the bytes that came out of readdir())
1245  * @return @c DB_NOTFOUND if new, 0 if already known
1246  *
1247  * @c disorder-rescan is responsible for normalizing the track name.
1248  */
1249 int trackdb_notice(const char *track,
1250                    const char *path) {
1251   int err;
1252   DB_TXN *tid;
1253
1254   for(;;) {
1255     tid = trackdb_begin_transaction();
1256     err = trackdb_notice_tid(track, path, tid);
1257     if(err == DB_LOCK_DEADLOCK) goto fail;
1258     break;
1259   fail:
1260     trackdb_abort_transaction(tid);
1261   }
1262   trackdb_commit_transaction(tid);
1263   return err;
1264 }
1265
1266 /** @brief Notice a possibly new track
1267  * @param track NFC UTF-8 track name
1268  * @param path Raw path name (i.e. the bytes that came out of readdir())
1269  * @param tid Owning transaction
1270  * @return @c DB_NOTFOUND if new, 0 if already known, @c DB_LOCK_DEADLOCK also
1271  *
1272  * @c disorder-rescan is responsible for normalizing the track name.
1273  */
1274 int trackdb_notice_tid(const char *track,
1275                        const char *path,
1276                        DB_TXN *tid) {
1277   int err, n;
1278   struct kvp *t, *a, *p;
1279   int t_changed, ret;
1280   char *alias, **w, *noticed;
1281   time_t now;
1282
1283   /* notice whether the tracks.db entry changes */
1284   t_changed = 0;
1285   /* get any existing tracks entry */
1286   if((err = gettrackdata(track, &t, &p, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1287     return err;
1288   ret = err;                            /* 0 or DB_NOTFOUND */
1289   /* this is a real track */
1290   t_changed += kvp_set(&t, "_alias_for", 0);
1291   t_changed += kvp_set(&t, "_path", path);
1292   xtime(&now);
1293   if(ret == DB_NOTFOUND) {
1294     /* It's a new track; record the time */
1295     byte_xasprintf(&noticed, "%lld", (long long)now);
1296     t_changed += kvp_set(&t, "_noticed", noticed);
1297   }
1298   /* if we have an alias record it in the database */
1299   if((err = compute_alias(&alias, track, p, tid))) return err;
1300   if(alias) {
1301     /* won't overwrite someone else's alias as compute_alias() checks */
1302     D(("%s: alias %s", track, alias));
1303     a = 0;
1304     kvp_set(&a, "_alias_for", track);
1305     if((err = trackdb_putdata(trackdb_tracksdb, alias, a, tid, 0))) return err;
1306   }
1307   /* update search.db */
1308   w = track_to_words(track, p);
1309   for(n = 0; w[n]; ++n)
1310     if((err = register_search_word(track, w[n], tid)))
1311       return err;
1312   /* update tags.db */
1313   w = parsetags(kvp_get(p, "tags"));
1314   for(n = 0; w[n]; ++n)
1315     if((err = register_tag(track, w[n], tid)))
1316       return err;
1317   /* only store the tracks.db entry if it has changed */
1318   if(t_changed && (err = trackdb_putdata(trackdb_tracksdb, track, t, tid, 0)))
1319     return err;
1320   if(ret == DB_NOTFOUND) {
1321     uint32_t timestamp[2];
1322     DBT key, data;
1323
1324     timestamp[0] = htonl((uint64_t)now >> 32);
1325     timestamp[1] = htonl((uint32_t)now);
1326     memset(&key, 0, sizeof key);
1327     key.data = timestamp;
1328     key.size = sizeof timestamp;
1329     switch(err = trackdb_noticeddb->put(trackdb_noticeddb, tid, &key,
1330                                         make_key(&data, track), 0)) {
1331     case 0: break;
1332     case DB_LOCK_DEADLOCK: return err;
1333     default:
1334       disorder_fatal(0, "error updating noticed.db: %s", db_strerror(err));
1335     }
1336   }
1337   return ret;
1338 }
1339
1340 /* trackdb_obsolete() ********************************************************/
1341
1342 /** @brief Obsolete a track
1343  * @param track Track name
1344  * @param tid Owning transaction
1345  * @return 0 or DB_LOCK_DEADLOCK
1346  *
1347  * Discards a track from the database when it's known not to exist any more.
1348  * Returns 0 even if it wasn't recorded.
1349  */
1350 int trackdb_obsolete(const char *track, DB_TXN *tid) {
1351   int err, n;
1352   struct kvp *p;
1353   char *alias, **w;
1354
1355   if((err = gettrackdata(track, 0, &p, 0,
1356                          GTD_NOALIAS, tid)) == DB_LOCK_DEADLOCK)
1357     return err;
1358   else if(err == DB_NOTFOUND) return 0;
1359   /* compute the alias, if any, and delete it */
1360   if((err = compute_alias(&alias, track, p, tid))) return err;
1361   if(alias) {
1362     /* if the alias points to some other track then compute_alias won't
1363      * return it */
1364     if((err = trackdb_delkey(trackdb_tracksdb, alias, tid))
1365        && err != DB_NOTFOUND)
1366       return err;
1367   }
1368   /* update search.db */
1369   w = track_to_words(track, p);
1370   for(n = 0; w[n]; ++n)
1371     if(trackdb_delkeydata(trackdb_searchdb,
1372                           w[n], track, tid) == DB_LOCK_DEADLOCK)
1373       return err;
1374   /* update tags.db */
1375   w = parsetags(kvp_get(p, "tags"));
1376   for(n = 0; w[n]; ++n)
1377     if(trackdb_delkeydata(trackdb_tagsdb,
1378                           w[n], track, tid) == DB_LOCK_DEADLOCK)
1379       return err;
1380   /* update tracks.db */
1381   if(trackdb_delkey(trackdb_tracksdb, track, tid) == DB_LOCK_DEADLOCK)
1382     return err;
1383   /* We don't delete the prefs, so they survive temporary outages of the
1384    * (possibly virtual) track filesystem */
1385   return 0;
1386 }
1387
1388 /* trackdb_stats() ***********************************************************/
1389
1390 #define H(name) { #name, offsetof(DB_HASH_STAT, name) }
1391 #define B(name) { #name, offsetof(DB_BTREE_STAT, name) }
1392
1393 /** @brief Table of libdb stats to return */
1394 static const struct statinfo {
1395   const char *name;
1396   size_t offset;
1397 } statinfo_hash[] = {
1398   H(hash_magic),
1399   H(hash_version),
1400   H(hash_nkeys),
1401   H(hash_ndata),
1402   H(hash_pagesize),
1403   H(hash_ffactor),
1404   H(hash_buckets),
1405   H(hash_free),
1406   H(hash_bfree),
1407   H(hash_bigpages),
1408   H(hash_big_bfree),
1409   H(hash_overflows),
1410   H(hash_ovfl_free),
1411   H(hash_dup),
1412   H(hash_dup_free),
1413 }, statinfo_btree[] = {
1414   B(bt_magic),
1415   B(bt_version),
1416   B(bt_nkeys),
1417   B(bt_ndata),
1418   B(bt_pagesize),
1419   B(bt_minkey),
1420   B(bt_re_len),
1421   B(bt_re_pad),
1422   B(bt_levels),
1423   B(bt_int_pg),
1424   B(bt_leaf_pg),
1425   B(bt_dup_pg),
1426   B(bt_over_pg),
1427   B(bt_free),
1428   B(bt_int_pgfree),
1429   B(bt_leaf_pgfree),
1430   B(bt_dup_pgfree),
1431   B(bt_over_pgfree),
1432 };
1433
1434 /** @brief Look up DB statistics
1435  * @param v Where to store stats
1436  * @param database Database
1437  * @param si Pointer to table of stats
1438  * @param nsi Size of @p si
1439  * @param tid Owning transaction
1440  * @return 0 or DB_LOCK_DEADLOCK
1441  */
1442 static int get_stats(struct vector *v,
1443                      DB *database,
1444                      const struct statinfo *si,
1445                      size_t nsi,
1446                      DB_TXN *tid) {
1447   void *sp;
1448   size_t n;
1449   char *str;
1450   int err;
1451
1452   if(database) {
1453     switch(err = database->stat(database, tid, &sp, 0)) {
1454     case 0:
1455       break;
1456     case DB_LOCK_DEADLOCK:
1457       disorder_error(0, "error querying database: %s", db_strerror(err));
1458       return err;
1459     default:
1460       disorder_fatal(0, "error querying database: %s", db_strerror(err));
1461     }
1462     for(n = 0; n < nsi; ++n) {
1463       byte_xasprintf(&str, "%s=%"PRIuMAX, si[n].name,
1464                      (uintmax_t)*(u_int32_t *)((char *)sp + si[n].offset));
1465       vector_append(v, str);
1466     }
1467   }
1468   return 0;
1469 }
1470
1471 /** @brief One entry in the search league */
1472 struct search_entry {
1473   char *word;
1474   int n;
1475 };
1476
1477 /** @brief Add a word to the search league
1478  * @param se Pointer to search league
1479  * @param count Maximum size for search league
1480  * @param nse Current size of search league
1481  * @param word New word, or NULL
1482  * @param n How often @p word appears
1483  * @return New size of search league
1484  */
1485 static int register_search_entry(struct search_entry *se,
1486                                  int count,
1487                                  int nse,
1488                                  char *word,
1489                                  int n) {
1490   int i;
1491
1492   if(word && (nse < count || n > se[nse - 1].n)) {
1493     /* Find the starting point */
1494     if(nse == count)
1495       i = nse - 1;
1496     else
1497       i = nse++;
1498     /* Find the insertion point */
1499     while(i > 0 && n > se[i - 1].n)
1500       --i;
1501     memmove(&se[i + 1], &se[i], (nse - i - 1) * sizeof *se);
1502     se[i].word = word;
1503     se[i].n = n;
1504   }
1505   return nse;
1506 }
1507
1508 /** @brief Find the top @p count words in the search database
1509  * @param v Where to format the result
1510  * @param count Maximum number of words
1511  * @param tid Owning transaction
1512  * @return 0 or DB_LOCK_DEADLOCK
1513  */
1514 static int search_league(struct vector *v, int count, DB_TXN *tid) {
1515   struct search_entry *se;
1516   DBT k, d;
1517   DBC *cursor;
1518   int err, n = 0, nse = 0, i;
1519   char *word = 0;
1520   size_t wl = 0;
1521   char *str;
1522
1523   cursor = trackdb_opencursor(trackdb_searchdb, tid);
1524   se = xmalloc(count * sizeof *se);
1525   /* Walk across the whole database counting up the number of times each
1526    * word appears. */
1527   while(!(err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
1528                               DB_NEXT))) {
1529     if(word && wl == k.size && !strncmp(word, k.data, wl))
1530       ++n;                              /* same word again */
1531     else {
1532       nse = register_search_entry(se, count, nse, word, n);
1533       word = xstrndup(k.data, wl = k.size);
1534       n = 1;
1535     }
1536   }
1537   switch(err) {
1538   case DB_NOTFOUND:
1539     err = 0;
1540     break;
1541   case DB_LOCK_DEADLOCK:
1542     disorder_error(0, "error querying search database: %s", db_strerror(err));
1543     break;
1544   default:
1545     disorder_fatal(0, "error querying search database: %s", db_strerror(err));
1546   }
1547   if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1548   if(err) return err;
1549   nse = register_search_entry(se, count, nse, word, n);
1550   byte_xasprintf(&str, "Top %d search words:", nse);
1551   vector_append(v, str);
1552   for(i = 0; i < nse; ++i) {
1553     byte_xasprintf(&str, "%4d: %5d %s", i + 1, se[i].n, se[i].word);
1554     vector_append(v, str);
1555   }
1556   return 0;
1557 }
1558
1559 #define SI(what) statinfo_##what, \
1560                  sizeof statinfo_##what / sizeof (struct statinfo)
1561
1562 /** @brief Return a list of database stats
1563  * @param nstatsp Where to store number of lines (or NULL)
1564  * @return Database stats output
1565  *
1566  * This is called by @c disorder-stats.  Don't call it directly from elsewhere
1567  * as it can take unreasonably long.
1568  */
1569 char **trackdb_stats(int *nstatsp) {
1570   DB_TXN *tid;
1571   struct vector v;
1572
1573   vector_init(&v);
1574   for(;;) {
1575     tid = trackdb_begin_transaction();
1576     v.nvec = 0;
1577     vector_append(&v, (char *)"Tracks database stats:");
1578     if(get_stats(&v, trackdb_tracksdb, SI(btree), tid)) goto fail;
1579     vector_append(&v, (char *)"");
1580     vector_append(&v, (char *)"Search database stats:");
1581     if(get_stats(&v, trackdb_searchdb, SI(hash), tid)) goto fail;
1582     vector_append(&v, (char *)"");
1583     vector_append(&v, (char *)"Prefs database stats:");
1584     if(get_stats(&v, trackdb_prefsdb, SI(hash), tid)) goto fail;
1585     vector_append(&v, (char *)"");
1586     if(search_league(&v, 10, tid)) goto fail;
1587     vector_terminate(&v);
1588     break;
1589 fail:
1590     trackdb_abort_transaction(tid);
1591   }
1592   trackdb_commit_transaction(tid);
1593   if(nstatsp) *nstatsp = v.nvec;
1594   return v.vec;
1595 }
1596
1597 /** @brief State structure tracking @c disorder-stats */
1598 struct stats_details {
1599   void (*done)(char *data, void *u);
1600   void *u;
1601   int exited;                           /* subprocess exited */
1602   int closed;                           /* pipe close */
1603   int wstat;                            /* wait status from subprocess */
1604   struct dynstr data[1];                /* data read from pipe */
1605 };
1606
1607 /** @brief Called when @c disorder-stats may have completed
1608  * @param d Pointer to state structure
1609  *
1610  * Called from stats_finished() and stats_read().  Only proceeds when the
1611  * process has terminated and the output is complete.
1612  */
1613 static void stats_complete(struct stats_details *d) {
1614   char *s;
1615
1616   if(!(d->exited && d->closed))
1617     return;
1618   byte_xasprintf(&s, "\n"
1619                  "Server stats:\n"
1620                  "track lookup cache hits: %lu\n"
1621                  "track lookup cache misses: %lu\n",
1622                  cache_files_hits,
1623                  cache_files_misses);
1624   dynstr_append_string(d->data, s);
1625   dynstr_terminate(d->data);
1626   d->done(d->data->vec, d->u);
1627 }
1628
1629 /** @brief Called when @c disorder-stats exits
1630  * @param ev Event loop
1631  * @param pid Process ID
1632  * @param status Exit status
1633  * @param rusage Resource usage
1634  * @param u Pointer to state structure (@ref stats_details)
1635  * @return 0
1636  */
1637 static int stats_finished(ev_source attribute((unused)) *ev,
1638                           pid_t pid,
1639                           int status,
1640                           const struct rusage attribute((unused)) *rusage,
1641                           void *u) {
1642   struct stats_details *const d = u;
1643
1644   d->exited = 1;
1645   if(status)
1646     disorder_error(0, "disorder-stats %s", wstat(status));
1647   stats_complete(d);
1648   char *k;
1649   byte_xasprintf(&k, "%lu", (unsigned long)pid);
1650   hash_remove(stats_pids, k);
1651   return 0;
1652 }
1653
1654 /** @brief Called when pipe from @c disorder-stats is readable
1655  * @param ev Event loop
1656  * @param reader Reader state
1657  * @param ptr Pointer to bytes read
1658  * @param bytes Number of bytes available
1659  * @param eof Set at end of file
1660  * @param u Pointer to state structure (@ref stats_details)
1661  * @return 0
1662  */
1663 static int stats_read(ev_source attribute((unused)) *ev,
1664                       ev_reader *reader,
1665                       void *ptr,
1666                       size_t bytes,
1667                       int eof,
1668                       void *u) {
1669   struct stats_details *const d = u;
1670
1671   dynstr_append_bytes(d->data, ptr, bytes);
1672   ev_reader_consume(reader, bytes);
1673   if(eof)
1674     d->closed = 1;
1675   stats_complete(d);
1676   return 0;
1677 }
1678
1679 /** @brief Called when pipe from @c disorder-stats errors
1680  * @param ev Event loop
1681  * @param errno_value Error code
1682  * @param u Pointer to state structure (@ref stats_details)
1683  * @return 0
1684  */
1685 static int stats_error(ev_source attribute((unused)) *ev,
1686                        int errno_value,
1687                        void *u) {
1688   struct stats_details *const d = u;
1689
1690   disorder_error(errno_value, "error reading from pipe to disorder-stats");
1691   d->closed = 1;
1692   stats_complete(d);
1693   return 0;
1694 }
1695
1696 /** @brief Get database statistics via background process
1697  * @param ev Event loop
1698  * @param done Called on completion
1699  * @param u Passed to @p done
1700  *
1701  * Within the main server use this instead of trackdb_stats(), which can take
1702  * unreasonably long.
1703  */
1704 void trackdb_stats_subprocess(ev_source *ev,
1705                               void (*done)(char *data, void *u),
1706                               void *u) {
1707   int p[2];
1708   pid_t pid;
1709   struct stats_details *d = xmalloc(sizeof *d);
1710
1711   dynstr_init(d->data);
1712   d->done = done;
1713   d->u = u;
1714   xpipe(p);
1715   pid = subprogram(ev, p[1], "disorder-stats", (char *)0);
1716   xclose(p[1]);
1717   ev_child(ev, pid, 0, stats_finished, d);
1718   if(!ev_reader_new(ev, p[0], stats_read, stats_error, d,
1719                     "disorder-stats reader"))
1720     disorder_fatal(0, "ev_reader_new for disorder-stats reader failed");
1721   /* Remember the PID */
1722   if(!stats_pids)
1723     stats_pids = hash_new(1);
1724   char *k;
1725   byte_xasprintf(&k, "%lu", (unsigned long)pid);
1726   hash_add(stats_pids, k, "", HASH_INSERT);
1727 }
1728
1729 /** @brief Parse a track name part preference
1730  * @param name Preference name
1731  * @param partp Where to store part name
1732  * @param contextp Where to store context name
1733  * @return 0 on success, non-0 if parse fails
1734  */
1735 static int trackdb__parse_namepref(const char *name,
1736                                    char **partp,
1737                                    char **contextp) {
1738   char *c;
1739   static const char prefix[] = "trackname_";
1740   
1741   if(strncmp(name, prefix, strlen(prefix)))
1742     return -1;                          /* not trackname_* at all */
1743   name += strlen(prefix);
1744   /* There had better be a _ between context and part */
1745   c = strchr(name, '_');
1746   if(!c)
1747     return -1;
1748   /* Context is first in the pref name even though most APIs have the part
1749    * first.  Confusing; sorry. */
1750   *contextp = xstrndup(name, c - name);
1751   ++c;
1752   /* There had better NOT be a second _ */
1753   if(strchr(c, '_'))
1754     return -1;
1755   *partp = xstrdup(c);
1756   return 0;
1757 }
1758
1759 /** @brief Compute the default value for a track preference
1760  * @param track Track name
1761  * @param name Preference name
1762  * @return Default value or 0 if none/not known
1763  */
1764 static const char *trackdb__default(const char *track, const char *name) {
1765   char *context, *part;
1766   
1767   if(!trackdb__parse_namepref(name, &part, &context)) {
1768     /* We can work out the default for a trackname_ pref */
1769     return trackname_part(track, context, part);
1770   } else if(!strcmp(name, "weight")) {
1771     /* We know the default weight */
1772     return "90000";
1773   } else if(!strcmp(name, "pick_at_random")) {
1774     /* By default everything is eligible for picking at random */
1775     return "1";
1776   } else if(!strcmp(name, "tags")) {
1777     /* By default everything no track has any tags */
1778     return "";
1779   }
1780   return 0;
1781 }
1782
1783 /** @brief Set a preference
1784  * @param track Track to modify
1785  * @param name Preference name
1786  * @param value New value, or NULL to erase any existing value
1787  * @return 0 on success or non-zero if not allowed to set preference
1788  */
1789 int trackdb_set(const char *track,
1790                 const char *name,
1791                 const char *value) {
1792   struct kvp *t, *p, *a;
1793   DB_TXN *tid;
1794   int err, cmp;
1795   char *oldalias, *newalias, **oldtags = 0, **newtags;
1796   const char *def;
1797
1798   /* If the value matches the default then unset instead, to keep the database
1799    * tidy.  Older versions did not have this feature so your database may yet
1800    * have some default values stored in it. */
1801   if(value) {
1802     def = trackdb__default(track, name);
1803     if(def && !strcmp(value, def))
1804       value = 0;
1805   }
1806
1807   for(;;) {
1808     tid = trackdb_begin_transaction();
1809     if((err = gettrackdata(track, &t, &p, 0,
1810                            0, tid)) == DB_LOCK_DEADLOCK)
1811       goto fail;
1812     if(err == DB_NOTFOUND) break;
1813     if(name[0] == '_') {
1814       if(kvp_set(&t, name, value))
1815         if(trackdb_putdata(trackdb_tracksdb, track, t, tid, 0))
1816           goto fail;
1817     } else {
1818       /* get the old alias name */
1819       if(compute_alias(&oldalias, track, p, tid)) goto fail;
1820       /* get the old tags */
1821       if(!strcmp(name, "tags"))
1822         oldtags = parsetags(kvp_get(p, "tags"));
1823       /* set the value */
1824       if(kvp_set(&p, name, value))
1825         if(trackdb_putdata(trackdb_prefsdb, track, p, tid, 0))
1826           goto fail;
1827       /* compute the new alias name */
1828       if(compute_alias(&newalias, track, p, tid)) goto fail;
1829       /* check whether alias has changed */
1830       if(!(oldalias == newalias
1831            || (oldalias && newalias && !strcmp(oldalias, newalias)))) {
1832         /* adjust alias records to fit change */
1833         if(oldalias
1834            && trackdb_delkey(trackdb_tracksdb, oldalias, tid) == DB_LOCK_DEADLOCK)
1835           goto fail;
1836         if(newalias) {
1837           a = 0;
1838           kvp_set(&a, "_alias_for", track);
1839           if(trackdb_putdata(trackdb_tracksdb, newalias, a, tid, 0)) goto fail;
1840         }
1841       }
1842       /* check whether tags have changed */
1843       if(!strcmp(name, "tags")) {
1844         newtags = parsetags(value);
1845         while(*oldtags || *newtags) {
1846           if(*oldtags && *newtags) {
1847             cmp = strcmp(*oldtags, *newtags);
1848             if(!cmp) {
1849               /* keeping this tag */
1850               ++oldtags;
1851               ++newtags;
1852             } else if(cmp < 0)
1853               /* old tag fits into a gap in the new list, so delete old */
1854               goto delete_old;
1855             else
1856               /* new tag fits into a gap in the old list, so insert new */
1857               goto insert_new;
1858           } else if(*oldtags) {
1859             /* we've run out of new tags, so remaining old ones are to be
1860              * deleted */
1861           delete_old:
1862             if(trackdb_delkeydata(trackdb_tagsdb,
1863                                   *oldtags, track, tid) == DB_LOCK_DEADLOCK)
1864               goto fail;
1865             ++oldtags;
1866           } else {
1867             /* we've run out of old tags, so remainig new ones are to be
1868              * inserted */
1869           insert_new:
1870             if(register_tag(track, *newtags, tid)) goto fail;
1871             ++newtags;
1872           }
1873         }
1874       }
1875     }
1876     err = 0;
1877     break;
1878 fail:
1879     trackdb_abort_transaction(tid);
1880   }
1881   trackdb_commit_transaction(tid);
1882   return err == 0 ? 0 : -1;
1883 }
1884
1885 /** @brief Get the value of a preference
1886  * @param track Track name
1887  * @param name Preference name
1888  * @return Preference value or NULL if it's not set
1889  */
1890 const char *trackdb_get(const char *track,
1891                         const char *name) {
1892   return kvp_get(trackdb_get_all(track), name);
1893 }
1894
1895 /** @brief Get all preferences for a track
1896  * @param track Track name
1897  * @return Linked list of preferences
1898  */
1899 struct kvp *trackdb_get_all(const char *track) {
1900   struct kvp *t, *p, **pp;
1901   DB_TXN *tid;
1902
1903   for(;;) {
1904     tid = trackdb_begin_transaction();
1905     if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1906       goto fail;
1907     break;
1908 fail:
1909     trackdb_abort_transaction(tid);
1910   }
1911   trackdb_commit_transaction(tid);
1912   for(pp = &p; *pp; pp = &(*pp)->next)
1913     ;
1914   *pp = t;
1915   return p;
1916 }
1917
1918 /** @brief Resolve an alias
1919  * @param track Track name (might be an alias)
1920  * @return Real track name (definitely not an alias) or NULL if no such track
1921  */
1922 const char *trackdb_resolve(const char *track) {
1923   DB_TXN *tid;
1924   const char *actual;
1925
1926   for(;;) {
1927     tid = trackdb_begin_transaction();
1928     if(gettrackdata(track, 0, 0, &actual, 0, tid) == DB_LOCK_DEADLOCK)
1929       goto fail;
1930     break;
1931 fail:
1932     trackdb_abort_transaction(tid);
1933   }
1934   trackdb_commit_transaction(tid);
1935   return actual;
1936 }
1937
1938 /** @brief Detect an alias
1939  * @param track Track name
1940  * @return Nonzero if @p track exists and is an alias
1941  */
1942 int trackdb_isalias(const char *track) {
1943   const char *actual = trackdb_resolve(track);
1944
1945   return strcmp(actual, track);
1946 }
1947
1948 /** @brief Detect whether a track exists
1949  * @param track Track name (can be an alias)
1950  * @return Nonzero if @p track exists (whether or not it's an alias)
1951  */
1952 int trackdb_exists(const char *track) {
1953   DB_TXN *tid;
1954   int err;
1955
1956   for(;;) {
1957     tid = trackdb_begin_transaction();
1958     /* unusually, here we want the return value */
1959     if((err = gettrackdata(track, 0, 0, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1960       goto fail;
1961     break;
1962 fail:
1963     trackdb_abort_transaction(tid);
1964   }
1965   trackdb_commit_transaction(tid);
1966   return (err == 0);
1967 }
1968
1969 /** @brief Return list of all known tags
1970  * @return NULL-terminated tag list
1971  */
1972 char **trackdb_alltags(void) {
1973   int e;
1974   struct vector v[1];
1975
1976   vector_init(v);
1977   WITH_TRANSACTION(trackdb_listkeys(trackdb_tagsdb, v, tid));
1978   return v->vec;
1979 }
1980
1981 /** @brief List all the keys in @p db
1982  * @param db Database
1983  * @param v Vector to store keys in
1984  * @param tid Transaction ID
1985  * @return 0 or DB_LOCK_DEADLOCK
1986  */
1987 int trackdb_listkeys(DB *db, struct vector *v, DB_TXN *tid) {
1988   int e;
1989   DBT k, d;
1990   DBC *const c = trackdb_opencursor(db, tid);
1991
1992   v->nvec = 0;
1993   memset(&k, 0, sizeof k);
1994   while(!(e = c->c_get(c, &k, prepare_data(&d), DB_NEXT_NODUP)))
1995     vector_append(v, xstrndup(k.data, k.size));
1996   switch(e) {
1997   case DB_NOTFOUND:
1998     break;
1999   case DB_LOCK_DEADLOCK:
2000     return e;
2001   default:
2002     disorder_fatal(0, "c->c_get: %s", db_strerror(e));
2003   }
2004   if((e = trackdb_closecursor(c)))
2005     return e;
2006   vector_terminate(v);
2007   return 0;
2008 }
2009
2010 /* return 1 iff sorted tag lists A and B have at least one member in common */
2011 /** @brief Detect intersecting tag lists
2012  * @param a First list of tags (NULL-terminated)
2013  * @param b Second list of tags (NULL-terminated)
2014  * @return 1 if @p a and @p b have at least one member in common
2015  *
2016  * @p a and @p must be sorted.
2017  */
2018 int tag_intersection(char **a, char **b) {
2019   int cmp;
2020
2021   /* Same sort of logic as trackdb_set() above */
2022   while(*a && *b) {
2023     if(!(cmp = strcmp(*a, *b))) return 1;
2024     else if(cmp < 0) ++a;
2025     else ++b;
2026   }
2027   return 0;
2028 }
2029
2030 /** @brief Called when disorder-choose might have completed
2031  * @param ev Event loop
2032  * @param which @ref CHOOSE_RUNNING or @ref CHOOSE_READING
2033  *
2034  * Once called with both @p which values, @ref choose_callback is called
2035  * (usually chosen_random_track()).
2036  */
2037 static void choose_finished(ev_source *ev, unsigned which) {
2038   choose_complete |= which;
2039   if(choose_complete != (CHOOSE_RUNNING|CHOOSE_READING))
2040     return;
2041   choose_pid = -1;
2042   if(choose_status == 0 && choose_output.nvec > 0) {
2043     dynstr_terminate(&choose_output);
2044     choose_callback(ev, xstrdup(choose_output.vec));
2045   } else
2046     choose_callback(ev, 0);
2047 }
2048
2049 /** @brief Called when @c disorder-choose terminates
2050  * @param ev Event loop
2051  * @param pid Process ID
2052  * @param status Exit status
2053  * @param rusage Resource usage
2054  * @param u User data
2055  * @return 0
2056  */
2057 static int choose_exited(ev_source *ev,
2058                          pid_t attribute((unused)) pid,
2059                          int status,
2060                          const struct rusage attribute((unused)) *rusage,
2061                          void attribute((unused)) *u) {
2062   if(status)
2063     disorder_error(0, "disorder-choose %s", wstat(status));
2064   choose_status = status;
2065   choose_finished(ev, CHOOSE_RUNNING);
2066   return 0;
2067 }
2068
2069 /** @brief Called with data from @c disorder-choose pipe
2070  * @param ev Event loop
2071  * @param reader Reader state
2072  * @param ptr Data read
2073  * @param bytes Number of bytes read
2074  * @param eof Set at end of file
2075  * @param u User data
2076  * @return 0
2077  */
2078 static int choose_readable(ev_source *ev,
2079                            ev_reader *reader,
2080                            void *ptr,
2081                            size_t bytes,
2082                            int eof,
2083                            void attribute((unused)) *u) {
2084   dynstr_append_bytes(&choose_output, ptr, bytes);
2085   ev_reader_consume(reader, bytes);
2086   if(eof)
2087     choose_finished(ev, CHOOSE_READING);
2088   return 0;
2089 }
2090
2091 /** @brief Called when @c disorder-choose pipe errors
2092  * @param ev Event loop
2093  * @param errno_value Error code
2094  * @param u User data
2095  * @return 0
2096  */
2097 static int choose_read_error(ev_source *ev,
2098                              int errno_value,
2099                              void attribute((unused)) *u) {
2100   disorder_error(errno_value, "error reading disorder-choose pipe");
2101   choose_finished(ev, CHOOSE_READING);
2102   return 0;
2103 }
2104
2105 /** @brief Request a random track
2106  * @param ev Event source
2107  * @param callback Called with random track or NULL
2108  * @return 0 if a request was initiated, else -1
2109  *
2110  * Initiates a random track choice.  @p callback will later be called back with
2111  * the choice (or NULL on error).  If a choice is already underway then -1 is
2112  * returned and there will be no additional callback.
2113  *
2114  * The caller shouldn't assume that the track returned actually exists (it
2115  * might be removed between the choice and the callback, or between being added
2116  * to the queue and being played).
2117  */
2118 int trackdb_request_random(ev_source *ev,
2119                            random_callback *callback) {
2120   int p[2];
2121   
2122   if(choose_pid != -1)
2123     return -1;                          /* don't run concurrent chooses */
2124   xpipe(p);
2125   cloexec(p[0]);
2126   choose_pid = subprogram(ev, p[1], "disorder-choose", (char *)0);
2127   choose_fd = p[0];
2128   xclose(p[1]);
2129   choose_callback = callback;
2130   choose_output.nvec = 0;
2131   choose_complete = 0;
2132   if(!ev_reader_new(ev, p[0], choose_readable, choose_read_error, 0,
2133                     "disorder-choose reader")) /* owns p[0] */
2134     disorder_fatal(0, "ev_reader_new for disorder-choose reader failed");
2135   ev_child(ev, choose_pid, 0, choose_exited, 0); /* owns the subprocess */
2136   return 0;
2137 }
2138
2139 /** @brief Get a track name part, using prefs
2140  * @param track Track name
2141  * @param context Context ("display" etc)
2142  * @param part Part ("album" etc)
2143  * @param p Preference
2144  * @param used_db Set if a preference is used
2145  * @return Name part (never NULL)
2146  *
2147  * Used by compute_alias() and trackdb_getpart().
2148  */
2149 static const char *getpart(const char *track,
2150                            const char *context,
2151                            const char *part,
2152                            const struct kvp *p,
2153                            int *used_db) {
2154   const char *result;
2155   char *pref;
2156
2157   byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2158   if((result = kvp_get(p, pref)))
2159     *used_db = 1;
2160   else
2161     result = trackname_part(track, context, part);
2162   assert(result != 0);
2163   return result;
2164 }
2165
2166 /** @brief Get a track name part
2167  * @param track Track name
2168  * @param context Context ("display" etc)
2169  * @param part Part ("album" etc)
2170  * @return Name part (never NULL)
2171  *
2172  * This is interface used by c_part().
2173  */
2174 const char *trackdb_getpart(const char *track,
2175                             const char *context,
2176                             const char *part) {
2177   struct kvp *p;
2178   DB_TXN *tid;
2179   char *pref;
2180   const char *actual;
2181   int used_db;
2182
2183   /* construct the full pref */
2184   byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2185   for(;;) {
2186     tid = trackdb_begin_transaction();
2187     if(gettrackdata(track, 0, &p, &actual, 0, tid) == DB_LOCK_DEADLOCK)
2188       goto fail;
2189     break;
2190 fail:
2191     trackdb_abort_transaction(tid);
2192   }
2193   trackdb_commit_transaction(tid);
2194   return getpart(actual, context, part, p, &used_db);
2195 }
2196
2197 /** @brief Get the raw (filesystem) path for @p track
2198  * @param track track Track name (can be an alias)
2199  * @return Raw path (never NULL)
2200  *
2201  * The raw path is the actual bytes that came out of readdir() etc.
2202  */
2203 const char *trackdb_rawpath(const char *track) {
2204   DB_TXN *tid;
2205   struct kvp *t;
2206   const char *path;
2207
2208   for(;;) {
2209     tid = trackdb_begin_transaction();
2210     if(gettrackdata(track, &t, 0, 0, 0, tid) == DB_LOCK_DEADLOCK)
2211       goto fail;
2212     break;
2213 fail:
2214     trackdb_abort_transaction(tid);
2215   }
2216   trackdb_commit_transaction(tid);
2217   if(!(path = kvp_get(t, "_path"))) path = track;
2218   return path;
2219 }
2220
2221 /* trackdb_list **************************************************************/
2222
2223 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
2224  * readable at some point */
2225
2226 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
2227  * If RE is a null pointer then it matches everything. */
2228 /** @brief Match a track against a rgeexp
2229  * @param dl Length of directory part of track
2230  * @param track Track name
2231  * @param tl Length of track name
2232  * @param re Regular expression or NULL
2233  * @return Nonzero on match
2234  *
2235  * @p tl is the total length of @p track, @p dl is the length of the directory
2236  * part (the index of the final "/").  The subject of the regexp match is the
2237  * basename, i.e. the part after @p dl.
2238  *
2239  * If @p re is NULL then always matches.
2240  */
2241 static int track_matches(size_t dl, const char *track, size_t tl,
2242                          const pcre *re) {
2243   int ovec[3], rc;
2244
2245   if(!re)
2246     return 1;
2247   track += dl + 1;
2248   tl -= (dl + 1);
2249   switch(rc = pcre_exec(re, 0, track, tl, 0, 0, ovec, 3)) {
2250   case PCRE_ERROR_NOMATCH: return 0;
2251   default:
2252     if(rc < 0) {
2253       disorder_error(0, "pcre_exec returned %d, subject '%s'", rc, track);
2254       return 0;
2255     }
2256     return 1;
2257   }
2258 }
2259
2260 /** @brief Generate a list of tracks and/or directories in @p dir
2261  * @param v Where to put results
2262  * @param dir Directory to list
2263  * @param what Bitmap of objects to return
2264  * @param re Regexp to filter matches (or NULL to accept all)
2265  * @param tid Owning transaction
2266  * @return 0 or DB_LOCK_DEADLOCK
2267  */
2268 static int do_list(struct vector *v, const char *dir,
2269                    enum trackdb_listable what, const pcre *re, DB_TXN *tid) {
2270   DBC *cursor;
2271   DBT k, d;
2272   size_t dl;
2273   char *ptr;
2274   int err;
2275   size_t l, last_dir_len = 0;
2276   char *last_dir = 0, *track;
2277   struct kvp *p;
2278
2279   dl = strlen(dir);
2280   cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2281   make_key(&k, dir);
2282   prepare_data(&d);
2283   /* find the first key >= dir */
2284   err = cursor->c_get(cursor, &k, &d, DB_SET_RANGE);
2285   /* keep going while we're dealing with <dir/anything> */
2286   while(err == 0
2287         && k.size > dl
2288         && ((char *)k.data)[dl] == '/'
2289         && !memcmp(k.data, dir, dl)) {
2290     ptr = memchr((char *)k.data + dl + 1, '/', k.size - (dl + 1));
2291     if(ptr) {
2292       /* we have <dir/component/anything>, so <dir/component> is a directory */
2293       l = ptr - (char *)k.data;
2294       if(what & trackdb_directories)
2295         if(!(last_dir
2296              && l == last_dir_len
2297              && !memcmp(last_dir, k.data, l))) {
2298           last_dir = xstrndup(k.data, last_dir_len = l);
2299           if(track_matches(dl, k.data, l, re))
2300             vector_append(v, last_dir);
2301         }
2302     } else {
2303       /* found a plain file */
2304       if((what & trackdb_files)) {
2305         track = xstrndup(k.data, k.size);
2306         if((err = trackdb_getdata(trackdb_prefsdb,
2307                                   track, &p, tid)) == DB_LOCK_DEADLOCK)
2308           goto deadlocked;
2309         /* There's an awkward question here...
2310          *
2311          * If a track shares a directory with its alias then we could
2312          * do one of three things:
2313          * - report both.  Looks ridiculuous in most UIs.
2314          * - report just the alias.  Remarkably inconvenient to write
2315          *   UI code for!
2316          * - report just the real name.  Ugly if the UI doesn't prettify
2317          *   names via the name parts.
2318          */
2319 #if 1
2320         /* If this file is an alias for a track in the same directory then we
2321          * skip it */
2322         struct kvp *t = kvp_urldecode(d.data, d.size);
2323         const char *alias_target = kvp_get(t, "_alias_for");
2324         if(!(alias_target
2325              && !strcmp(d_dirname(alias_target),
2326                         d_dirname(track))))
2327           if(track_matches(dl, k.data, k.size, re))
2328             vector_append(v, track);
2329 #else
2330         /* if this file has an alias in the same directory then we skip it */
2331            char *alias;
2332         if((err = compute_alias(&alias, track, p, tid)))
2333           goto deadlocked;
2334         if(!(alias && !strcmp(d_dirname(alias), d_dirname(track))))
2335           if(track_matches(dl, k.data, k.size, re))
2336             vector_append(v, track);
2337 #endif
2338       }
2339     }
2340     err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2341   }
2342   switch(err) {
2343   case 0:
2344     break;
2345   case DB_NOTFOUND:
2346     err = 0;
2347     break;
2348   case DB_LOCK_DEADLOCK:
2349     disorder_error(0, "error querying database: %s", db_strerror(err));
2350     break;
2351   default:
2352     disorder_fatal(0, "error querying database: %s", db_strerror(err));
2353   }
2354 deadlocked:
2355   if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2356   return err;
2357 }
2358
2359 /** @brief Get the directories or files below @p dir
2360  * @param dir Directory to list
2361  * @param np Where to put number of results (or NULL)
2362  * @param what Bitmap of objects to return
2363  * @param re Regexp to filter matches (or NULL to accept all)
2364  * @return List of tracks
2365  */
2366 char **trackdb_list(const char *dir, int *np, enum trackdb_listable what,
2367                     const pcre *re) {
2368   DB_TXN *tid;
2369   int n;
2370   struct vector v;
2371
2372   vector_init(&v);
2373   for(;;) {
2374     tid = trackdb_begin_transaction();
2375     v.nvec = 0;
2376     if(dir) {
2377       if(do_list(&v, dir, what, re, tid))
2378         goto fail;
2379     } else {
2380       for(n = 0; n < config->collection.n; ++n)
2381         if(do_list(&v, config->collection.s[n].root, what, re, tid))
2382           goto fail;
2383     }
2384     break;
2385 fail:
2386     trackdb_abort_transaction(tid);
2387   }
2388   trackdb_commit_transaction(tid);
2389   vector_terminate(&v);
2390   if(np)
2391     *np = v.nvec;
2392   return v.vec;
2393 }
2394
2395 /** @brief Detect a tag element in a search string
2396  * @param s Element of search string
2397  * @return Pointer to tag name (in @p s) if this is a tag: search, else NULL
2398  *
2399  * Tag searches take the form "tag:TAG".
2400  */
2401 static const char *checktag(const char *s) {
2402   if(!strncmp(s, "tag:", 4))
2403     return s + 4;
2404   else
2405     return 0;
2406 }
2407
2408 /* return a list of tracks containing all of the words given.  If you
2409  * ask for only stopwords you get no tracks. */
2410 char **trackdb_search(char **wordlist, int nwordlist, int *ntracks) {
2411   const char **w, *best = 0, *tag;
2412   char **twords, **tags;
2413   char *istag;
2414   int i, j, n, err, what;
2415   DBC *cursor = 0;
2416   DBT k, d;
2417   struct vector u, v;
2418   DB_TXN *tid;
2419   struct kvp *p;
2420   int ntags = 0;
2421   DB *db;
2422   const char *dbname;
2423
2424   *ntracks = 0;                         /* for early returns */
2425   /* normalize all the words */
2426   w = xmalloc(nwordlist * sizeof (char *));
2427   istag = xmalloc_noptr(nwordlist);
2428   for(n = 0; n < nwordlist; ++n) {
2429     uint32_t *w32;
2430     size_t nw32;
2431
2432     w[n] = utf8_casefold_compat(wordlist[n], strlen(wordlist[n]), 0);
2433     if(checktag(w[n])) {
2434       ++ntags;         /* count up tags */
2435       /* Normalize the tag */
2436       w[n] = normalize_tag(w[n] + 4, strlen(w[n] + 4));
2437       istag[n] = 1;
2438     } else {
2439       /* Normalize the search term by removing combining characters */
2440       if(!(w32 = utf8_to_utf32(w[n], strlen(w[n]), &nw32)))
2441         return 0;
2442       nw32 = remove_combining_chars(w32, nw32);
2443       if(!(w[n] = utf32_to_utf8(w32, nw32, 0)))
2444         return 0;
2445       istag[n] = 0;
2446     }
2447   }
2448   /* find the longest non-stopword */
2449   for(n = 0; n < nwordlist; ++n)
2450     if(!istag[n] && !stopword(w[n]))
2451       if(!best || strlen(w[n]) > strlen(best))
2452         best = w[n];
2453   /* TODO: we should at least in principal be able to identify the word or tag
2454    * with the least matches in log time, and choose that as our primary search
2455    * term. */
2456   if(ntags && !best) {
2457     /* Only tags are listed.  We limit to the first and narrow down with the
2458      * rest. */
2459     best = istag[0] ? w[0] : 0;
2460     db = trackdb_tagsdb;
2461     dbname = "tags";
2462   } else if(best) {
2463     /* We can limit to some word. */
2464     db = trackdb_searchdb;
2465     dbname = "search";
2466   } else {
2467     /* Only stopwords */
2468     return 0;
2469   }
2470   vector_init(&u);
2471   vector_init(&v);
2472   for(;;) {
2473     tid = trackdb_begin_transaction();
2474     /* find all the tracks that have that word */
2475     make_key(&k, best);
2476     prepare_data(&d);
2477     what = DB_SET;
2478     v.nvec = 0;
2479     cursor = trackdb_opencursor(db, tid);
2480     while(!(err = cursor->c_get(cursor, &k, &d, what))) {
2481       vector_append(&v, xstrndup(d.data, d.size));
2482       what = DB_NEXT_DUP;
2483     }
2484     switch(err) {
2485     case DB_NOTFOUND:
2486       err = 0;
2487       break;
2488     case DB_LOCK_DEADLOCK:
2489       disorder_error(0, "error querying %s database: %s",
2490                      dbname, db_strerror(err));
2491       break;
2492     default:
2493       disorder_fatal(0, "error querying %s database: %s",
2494                      dbname, db_strerror(err));
2495     }
2496     if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2497     cursor = 0;
2498     if(err)
2499       goto fail;
2500     cursor = 0;
2501     /* do a naive search over that (hopefuly fairly small) list of tracks */
2502     u.nvec = 0;
2503     for(n = 0; n < v.nvec; ++n) {
2504       if((err = gettrackdata(v.vec[n], 0, &p, 0, 0, tid) == DB_LOCK_DEADLOCK))
2505         goto fail;
2506       else if(err) {
2507         disorder_error(0, "track %s unexpected error: %s",
2508                        v.vec[n], db_strerror(err));
2509         continue;
2510       }
2511       twords = track_to_words(v.vec[n], p);
2512       tags = parsetags(kvp_get(p, "tags"));
2513       for(i = 0; i < nwordlist; ++i) {
2514         if(istag[i]) {
2515           tag = w[i];
2516           /* Track must have this tag */
2517           for(j = 0; tags[j]; ++j)
2518             if(!strcmp(tag, tags[j])) break; /* tag found */
2519           if(!tags[j]) break;           /* tag not found */
2520         } else {
2521           /* Track must contain this word */
2522           for(j = 0; twords[j]; ++j)
2523             if(!strcmp(w[i], twords[j])) break; /* word found */
2524           if(!twords[j]) break;         /* word not found */
2525         }
2526       }
2527       if(i >= nwordlist)                /* all words found */
2528         vector_append(&u, v.vec[n]);
2529     }
2530     break;
2531   fail:
2532     trackdb_closecursor(cursor);
2533     cursor = 0;
2534     trackdb_abort_transaction(tid);
2535     disorder_info("retrying search");
2536   }
2537   trackdb_commit_transaction(tid);
2538   vector_terminate(&u);
2539   if(ntracks)
2540     *ntracks = u.nvec;
2541   return u.vec;
2542 }
2543
2544 /* trackdb_scan **************************************************************/
2545
2546 /** @brief Visit every track
2547  * @param root Root to scan or NULL for all
2548  * @param callback Callback for each track
2549  * @param u Passed to @p callback
2550  * @param tid Owning transaction
2551  * @return 0, DB_LOCK_DEADLOCK or EINTR
2552  *
2553  * Visits every track and calls @p callback.  @p callback will get the track
2554  * data and preferences and should return 0 to continue scanning or EINTR to
2555  * stop.
2556  */
2557 int trackdb_scan(const char *root,
2558                  int (*callback)(const char *track,
2559                                  struct kvp *data,
2560                                  struct kvp *prefs,
2561                                  void *u,
2562                                  DB_TXN *tid),
2563                  void *u,
2564                  DB_TXN *tid) {
2565   DBC *cursor;
2566   DBT k, d, pd;
2567   const size_t root_len = root ? strlen(root) : 0;
2568   int err, cberr;
2569   struct kvp *data, *prefs;
2570   const char *track;
2571
2572   cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2573   if(root)
2574     err = cursor->c_get(cursor, make_key(&k, root), prepare_data(&d),
2575                         DB_SET_RANGE);
2576   else {
2577     memset(&k, 0, sizeof k);
2578     err = cursor->c_get(cursor, &k, prepare_data(&d),
2579                         DB_FIRST);
2580   }
2581   while(!err) {
2582     if(!root
2583        || (k.size > root_len
2584            && !strncmp(k.data, root, root_len)
2585            && ((char *)k.data)[root_len] == '/')) {
2586       data = kvp_urldecode(d.data, d.size);
2587       if(kvp_get(data, "_path")) {
2588         track = xstrndup(k.data, k.size);
2589         /* TODO: trackdb_prefsdb is currently a DB_HASH.  This means we have to
2590          * do a lookup for every single track.  In fact this is quite quick:
2591          * with around 10,000 tracks a complete scan is around 0.3s on my
2592          * 2.2GHz Athlon.  However, if it were a DB_BTREE, we could do the same
2593          * linear walk as we already do over trackdb_tracksdb, and probably get
2594          * even higher performance.  That would require upgrade logic to
2595          * translate old databases though.
2596          */
2597         switch(err = trackdb_prefsdb->get(trackdb_prefsdb, tid, &k,
2598                                           prepare_data(&pd), 0)) {
2599         case 0:
2600           prefs = kvp_urldecode(pd.data, pd.size);
2601           break;
2602         case DB_NOTFOUND:
2603           prefs = 0;
2604           break;
2605         case DB_LOCK_DEADLOCK:
2606           disorder_error(0, "getting prefs: %s", db_strerror(err));
2607           trackdb_closecursor(cursor);
2608           return err;
2609         default:
2610           disorder_fatal(0, "getting prefs: %s", db_strerror(err));
2611         }
2612         /* Advance to the next track before the callback so that the callback
2613          * may safely delete the track */
2614         err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2615         if((cberr = callback(track, data, prefs, u, tid))) {
2616           err = cberr;
2617           break;
2618         }
2619       } else
2620         err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2621     } else
2622       break;
2623   }
2624   trackdb_closecursor(cursor);
2625   switch(err) {
2626   case EINTR:
2627     return err;
2628   case 0:
2629   case DB_NOTFOUND:
2630     return 0;
2631   case DB_LOCK_DEADLOCK:
2632     disorder_error(0, "c->c_get: %s", db_strerror(err));
2633     return err;
2634   default:
2635     disorder_fatal(0, "c->c_get: %s", db_strerror(err));
2636   }
2637 }
2638
2639 /* trackdb_rescan ************************************************************/
2640
2641 /** @brief Node in the list of rescan-complete callbacks */
2642 struct rescanned_node {
2643   struct rescanned_node *next;
2644   void (*rescanned)(void *ru);
2645   void *ru;
2646 };
2647
2648 /** @brief List of rescan-complete callbacks */
2649 static struct rescanned_node *rescanned_list;
2650
2651 /** @brief Add a rescan completion callback */
2652 void trackdb_add_rescanned(void (*rescanned)(void *ru),
2653                            void *ru) {
2654   if(rescanned) {
2655     struct rescanned_node *n = xmalloc(sizeof *n);
2656     n->next = rescanned_list;
2657     n->rescanned = rescanned;
2658     n->ru = ru;
2659     rescanned_list = n;
2660   }
2661 }
2662
2663 /* called when the rescanner terminates */
2664 static int reap_rescan(ev_source attribute((unused)) *ev,
2665                        pid_t pid,
2666                        int status,
2667                        const struct rusage attribute((unused)) *rusage,
2668                        void attribute((unused)) *u) {
2669   if(pid == rescan_pid) rescan_pid = -1;
2670   if(status)
2671     disorder_error(0, RESCAN": %s", wstat(status));
2672   else
2673     D((RESCAN" terminated: %s", wstat(status)));
2674   /* Our cache of file lookups is out of date now */
2675   cache_clean(&cache_files_type);
2676   eventlog("rescanned", (char *)0);
2677   /* Call rescanned callbacks */
2678   while(rescanned_list) {
2679     void (*rescanned)(void *u_) = rescanned_list->rescanned;
2680     void *ru = rescanned_list->ru;
2681
2682     rescanned_list = rescanned_list->next;
2683     rescanned(ru);
2684   }
2685   return 0;
2686 }
2687
2688 /** @brief Initiate a rescan
2689  * @param ev Event loop or 0 to block
2690  * @param recheck 1 to recheck lengths, 0 to suppress check
2691  * @param rescanned Called on completion (if not NULL)
2692  * @param ru Passed to @p rescanned
2693  */
2694 void trackdb_rescan(ev_source *ev, int recheck,
2695                     void (*rescanned)(void *ru),
2696                     void *ru) {
2697   int w;
2698
2699   if(rescan_pid != -1) {
2700     trackdb_add_rescanned(rescanned, ru);
2701     disorder_error(0, "rescan already underway");
2702     return;
2703   }
2704   rescan_pid = subprogram(ev, -1, RESCAN,
2705                           recheck ? "--check" : "--no-check",
2706                           (char *)0);
2707   trackdb_add_rescanned(rescanned, ru);
2708   if(ev) {
2709     ev_child(ev, rescan_pid, 0, reap_rescan, 0);
2710     D(("started rescanner"));
2711   } else {
2712     /* This is the first rescan, we block until it is complete */
2713     while(waitpid(rescan_pid, &w, 0) < 0 && errno == EINTR)
2714       ;
2715     reap_rescan(0, rescan_pid, w, 0, 0);
2716   }
2717 }
2718
2719 /** @brief Cancel a rescan
2720  * @return Nonzero if a rescan was cancelled
2721  */
2722 int trackdb_rescan_cancel(void) {
2723   if(rescan_pid == -1) return 0;
2724   if(kill(rescan_pid, SIGTERM) < 0)
2725     disorder_fatal(errno, "error killing rescanner");
2726   rescan_pid = -1;
2727   return 1;
2728 }
2729
2730 /** @brief Return true if a rescan is underway */
2731 int trackdb_rescan_underway(void) {
2732   return rescan_pid != -1;
2733 }
2734
2735 /* global prefs **************************************************************/
2736
2737 /** @brief Set a global preference
2738  * @param name Global preference name
2739  * @param value New value
2740  * @param who Who is setting it
2741  * @return 0 on success, -1 on error
2742  */
2743 int trackdb_set_global(const char *name,
2744                         const char *value,
2745                         const char *who) {
2746   DB_TXN *tid;
2747   int state, err;
2748
2749   for(;;) {
2750     tid = trackdb_begin_transaction();
2751     err = trackdb_set_global_tid(name, value, tid);
2752     if(err != DB_LOCK_DEADLOCK)
2753       break;
2754     trackdb_abort_transaction(tid);
2755   }
2756   trackdb_commit_transaction(tid);
2757   /* log important state changes */
2758   if(!strcmp(name, "playing")) {
2759     state = !value || !strcmp(value, "yes");
2760     disorder_info("playing %s by %s",
2761                   state ? "enabled" : "disabled",
2762                   who ? who : "-");
2763     eventlog("state", state ? "enable_play" : "disable_play", (char *)0);
2764   }
2765   if(!strcmp(name, "random-play")) {
2766     state = !value || !strcmp(value, "yes");
2767     disorder_info("random play %s by %s",
2768                   state ? "enabled" : "disabled",
2769                   who ? who : "-");
2770     eventlog("state", state ? "enable_random" : "disable_random", (char *)0);
2771   }
2772   eventlog("global_pref", name, value, (char *)0);
2773   return err == 0 ? 0 : -1;
2774 }
2775
2776 /** @brief Set a global preference
2777  * @param name Global preference name
2778  * @param value New value
2779  * @param tid Owning transaction
2780  */
2781 int trackdb_set_global_tid(const char *name,
2782                            const char *value,
2783                            DB_TXN *tid) {
2784   DBT k, d;
2785   int err;
2786
2787   memset(&k, 0, sizeof k);
2788   memset(&d, 0, sizeof d);
2789   k.data = (void *)name;
2790   k.size = strlen(name);
2791   if(value) {
2792     d.data = (void *)value;
2793     d.size = strlen(value);
2794   }
2795   if(value)
2796     err = trackdb_globaldb->put(trackdb_globaldb, tid, &k, &d, 0);
2797   else
2798     err = trackdb_globaldb->del(trackdb_globaldb, tid, &k, 0);
2799   if(err == DB_LOCK_DEADLOCK || err == DB_NOTFOUND) return err;
2800   if(err)
2801     disorder_fatal(0, "error updating database: %s", db_strerror(err));
2802   return 0;
2803 }
2804
2805 /** @brief Get a global preference
2806  * @param name Global preference name
2807  * @return Value of global preference, or NULL if it's not set
2808  */
2809 const char *trackdb_get_global(const char *name) {
2810   DB_TXN *tid;
2811   const char *r;
2812
2813   for(;;) {
2814     tid = trackdb_begin_transaction();
2815     if(!trackdb_get_global_tid(name, tid, &r))
2816       break;
2817     trackdb_abort_transaction(tid);
2818   }
2819   trackdb_commit_transaction(tid);
2820   return r;
2821 }
2822
2823 /** @brief Get a global preference
2824  * @param name Global preference name
2825  * @param tid Owning transaction
2826  * @param rp Where to store value (will get NULL if preference not set)
2827  * @return 0 or DB_LOCK_DEADLOCK
2828  */
2829 int trackdb_get_global_tid(const char *name,
2830                            DB_TXN *tid,
2831                            const char **rp) {
2832   DBT k, d;
2833   int err;
2834
2835   memset(&k, 0, sizeof k);
2836   k.data = (void *)name;
2837   k.size = strlen(name);
2838   switch(err = trackdb_globaldb->get(trackdb_globaldb, tid, &k,
2839                                      prepare_data(&d), 0)) {
2840   case 0:
2841     *rp = xstrndup(d.data, d.size);
2842     return 0;
2843   case DB_NOTFOUND:
2844     *rp = 0;
2845     return 0;
2846   case DB_LOCK_DEADLOCK:
2847     return err;
2848   default:
2849     disorder_fatal(0, "error reading database: %s", db_strerror(err));
2850   }
2851 }
2852
2853 /** @brief Retrieve the most recently added tracks
2854  * @param ntracksp Where to put count, or 0
2855  * @param maxtracks Maximum number of tracks to retrieve
2856  * @return null-terminated array of track names
2857  *
2858  * The most recently added track is first in the array.
2859  */
2860 char **trackdb_new(int *ntracksp,
2861                    int maxtracks) {
2862   DB_TXN *tid;
2863   char **tracks;
2864
2865   for(;;) {
2866     tid = trackdb_begin_transaction();
2867     tracks = trackdb_new_tid(ntracksp, maxtracks, tid);
2868     if(tracks)
2869       break;
2870     trackdb_abort_transaction(tid);
2871   }
2872   trackdb_commit_transaction(tid);
2873   return tracks;
2874 }
2875
2876 /** @brief Retrieve the most recently added tracks
2877  * @param ntracksp Where to put count, or 0
2878  * @param maxtracks Maximum number of tracks to retrieve, or 0 for all
2879  * @param tid Transaction ID
2880  * @return null-terminated array of track names, or NULL on deadlock
2881  *
2882  * The most recently added track is first in the array.
2883  */
2884 static char **trackdb_new_tid(int *ntracksp,
2885                               int maxtracks,
2886                               DB_TXN *tid) {
2887   DBC *c;
2888   DBT k, d;
2889   int err = 0;
2890   struct vector tracks[1];
2891   hash *h = hash_new(1);
2892
2893   vector_init(tracks);
2894   c = trackdb_opencursor(trackdb_noticeddb, tid);
2895   while((maxtracks <= 0 || tracks->nvec < maxtracks)
2896         && !(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_PREV))) {
2897     char *const track = xstrndup(d.data, d.size);
2898     /* Don't add any track more than once */
2899     if(hash_add(h, track, "", HASH_INSERT))
2900       continue;
2901     /* See if the track still exists */
2902     err = trackdb_getdata(trackdb_tracksdb, track, NULL/*kp*/, tid);
2903     if(err == DB_NOTFOUND)
2904       continue;                         /* It doesn't, skip it */
2905     if(err == DB_LOCK_DEADLOCK)
2906       break;                            /* Doh */
2907     vector_append(tracks, track);
2908   }
2909   switch(err) {
2910   case 0:                               /* hit maxtracks */
2911   case DB_NOTFOUND:                     /* ran out of tracks */
2912     break;
2913   case DB_LOCK_DEADLOCK:
2914     trackdb_closecursor(c);
2915     return 0;
2916   default:
2917     disorder_fatal(0, "error reading noticed.db: %s", db_strerror(err));
2918   }
2919   if(trackdb_closecursor(c))
2920     return 0;                           /* deadlock */
2921   vector_terminate(tracks);
2922   if(ntracksp)
2923     *ntracksp = tracks->nvec;
2924   return tracks->vec;
2925 }
2926
2927 /** @brief Expire noticed.db
2928  * @param earliest Earliest timestamp to keep
2929  */
2930 void trackdb_expire_noticed(time_t earliest) {
2931   DB_TXN *tid;
2932
2933   for(;;) {
2934     tid = trackdb_begin_transaction();
2935     if(!trackdb_expire_noticed_tid(earliest, tid))
2936       break;
2937     trackdb_abort_transaction(tid);
2938   }
2939   trackdb_commit_transaction(tid);
2940 }
2941
2942 /** @brief Expire noticed.db
2943  * @param earliest Earliest timestamp to keep
2944  * @param tid Transaction ID
2945  * @return 0 or DB_LOCK_DEADLOCK
2946  */
2947 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid) {
2948   DBC *c;
2949   DBT k, d;
2950   int err = 0, ret;
2951   time_t when;
2952   uint32_t *kk;
2953   int count = 0;
2954
2955   c = trackdb_opencursor(trackdb_noticeddb, tid);
2956   while(!(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_NEXT))) {
2957     kk = k.data;
2958     when = (time_t)(((uint64_t)ntohl(kk[0]) << 32) + ntohl(kk[1]));
2959     if(when >= earliest)
2960       break;
2961     if((err = c->c_del(c, 0))) {
2962       if(err != DB_LOCK_DEADLOCK)
2963         disorder_fatal(0, "error deleting expired noticed.db entry: %s",
2964                        db_strerror(err));
2965       break;
2966     }
2967     ++count;
2968   }
2969   if(err == DB_NOTFOUND)
2970     err = 0;
2971   if(err && err != DB_LOCK_DEADLOCK)
2972     disorder_fatal(0, "error expiring noticed.db: %s", db_strerror(err));
2973   ret = err;
2974   if((err = trackdb_closecursor(c))) {
2975     if(err != DB_LOCK_DEADLOCK)
2976       disorder_fatal(0, "error closing cursor: %s", db_strerror(err));
2977     ret = err;
2978   }
2979   if(!ret && count)
2980     disorder_info("expired %d tracks from noticed.db", count);
2981   return ret;
2982 }
2983
2984 /* tidying up ****************************************************************/
2985
2986 /** @brief Do database garbage collection
2987  *
2988  * Called form periodic_database_gc().
2989  */
2990 void trackdb_gc(void) {
2991   int err;
2992   char **logfiles;
2993
2994   if((err = trackdb_env->txn_checkpoint(trackdb_env,
2995                                         config->checkpoint_kbyte,
2996                                         config->checkpoint_min,
2997                                         0)))
2998     disorder_fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err));
2999   if((err = trackdb_env->log_archive(trackdb_env, &logfiles, DB_ARCH_REMOVE)))
3000     disorder_fatal(0, "trackdb_env->log_archive: %s", db_strerror(err));
3001   /* This makes catastrophic recovery impossible.  However, the user can still
3002    * preserve the important data by using disorder-dump to snapshot their
3003    * prefs, and later to restore it.  This is likely to have much small
3004    * long-term storage requirements than record the db logfiles. */
3005 }
3006
3007 /* user database *************************************************************/
3008
3009 /** @brief Add a user
3010  * @param user Username
3011  * @param password Initial password or NULL
3012  * @param rights Initial rights
3013  * @param email Email address or NULL
3014  * @param confirmation Confirmation string to require
3015  * @param tid Owning transaction
3016  * @param flags DB flags e.g. DB_NOOVERWRITE
3017  * @return 0, DB_KEYEXIST or DB_LOCK_DEADLOCK
3018  */
3019 static int create_user(const char *user,
3020                        const char *password,
3021                        const char *rights,
3022                        const char *email,
3023                        const char *confirmation,
3024                        DB_TXN *tid,
3025                        uint32_t flags) {
3026   struct kvp *k = 0;
3027   char s[64];
3028
3029   /* sanity check user */
3030   if(!valid_username(user)) {
3031     disorder_error(0, "invalid username '%s'", user);
3032     return -1;
3033   }
3034   if(parse_rights(rights, 0, 1)) {
3035     disorder_error(0, "invalid rights string");
3036     return -1;
3037   }
3038   /* data for this user */
3039   if(password)
3040     kvp_set(&k, "password", password);
3041   kvp_set(&k, "rights", rights);
3042   if(email)
3043     kvp_set(&k, "email", email);
3044   if(confirmation)
3045     kvp_set(&k, "confirmation", confirmation);
3046   snprintf(s, sizeof s, "%jd", (intmax_t)xtime(0));
3047   kvp_set(&k, "created", s);
3048   return trackdb_putdata(trackdb_usersdb, user, k, tid, flags);
3049 }
3050
3051 /** @brief Create a root user in the user database if there is none */
3052 void trackdb_create_root(void) {
3053   int e;
3054   uint8_t pwbin[12];
3055   char *pw;
3056
3057   /* Choose a new root password */
3058   gcry_randomize(pwbin, sizeof pwbin, GCRY_STRONG_RANDOM);
3059   pw = mime_to_base64(pwbin, sizeof pwbin);
3060   /* Create the root user if it does not exist */
3061   WITH_TRANSACTION(create_user("root", pw, "all",
3062                                0/*email*/, 0/*confirmation*/,
3063                                tid, DB_NOOVERWRITE));
3064   if(e == 0)
3065     disorder_info("created root user");
3066 }
3067
3068 /** @brief Find a user's password from the database
3069  * @param user Username
3070  * @return Password or NULL
3071  *
3072  * Only works if running as a user that can read the database!
3073  *
3074  * If the user exists but has no password, "" is returned.
3075  */
3076 const char *trackdb_get_password(const char *user) {
3077   int e;
3078   struct kvp *k;
3079   const char *password;
3080
3081   WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3082   if(e)
3083     return 0;
3084   password = kvp_get(k, "password");
3085   return password ? password : "";
3086 }
3087
3088 /** @brief Add a new user
3089  * @param user Username
3090  * @param password Password or NULL
3091  * @param rights Initial rights
3092  * @param email Email address or NULL
3093  * @param confirmation Confirmation string or NULL
3094  * @return 0 on success, non-0 on error
3095  */
3096 int trackdb_adduser(const char *user,
3097                     const char *password,
3098                     const char *rights,
3099                     const char *email,
3100                     const char *confirmation) {
3101   int e;
3102
3103   WITH_TRANSACTION(create_user(user, password, rights, email, confirmation,
3104                                tid, DB_NOOVERWRITE));
3105   if(e) {
3106     disorder_error(0, "cannot create user '%s' because they already exist",
3107                    user);
3108     return -1;
3109   } else {
3110     if(email)
3111       disorder_info("created user '%s' with rights '%s' and email address '%s'",
3112                     user, rights, email);
3113     else
3114       disorder_info("created user '%s' with rights '%s'", user, rights);
3115     eventlog("user_add", user, (char *)0);
3116     return 0;
3117   }
3118 }
3119
3120 /** @brief Delete a user
3121  * @param user User to delete
3122  * @return 0 on success, non-0 if the user didn't exist anyway
3123  */
3124 int trackdb_deluser(const char *user) {
3125   int e;
3126
3127   WITH_TRANSACTION(trackdb_delkey(trackdb_usersdb, user, tid));
3128   if(e) {
3129     disorder_error(0, "cannot delete user '%s' because they do not exist",
3130                    user);
3131     return -1;
3132   }
3133   disorder_info("deleted user '%s'", user);
3134   eventlog("user_delete", user, (char *)0);
3135   return 0;
3136 }
3137
3138 /** @brief Get user information
3139  * @param user User to query
3140  * @return Linked list of user information or NULL if user does not exist
3141  *
3142  * Every user has at least a @c rights entry so NULL can be used to mean no
3143  * such user safely.
3144  */
3145 struct kvp *trackdb_getuserinfo(const char *user) {
3146   int e;
3147   struct kvp *k;
3148
3149   WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3150   if(e)
3151     return 0;
3152   else
3153     return k;
3154 }
3155
3156 /** @brief Edit user information
3157  * @param user User to edit
3158  * @param key Key to change
3159  * @param value Value to set, or NULL to remove
3160  * @param tid Transaction ID
3161  * @return 0, DB_LOCK_DEADLOCK or DB_NOTFOUND
3162  */
3163 static int trackdb_edituserinfo_tid(const char *user, const char *key,
3164                                     const char *value, DB_TXN *tid) {
3165   struct kvp *k;
3166   int e;
3167
3168   if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3169     return e;
3170   if(!kvp_set(&k, key, value))
3171     return 0;                           /* no change */
3172   return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3173 }
3174
3175 /** @brief Edit user information
3176  * @param user User to edit
3177  * @param key Key to change
3178  * @param value Value to set, or NULL to remove
3179  * @return 0 on success, non-0 on error
3180  */
3181 int trackdb_edituserinfo(const char *user,
3182                          const char *key, const char *value) {
3183   int e;
3184
3185   if(!strcmp(key, "rights")) {
3186     if(!value) {
3187       disorder_error(0, "cannot remove 'rights' key from user '%s'", user);
3188       return -1;
3189     }
3190     if(parse_rights(value, 0, 1)) {
3191       disorder_error(0, "invalid rights string");
3192       return -1;
3193     }
3194   } else if(!strcmp(key, "email")) {
3195     if(*value) {
3196       if(!email_valid(value)) {
3197         disorder_error(0, "invalid email address '%s' for user '%s'",
3198                        value, user);
3199         return -1;
3200       }
3201     } else
3202       value = 0;                        /* no email -> remove key */
3203   } else if(!strcmp(key, "created")) {
3204     disorder_error(0, "cannot change creation date for user '%s'", user);
3205     return -1;
3206   } else if(strcmp(key, "password")
3207             && !strcmp(key, "confirmation")) {
3208     disorder_error(0, "unknown user info key '%s' for user '%s'", key, user);
3209     return -1;
3210   }
3211   WITH_TRANSACTION(trackdb_edituserinfo_tid(user, key, value, tid));
3212   if(e) {
3213     disorder_error(0, "unknown user '%s'", user);
3214     return -1;
3215   } else {
3216     eventlog("user_edit", user, key, (char *)0);
3217     return 0;
3218   }
3219 }
3220
3221 /** @brief List all users
3222  * @return NULL-terminated list of users
3223  */
3224 char **trackdb_listusers(void) {
3225   int e;
3226   struct vector v[1];
3227
3228   vector_init(v);
3229   WITH_TRANSACTION(trackdb_listkeys(trackdb_usersdb, v, tid));
3230   return v->vec;
3231 }
3232
3233 /** @brief Confirm a user registration
3234  * @param user Username
3235  * @param confirmation Confirmation string
3236  * @param rightsp Where to put user rights
3237  * @param tid Transaction ID
3238  * @return 0 on success, non-0 on error
3239  */
3240 static int trackdb_confirm_tid(const char *user, const char *confirmation,
3241                                rights_type *rightsp,
3242                                DB_TXN *tid) {
3243   const char *stored_confirmation;
3244   struct kvp *k;
3245   int e;
3246   const char *rights;
3247   
3248   if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3249     return e;
3250   if(!(stored_confirmation = kvp_get(k, "confirmation"))) {
3251     disorder_error(0, "already confirmed user '%s'", user);
3252     /* DB claims -30,800 to -30,999 so -1 should be a safe bet */
3253     return -1;
3254   }
3255   if(!(rights = kvp_get(k, "rights"))) {
3256     disorder_error(0, "no rights for unconfirmed user '%s'", user);
3257     return -1;
3258   }
3259   if(parse_rights(rights, rightsp, 1))
3260     return -1;
3261   if(strcmp(confirmation, stored_confirmation)) {
3262     disorder_error(0, "wrong confirmation string for user '%s'", user);
3263     return -1;
3264   }
3265   /* 'sall good */
3266   kvp_set(&k, "confirmation", 0);
3267   return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3268 }
3269
3270 /** @brief Confirm a user registration
3271  * @param user Username
3272  * @param confirmation Confirmation string
3273  * @param rightsp Where to put user rights
3274  * @return 0 on success, non-0 on error
3275  */
3276 int trackdb_confirm(const char *user, const char *confirmation,
3277                     rights_type *rightsp) {
3278   int e;
3279
3280   WITH_TRANSACTION(trackdb_confirm_tid(user, confirmation, rightsp, tid));
3281   switch(e) {
3282   case 0:
3283     disorder_info("registration confirmed for user '%s'", user);
3284     eventlog("user_confirm", user, (char *)0);
3285     return 0;
3286   case DB_NOTFOUND:
3287     disorder_error(0, "confirmation for nonexistent user '%s'", user);
3288     return -1;
3289   default:                              /* already reported */
3290     return -1;
3291   }
3292 }
3293
3294 /*
3295 Local Variables:
3296 c-basic-offset:2
3297 comment-column:40
3298 fill-column:79
3299 indent-tabs-mode:nil
3300 End:
3301 */