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