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