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