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