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