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