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