2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
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.
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.
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
20 /** @file lib/trackdb.c
21 * @brief Track database
23 * This file is getting in desparate need of splitting up...
32 #include <sys/socket.h>
39 #include <sys/resource.h>
41 #include <arpa/inet.h>
54 #include "configuration.h"
59 #include "trackname.h"
60 #include "trackdb-int.h"
69 #define RESCAN "disorder-rescan"
70 #define DEADLOCK "disorder-deadlock"
72 static const char *getpart(const char *track,
77 static char **trackdb_new_tid(int *ntracksp,
80 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid);
81 static char *normalize_tag(const char *s, size_t ns);
83 const struct cache_type cache_files_type = { 86400 };
84 unsigned long cache_files_hits, cache_files_misses;
86 /** @brief Set by trackdb_open() */
87 int trackdb_existing_database;
89 /* setup and teardown ********************************************************/
91 static const char *home; /* home had better not change */
92 DB_ENV *trackdb_env; /* db environment */
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
101 /** @brief The preferences database
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
110 /** @brief The search database
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
116 * - Only tracks fond in @ref trackdb_tracksdb are represented here
117 * - This database can be reconstructed, it contains no user data
119 DB *trackdb_searchdb;
121 /** @brief The tags database
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
130 DB *trackdb_tagsdb; /* the tags database */
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
137 DB *trackdb_globaldb; /* global preferences */
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)
146 DB *trackdb_noticeddb; /* when track noticed */
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
155 static pid_t db_deadlock_pid = -1; /* deadlock manager PID */
156 static pid_t rescan_pid = -1; /* rescanner PID */
157 static int initialized, opened; /* state */
159 /* tracks matched by required_tags */
160 static char **reqtracks;
161 static size_t nreqtracks;
163 /* comparison function for keys */
164 static 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);
169 /** @brief Open database environment
170 * @param flags Flags word
172 * Flags should be one of:
173 * - @ref TRACKDB_NO_RECOVER
174 * - @ref TRACKDB_NORMAL_RECOVER
175 * - @ref TRACKDB_FATAL_RECOVER
176 * - @ref TRACKDB_MAY_CREATE
178 void trackdb_init(int flags) {
180 const int recover = flags & TRACKDB_RECOVER_MASK;
181 static int recover_type[] = { 0, DB_RECOVER, DB_RECOVER_FATAL };
184 assert(initialized == 0);
187 if(strcmp(home, config->home))
188 fatal(0, "cannot change db home without server restart");
192 if(flags & TRACKDB_MAY_CREATE) {
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.
203 * The socket, not being a regular file, is excepted.
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)) {
212 if(chmod(p, st.st_mode & 07700) < 0)
213 fatal(errno, "cannot chmod %s", p);
220 /* create environment */
221 if((err = db_env_create(&trackdb_env, 0))) fatal(0, "db_env_create: %s",
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,
236 |recover_type[recover],
238 fatal(0, "trackdb_env->open %s: %s", config->home, db_strerror(err));
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"));
247 /* called when deadlock manager terminates */
248 static int reap_db_deadlock(ev_source attribute((unused)) *ev,
249 pid_t attribute((unused)) pid,
251 const struct rusage attribute((unused)) *rusage,
252 void attribute((unused)) *u) {
253 db_deadlock_pid = -1;
255 fatal(0, "deadlock manager unexpectedly terminated: %s",
258 D(("deadlock manager terminated: %s", wstat(status)));
262 static pid_t subprogram(ev_source *ev, const char *prog,
266 /* If we're in the background then trap subprocess stdout/stderr */
267 if(!(pid = xfork())) {
270 ev_signal_atfork(ev);
271 signal(SIGPIPE, SIG_DFL);
276 /* ensure we don't leak privilege anywhere */
277 if(setuid(geteuid()) < 0)
278 fatal(errno, "error calling setuid");
279 /* If we were negatively niced, undo it. We don't bother checking for
280 * error, it's not that important. */
281 setpriority(PRIO_PROCESS, 0, 0);
282 execlp(prog, prog, "--config", configfile,
283 debugging ? "--debug" : "--no-debug",
284 log_default == &log_syslog ? "--syslog" : "--no-syslog",
286 fatal(errno, "error invoking %s", prog);
291 /* start deadlock manager */
292 void trackdb_master(ev_source *ev) {
293 assert(db_deadlock_pid == -1);
294 db_deadlock_pid = subprogram(ev, DEADLOCK, -1);
295 ev_child(ev, db_deadlock_pid, 0, reap_db_deadlock, 0);
296 D(("started deadlock manager"));
299 /* close environment */
300 void trackdb_deinit(void) {
304 assert(initialized == 1);
307 /* close the environment */
308 if((err = trackdb_env->close(trackdb_env, 0)))
309 fatal(0, "trackdb_env->close: %s", db_strerror(err));
311 if(rescan_pid != -1 && kill(rescan_pid, SIGTERM) < 0)
312 fatal(errno, "error killing rescanner");
314 /* terminate the deadlock manager */
315 if(db_deadlock_pid != -1 && kill(db_deadlock_pid, SIGTERM) < 0)
316 fatal(errno, "error killing deadlock manager");
317 db_deadlock_pid = -1;
319 D(("deinitialized database environment"));
322 /* open a specific database */
323 static DB *open_db(const char *path,
331 D(("open %s", path));
332 path = config_get_file(path);
333 if((err = db_create(&db, trackdb_env, 0)))
334 fatal(0, "db_create %s: %s", path, db_strerror(err));
336 if((err = db->set_flags(db, dbflags)))
337 fatal(0, "db->set_flags %s: %s", path, db_strerror(err));
338 if(dbtype == DB_BTREE)
339 if((err = db->set_bt_compare(db, compare)))
340 fatal(0, "db->set_bt_compare %s: %s", path, db_strerror(err));
341 if((err = db->open(db, 0, path, 0, dbtype,
342 openflags | DB_AUTO_COMMIT, mode))) {
343 if((openflags & DB_CREATE) || errno != ENOENT)
344 fatal(0, "db->open %s: %s", path, db_strerror(err));
351 /** @brief Open track databases
352 * @param flags Flags flags word
354 * @p flags should have one of:
355 * - @p TRACKDB_NO_UPGRADE, if no upgrade should be attempted
356 * - @p TRACKDB_CAN_UPGRADE, if an upgrade may be attempted
357 * - @p TRACKDB_OPEN_FOR_UPGRADE, if this is disorder-dbupgrade
359 * - @p TRACKDB_READ_ONLY, read only access
361 void trackdb_open(int flags) {
364 uint32_t dbflags = flags & TRACKDB_READ_ONLY ? DB_RDONLY : DB_CREATE;
369 /* check the database version first */
370 trackdb_globaldb = open_db("global.db", 0, DB_HASH, DB_RDONLY, 0666);
371 if(trackdb_globaldb) {
372 /* This is an existing database */
376 s = trackdb_get_global("_dbversion");
377 /* Close the database again, we'll open it property below */
378 if((err = trackdb_globaldb->close(trackdb_globaldb, 0)))
379 fatal(0, "error closing global.db: %s", db_strerror(err));
380 trackdb_globaldb = 0;
381 /* Convert version string to an integer */
382 oldversion = s ? atol(s) : 1;
383 if(oldversion > config->dbversion) {
384 /* Database is from the future; we never allow this. */
385 fatal(0, "this version of DisOrder is too old for database version %ld",
388 if(oldversion < config->dbversion) {
389 /* Database version is out of date */
390 switch(flags & TRACKDB_UPGRADE_MASK) {
391 case TRACKDB_NO_UPGRADE:
392 /* This database needs upgrading but this is not permitted */
393 fatal(0, "database needs upgrading from %ld to %ld",
394 oldversion, config->dbversion);
395 case TRACKDB_CAN_UPGRADE:
396 /* This database needs upgrading */
397 info("invoking disorder-dbupgrade to upgrade from %ld to %ld",
398 oldversion, config->dbversion);
399 pid = subprogram(0, "disorder-dbupgrade", -1);
400 while(waitpid(pid, &err, 0) == -1 && errno == EINTR)
403 fatal(0, "disorder-dbupgrade %s", wstat(err));
404 info("disorder-dbupgrade succeeded");
406 case TRACKDB_OPEN_FOR_UPGRADE:
412 if(oldversion == config->dbversion && (flags & TRACKDB_OPEN_FOR_UPGRADE)) {
413 /* This doesn't make any sense */
414 fatal(0, "database is already at current version");
416 trackdb_existing_database = 1;
418 if(flags & TRACKDB_OPEN_FOR_UPGRADE) {
419 /* Cannot upgrade a new database */
420 fatal(0, "cannot upgrade a database that does not exist");
422 /* This is a brand new database */
423 trackdb_existing_database = 0;
425 /* open the databases */
426 trackdb_tracksdb = open_db("tracks.db",
427 DB_RECNUM, DB_BTREE, dbflags, 0666);
428 trackdb_searchdb = open_db("search.db",
429 DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
430 trackdb_tagsdb = open_db("tags.db",
431 DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
432 trackdb_prefsdb = open_db("prefs.db", 0, DB_HASH, dbflags, 0666);
433 trackdb_globaldb = open_db("global.db", 0, DB_HASH, dbflags, 0666);
434 trackdb_noticeddb = open_db("noticed.db",
435 DB_DUPSORT, DB_BTREE, dbflags, 0666);
436 trackdb_usersdb = open_db("users.db",
437 0, DB_HASH, dbflags, 0600);
438 if(!trackdb_existing_database) {
439 /* Stash the database version */
442 assert(!(flags & TRACKDB_OPEN_FOR_UPGRADE));
443 snprintf(buf, sizeof buf, "%ld", config->dbversion);
444 trackdb_set_global("_dbversion", buf, 0);
446 D(("opened databases"));
449 /* close track databases */
450 void trackdb_close(void) {
456 if((err = trackdb_tracksdb->close(trackdb_tracksdb, 0)))
457 fatal(0, "error closing tracks.db: %s", db_strerror(err));
458 if((err = trackdb_searchdb->close(trackdb_searchdb, 0)))
459 fatal(0, "error closing search.db: %s", db_strerror(err));
460 if((err = trackdb_tagsdb->close(trackdb_tagsdb, 0)))
461 fatal(0, "error closing tags.db: %s", db_strerror(err));
462 if((err = trackdb_prefsdb->close(trackdb_prefsdb, 0)))
463 fatal(0, "error closing prefs.db: %s", db_strerror(err));
464 if((err = trackdb_globaldb->close(trackdb_globaldb, 0)))
465 fatal(0, "error closing global.db: %s", db_strerror(err));
466 if((err = trackdb_noticeddb->close(trackdb_noticeddb, 0)))
467 fatal(0, "error closing noticed.db: %s", db_strerror(err));
468 if((err = trackdb_usersdb->close(trackdb_usersdb, 0)))
469 fatal(0, "error closing users.db: %s", db_strerror(err));
470 trackdb_tracksdb = trackdb_searchdb = trackdb_prefsdb = 0;
471 trackdb_tagsdb = trackdb_globaldb = 0;
472 D(("closed databases"));
475 /* generic db routines *******************************************************/
477 /* fetch and decode a database entry. Returns 0, DB_NOTFOUND or
478 * DB_LOCK_DEADLOCK. */
479 int trackdb_getdata(DB *db,
486 switch(err = db->get(db, tid, make_key(&key, track),
487 prepare_data(&data), 0)) {
489 *kp = kvp_urldecode(data.data, data.size);
494 case DB_LOCK_DEADLOCK:
495 error(0, "error querying database: %s", db_strerror(err));
498 fatal(0, "error querying database: %s", db_strerror(err));
502 /* encode and store a database entry. Returns 0, DB_KEYEXIST or
503 * DB_LOCK_DEADLOCK. */
504 int trackdb_putdata(DB *db,
512 switch(err = db->put(db, tid, make_key(&key, track),
513 encode_data(&data, k), flags)) {
517 case DB_LOCK_DEADLOCK:
518 error(0, "error updating database: %s", db_strerror(err));
521 fatal(0, "error updating database: %s", db_strerror(err));
525 /** @brief Delete a database entry
527 * @param track Key to delete
528 * @param tid Transaction ID
529 * @return 0, DB_NOTFOUND or DB_LOCK_DEADLOCK
531 int trackdb_delkey(DB *db,
537 switch(err = db->del(db, tid, make_key(&key, track), 0)) {
541 case DB_LOCK_DEADLOCK:
542 error(0, "error updating database: %s", db_strerror(err));
545 fatal(0, "error updating database: %s", db_strerror(err));
549 /* open a database cursor */
550 DBC *trackdb_opencursor(DB *db, DB_TXN *tid) {
554 switch(err = db->cursor(db, tid, &c, 0)) {
556 default: fatal(0, "error creating cursor: %s", db_strerror(err));
561 /* close a database cursor; returns 0 or DB_LOCK_DEADLOCK */
562 int trackdb_closecursor(DBC *c) {
566 switch(err = c->c_close(c)) {
569 case DB_LOCK_DEADLOCK:
570 error(0, "error closing cursor: %s", db_strerror(err));
573 fatal(0, "error closing cursor: %s", db_strerror(err));
577 /* delete a (key,data) pair. Returns 0, DB_NOTFOUND or DB_LOCK_DEADLOCK. */
578 int trackdb_delkeydata(DB *db,
586 c = trackdb_opencursor(db, tid);
587 switch(err = c->c_get(c, make_key(&key, word),
588 make_key(&data, track), DB_GET_BOTH)) {
590 switch(err = c->c_del(c, 0)) {
596 case DB_LOCK_DEADLOCK:
597 error(0, "error updating database: %s", db_strerror(err));
600 fatal(0, "c->c_del: %s", db_strerror(err));
605 case DB_LOCK_DEADLOCK:
606 error(0, "error updating database: %s", db_strerror(err));
609 fatal(0, "c->c_get: %s", db_strerror(err));
611 if(trackdb_closecursor(c)) err = DB_LOCK_DEADLOCK;
615 /* start a transaction */
616 DB_TXN *trackdb_begin_transaction(void) {
620 if((err = trackdb_env->txn_begin(trackdb_env, 0, &tid, 0)))
621 fatal(0, "trackdb_env->txn_begin: %s", db_strerror(err));
625 /* abort transaction */
626 void trackdb_abort_transaction(DB_TXN *tid) {
630 if((err = tid->abort(tid)))
631 fatal(0, "tid->abort: %s", db_strerror(err));
634 /* commit transaction */
635 void trackdb_commit_transaction(DB_TXN *tid) {
638 if((err = tid->commit(tid, 0)))
639 fatal(0, "tid->commit: %s", db_strerror(err));
642 /* search/tags shared code ***************************************************/
644 /* comparison function used by dedupe() */
645 static int wordcmp(const void *a, const void *b) {
646 return strcmp(*(const char **)a, *(const char **)b);
649 /* sort and de-dupe VEC */
650 static char **dedupe(char **vec, int nvec) {
653 qsort(vec, nvec, sizeof (char *), wordcmp);
657 for(n = 1; n < nvec; ++n)
658 if(strcmp(vec[n], vec[m - 1]))
665 /* update a key/track database. Returns 0 or DB_DEADLOCK. */
666 static int register_word(DB *db, const char *what,
667 const char *track, const char *word,
672 switch(err = db->put(db, tid, make_key(&key, word),
673 make_key(&data, track), DB_NODUPDATA)) {
677 case DB_LOCK_DEADLOCK:
678 error(0, "error updating %s.db: %s", what, db_strerror(err));
681 fatal(0, "error updating %s.db: %s", what, db_strerror(err));
685 /* search primitives *********************************************************/
687 /* return true iff NAME is a trackname_display_ pref */
688 static int is_display_pref(const char *name) {
689 static const char prefix[] = "trackname_display_";
690 return !strncmp(name, prefix, (sizeof prefix) - 1);
693 /** @brief Word_Break property tailor that treats underscores as spaces */
694 static int tailor_underscore_Word_Break_Other(uint32_t c) {
698 case 0x005F: /* LOW LINE (SPACING UNDERSCORE) */
699 return unicode_Word_Break_Other;
703 /** @brief Remove all combining characters in-place
704 * @param s Pointer to start of string
705 * @param ns Length of string
706 * @return New, possiblby reduced, length
708 static size_t remove_combining_chars(uint32_t *s, size_t ns) {
709 uint32_t *start = s, *t = s, *end = s + ns;
712 const uint32_t c = *s++;
713 if(!utf32_combining_class(c))
719 /** @brief Normalize and split a string using a given tailoring */
720 static void word_split(struct vector *v,
722 unicode_property_tailor *pt) {
724 uint32_t *t32, **w32;
726 /* Convert to UTF-32 */
727 if(!(t32 = utf8_to_utf32(s, strlen(s), &nt32)))
729 /* Erase case distinctions */
730 if(!(t32 = utf32_casefold_compat(t32, nt32, &nt32)))
732 /* Drop combining characters */
733 nt32 = remove_combining_chars(t32, nt32);
734 /* Split into words, treating _ as a space */
735 w32 = utf32_word_split(t32, nt32, &nw, pt);
736 /* Convert words back to UTF-8 and append to result */
737 for(i = 0; i < nw; ++i)
738 vector_append(v, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
741 /** @brief Normalize a tag
743 * @param ns Length of tag
744 * @return Normalized string or NULL on error
746 * The return value will be:
748 * - have no leading or trailing space
749 * - have no combining characters
750 * - all spacing between words will be a single U+0020 SPACE
752 static char *normalize_tag(const char *s, size_t ns) {
753 uint32_t *s32, **w32;
754 size_t ns32, nw32, i;
757 if(!(s32 = utf8_to_utf32(s, ns, &ns32)))
759 if(!(s32 = utf32_casefold_compat(s32, ns32, &ns32))) /* ->NFKD */
761 ns32 = remove_combining_chars(s32, ns32);
762 /* Split into words, no Word_Break tailoring */
763 w32 = utf32_word_split(s32, ns32, &nw32, 0);
764 /* Compose back into a string */
766 for(i = 0; i < nw32; ++i) {
768 dynstr_append(d, ' ');
769 dynstr_append_string(d, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
775 /* compute the words of a track name */
776 static char **track_to_words(const char *track,
777 const struct kvp *p) {
779 const char *rootless = track_rootless(track);
782 rootless = track; /* bodge */
784 rootless = strip_extension(rootless);
785 word_split(&v, strip_extension(rootless), tailor_underscore_Word_Break_Other);
786 for(; p; p = p->next)
787 if(is_display_pref(p->name))
788 word_split(&v, p->value, 0);
789 vector_terminate(&v);
790 return dedupe(v.vec, v.nvec);
793 /* return nonzero iff WORD is a stopword */
794 static int stopword(const char *word) {
797 for(n = 0; n < config->stopword.n
798 && strcmp(word, config->stopword.s[n]); ++n)
800 return n < config->stopword.n;
803 /* record that WORD appears in TRACK. Returns 0 or DB_LOCK_DEADLOCK. */
804 static int register_search_word(const char *track, const char *word,
806 if(stopword(word)) return 0;
807 return register_word(trackdb_searchdb, "search", track, word, tid);
810 /* Tags **********************************************************************/
812 /* Return nonzero if C is a valid tag character */
813 static int tagchar(int c) {
822 /* Parse and de-dupe a tag list. If S=0 then assumes "". */
823 static char **parsetags(const char *s) {
829 /* skip initial separators */
830 while(*s && (!tagchar(*s) || *s == ' '))
833 /* find the extent of the tag */
835 while(*s && tagchar(*s))
837 /* strip trailing spaces */
838 while(s > t && s[-1] == ' ')
840 /* add tag to list */
841 vector_append(&v, normalize_tag(t, (size_t)(s - t)));
842 /* skip intermediate and trailing separators */
843 while(*s && (!tagchar(*s) || *s == ' '))
847 vector_terminate(&v);
848 return dedupe(v.vec, v.nvec);
851 /* Record that TRACK has TAG. Returns 0 or DB_LOCK_DEADLOCK. */
852 static int register_tag(const char *track, const char *tag, DB_TXN *tid) {
853 return register_word(trackdb_tagsdb, "tags", track, tag, tid);
856 /* aliases *******************************************************************/
858 /* compute the alias and store at aliasp. Returns 0 or DB_LOCK_DEADLOCK. If
859 * there is no alias sets *aliasp to 0. */
860 static int compute_alias(char **aliasp,
865 const char *s = config->alias, *t, *expansion, *part;
866 int c, used_db = 0, slash_prefix, err;
868 const char *const root = find_track_root(track);
871 /* Bodge for tracks with no root */
876 dynstr_append_string(&d, root);
877 while((c = (unsigned char)*s++)) {
879 dynstr_append(&d, c);
882 if((slash_prefix = (*s == '/')))
885 assert(t != 0); /* validated at startup */
886 part = xstrndup(s, t - s);
887 expansion = getpart(track, "display", part, p, &used_db);
889 if(slash_prefix) dynstr_append(&d, '/');
890 dynstr_append_string(&d, expansion);
892 s = t + 1; /* skip {part} */
894 /* only admit to the alias if we used the db... */
899 dynstr_terminate(&d);
900 /* ...and the answer differs from the original... */
901 if(!strcmp(track, d.vec)) {
905 /* ...and there isn't already a different track with that name (including as
907 switch(err = trackdb_getdata(trackdb_tracksdb, d.vec, &at, tid)) {
909 if((s = kvp_get(at, "_alias_for"))
910 && !strcmp(s, track)) {
922 /* get track and prefs data (if tp/pp not null pointers). Returns 0 on
923 * success, DB_NOTFOUND if the track does not exist or DB_LOCK_DEADLOCK.
924 * Always sets the return values, even if only to null pointers. */
925 static int gettrackdata(const char *track,
928 const char **actualp,
930 #define GTD_NOALIAS 0x0001
933 const char *actual = track;
934 struct kvp *t = 0, *p = 0;
936 if((err = trackdb_getdata(trackdb_tracksdb, track, &t, tid))) goto done;
937 if((actual = kvp_get(t, "_alias_for"))) {
938 if(flags & GTD_NOALIAS) {
939 error(0, "alias passed to gettrackdata where real path required");
942 if((err = trackdb_getdata(trackdb_tracksdb, actual, &t, tid))) goto done;
947 if((err = trackdb_getdata(trackdb_prefsdb, actual, &p, tid)) == DB_LOCK_DEADLOCK)
952 if(actualp) *actualp = actual;
958 /* trackdb_notice() **********************************************************/
960 /** @brief notice a possibly new track
961 * @return @c DB_NOTFOUND if new, 0 if already known
963 int trackdb_notice(const char *track,
969 tid = trackdb_begin_transaction();
970 err = trackdb_notice_tid(track, path, tid);
971 if((err == DB_LOCK_DEADLOCK)) goto fail;
974 trackdb_abort_transaction(tid);
976 trackdb_commit_transaction(tid);
980 /** @brief notice a possibly new track
981 * @param track NFC UTF-8 track name
982 * @param path Raw path name
983 * @param tid Transaction ID
984 * @return @c DB_NOTFOUND if new, 0 if already known, @c DB_LOCK_DEADLOCK also
986 int trackdb_notice_tid(const char *track,
990 struct kvp *t, *a, *p;
994 /* notice whether the tracks.db entry changes */
996 /* get any existing tracks entry */
997 if((err = gettrackdata(track, &t, &p, 0, 0, tid)) == DB_LOCK_DEADLOCK)
999 ret = err; /* 0 or DB_NOTFOUND */
1000 /* this is a real track */
1001 t_changed += kvp_set(&t, "_alias_for", 0);
1002 t_changed += kvp_set(&t, "_path", path);
1003 /* if we have an alias record it in the database */
1004 if((err = compute_alias(&alias, track, p, tid))) return err;
1006 /* won't overwrite someone else's alias as compute_alias() checks */
1007 D(("%s: alias %s", track, alias));
1009 kvp_set(&a, "_alias_for", track);
1010 if((err = trackdb_putdata(trackdb_tracksdb, alias, a, tid, 0))) return err;
1012 /* update search.db */
1013 w = track_to_words(track, p);
1014 for(n = 0; w[n]; ++n)
1015 if((err = register_search_word(track, w[n], tid)))
1017 /* update tags.db */
1018 w = parsetags(kvp_get(p, "tags"));
1019 for(n = 0; w[n]; ++n)
1020 if((err = register_tag(track, w[n], tid)))
1023 /* only store the tracks.db entry if it has changed */
1024 if(t_changed && (err = trackdb_putdata(trackdb_tracksdb, track, t, tid, 0)))
1026 if(ret == DB_NOTFOUND) {
1027 uint32_t timestamp[2];
1032 timestamp[0] = htonl((uint64_t)now >> 32);
1033 timestamp[1] = htonl((uint32_t)now);
1034 memset(&key, 0, sizeof key);
1035 key.data = timestamp;
1036 key.size = sizeof timestamp;
1037 switch(err = trackdb_noticeddb->put(trackdb_noticeddb, tid, &key,
1038 make_key(&data, track), 0)) {
1040 case DB_LOCK_DEADLOCK: return err;
1041 default: fatal(0, "error updating noticed.db: %s", db_strerror(err));
1047 /* trackdb_obsolete() ********************************************************/
1049 /* obsolete a track */
1050 int trackdb_obsolete(const char *track, DB_TXN *tid) {
1055 if((err = gettrackdata(track, 0, &p, 0,
1056 GTD_NOALIAS, tid)) == DB_LOCK_DEADLOCK)
1058 else if(err == DB_NOTFOUND) return 0;
1059 /* compute the alias, if any, and delete it */
1060 if((err = compute_alias(&alias, track, p, tid))) return err;
1062 /* if the alias points to some other track then compute_alias won't
1064 if((err = trackdb_delkey(trackdb_tracksdb, alias, tid))
1065 && err != DB_NOTFOUND)
1068 /* update search.db */
1069 w = track_to_words(track, p);
1070 for(n = 0; w[n]; ++n)
1071 if(trackdb_delkeydata(trackdb_searchdb,
1072 w[n], track, tid) == DB_LOCK_DEADLOCK)
1074 /* update tags.db */
1075 w = parsetags(kvp_get(p, "tags"));
1076 for(n = 0; w[n]; ++n)
1077 if(trackdb_delkeydata(trackdb_tagsdb,
1078 w[n], track, tid) == DB_LOCK_DEADLOCK)
1081 /* update tracks.db */
1082 if(trackdb_delkey(trackdb_tracksdb, track, tid) == DB_LOCK_DEADLOCK)
1084 /* We don't delete the prefs, so they survive temporary outages of the
1085 * (possibly virtual) track filesystem */
1089 /* trackdb_stats() ***********************************************************/
1091 #define H(name) { #name, offsetof(DB_HASH_STAT, name) }
1092 #define B(name) { #name, offsetof(DB_BTREE_STAT, name) }
1094 static const struct statinfo {
1097 } statinfo_hash[] = {
1113 }, statinfo_btree[] = {
1134 /* look up stats for DB */
1135 static int get_stats(struct vector *v,
1137 const struct statinfo *si,
1146 switch(err = database->stat(database, tid, &sp, 0)) {
1149 case DB_LOCK_DEADLOCK:
1150 error(0, "error querying database: %s", db_strerror(err));
1153 fatal(0, "error querying database: %s", db_strerror(err));
1155 for(n = 0; n < nsi; ++n) {
1156 byte_xasprintf(&str, "%s=%"PRIuMAX, si[n].name,
1157 (uintmax_t)*(u_int32_t *)((char *)sp + si[n].offset));
1158 vector_append(v, str);
1164 /** @brief One entry in the search league */
1165 struct search_entry {
1170 /** @brief Add a word to the search league
1171 * @param se Pointer to search league
1172 * @param count Maximum size for search league
1173 * @param nse Current size of search league
1174 * @param word New word, or NULL
1175 * @param n How often @p word appears
1176 * @return New size of search league
1178 static int register_search_entry(struct search_entry *se,
1185 if(word && (nse < count || n > se[nse - 1].n)) {
1186 /* Find the starting point */
1191 /* Find the insertion point */
1192 while(i > 0 && n > se[i - 1].n)
1194 memmove(&se[i + 1], &se[i], (nse - i - 1) * sizeof *se);
1201 /* find the top COUNT words in the search database */
1202 static int search_league(struct vector *v, int count, DB_TXN *tid) {
1203 struct search_entry *se;
1206 int err, n = 0, nse = 0, i;
1211 cursor = trackdb_opencursor(trackdb_searchdb, tid);
1212 se = xmalloc(count * sizeof *se);
1213 /* Walk across the whole database counting up the number of times each
1215 while(!(err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
1217 if(word && wl == k.size && !strncmp(word, k.data, wl))
1218 ++n; /* same word again */
1220 nse = register_search_entry(se, count, nse, word, n);
1221 word = xstrndup(k.data, wl = k.size);
1229 case DB_LOCK_DEADLOCK:
1230 error(0, "error querying search database: %s", db_strerror(err));
1233 fatal(0, "error querying search database: %s", db_strerror(err));
1235 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1237 nse = register_search_entry(se, count, nse, word, n);
1238 byte_xasprintf(&str, "Top %d search words:", nse);
1239 vector_append(v, str);
1240 for(i = 0; i < nse; ++i) {
1241 byte_xasprintf(&str, "%4d: %5d %s", i + 1, se[i].n, se[i].word);
1242 vector_append(v, str);
1247 #define SI(what) statinfo_##what, \
1248 sizeof statinfo_##what / sizeof (struct statinfo)
1250 /* return a list of database stats */
1251 char **trackdb_stats(int *nstatsp) {
1257 tid = trackdb_begin_transaction();
1259 vector_append(&v, (char *)"Tracks database stats:");
1260 if(get_stats(&v, trackdb_tracksdb, SI(btree), tid)) goto fail;
1261 vector_append(&v, (char *)"");
1262 vector_append(&v, (char *)"Search database stats:");
1263 if(get_stats(&v, trackdb_searchdb, SI(hash), tid)) goto fail;
1264 vector_append(&v, (char *)"");
1265 vector_append(&v, (char *)"Prefs database stats:");
1266 if(get_stats(&v, trackdb_prefsdb, SI(hash), tid)) goto fail;
1267 vector_append(&v, (char *)"");
1268 if(search_league(&v, 10, tid)) goto fail;
1269 vector_terminate(&v);
1272 trackdb_abort_transaction(tid);
1274 trackdb_commit_transaction(tid);
1275 if(nstatsp) *nstatsp = v.nvec;
1279 struct stats_details {
1280 void (*done)(char *data, void *u);
1282 int exited; /* subprocess exited */
1283 int closed; /* pipe close */
1284 int wstat; /* wait status from subprocess */
1285 struct dynstr data[1]; /* data read from pipe */
1288 static void stats_complete(struct stats_details *d) {
1291 if(!(d->exited && d->closed))
1293 byte_xasprintf(&s, "\n"
1295 "track lookup cache hits: %lu\n"
1296 "track lookup cache misses: %lu\n",
1298 cache_files_misses);
1299 dynstr_append_string(d->data, s);
1300 dynstr_terminate(d->data);
1301 d->done(d->data->vec, d->u);
1304 static int stats_finished(ev_source attribute((unused)) *ev,
1305 pid_t attribute((unused)) pid,
1307 const struct rusage attribute((unused)) *rusage,
1309 struct stats_details *const d = u;
1313 error(0, "disorder-stats %s", wstat(status));
1318 static int stats_read(ev_source attribute((unused)) *ev,
1324 struct stats_details *const d = u;
1326 dynstr_append_bytes(d->data, ptr, bytes);
1327 ev_reader_consume(reader, bytes);
1334 static int stats_error(ev_source attribute((unused)) *ev,
1337 struct stats_details *const d = u;
1339 error(errno_value, "error reading from pipe to disorder-stats");
1345 void trackdb_stats_subprocess(ev_source *ev,
1346 void (*done)(char *data, void *u),
1350 struct stats_details *d = xmalloc(sizeof *d);
1352 dynstr_init(d->data);
1356 pid = subprogram(ev, "disorder-stats", p[1]);
1358 ev_child(ev, pid, 0, stats_finished, d);
1359 ev_reader_new(ev, p[0], stats_read, stats_error, d, "disorder-stats reader");
1362 /* set a pref (remove if value=0) */
1363 int trackdb_set(const char *track,
1365 const char *value) {
1366 struct kvp *t, *p, *a;
1369 char *oldalias, *newalias, **oldtags = 0, **newtags;
1372 /* TODO: if value matches default then set value=0 */
1376 tid = trackdb_begin_transaction();
1377 if((err = gettrackdata(track, &t, &p, 0,
1378 0, tid)) == DB_LOCK_DEADLOCK)
1380 if(err == DB_NOTFOUND) break;
1381 if(name[0] == '_') {
1382 if(kvp_set(&t, name, value))
1383 if(trackdb_putdata(trackdb_tracksdb, track, t, tid, 0))
1386 /* get the old alias name */
1387 if(compute_alias(&oldalias, track, p, tid)) goto fail;
1388 /* get the old tags */
1389 if(!strcmp(name, "tags"))
1390 oldtags = parsetags(kvp_get(p, "tags"));
1392 if(kvp_set(&p, name, value))
1393 if(trackdb_putdata(trackdb_prefsdb, track, p, tid, 0))
1395 /* compute the new alias name */
1396 if((err = compute_alias(&newalias, track, p, tid))) goto fail;
1397 /* check whether alias has changed */
1398 if(!(oldalias == newalias
1399 || (oldalias && newalias && !strcmp(oldalias, newalias)))) {
1400 /* adjust alias records to fit change */
1402 && trackdb_delkey(trackdb_tracksdb, oldalias, tid) == DB_LOCK_DEADLOCK)
1406 kvp_set(&a, "_alias_for", track);
1407 if(trackdb_putdata(trackdb_tracksdb, newalias, a, tid, 0)) goto fail;
1410 /* check whether tags have changed */
1411 if(!strcmp(name, "tags")) {
1412 newtags = parsetags(value);
1413 while(*oldtags || *newtags) {
1414 if(*oldtags && *newtags) {
1415 cmp = strcmp(*oldtags, *newtags);
1417 /* keeping this tag */
1421 /* old tag fits into a gap in the new list, so delete old */
1424 /* new tag fits into a gap in the old list, so insert new */
1426 } else if(*oldtags) {
1427 /* we've run out of new tags, so remaining old ones are to be
1430 if(trackdb_delkeydata(trackdb_tagsdb,
1431 *oldtags, track, tid) == DB_LOCK_DEADLOCK)
1435 /* we've run out of old tags, so remainig new ones are to be
1438 if(register_tag(track, *newtags, tid)) goto fail;
1448 trackdb_abort_transaction(tid);
1450 trackdb_commit_transaction(tid);
1451 return err == 0 ? 0 : -1;
1455 const char *trackdb_get(const char *track,
1457 return kvp_get(trackdb_get_all(track), name);
1460 /* get all prefs as a 0-terminated array */
1461 struct kvp *trackdb_get_all(const char *track) {
1462 struct kvp *t, *p, **pp;
1466 tid = trackdb_begin_transaction();
1467 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1471 trackdb_abort_transaction(tid);
1473 trackdb_commit_transaction(tid);
1474 for(pp = &p; *pp; pp = &(*pp)->next)
1481 const char *trackdb_resolve(const char *track) {
1486 tid = trackdb_begin_transaction();
1487 if(gettrackdata(track, 0, 0, &actual, 0, tid) == DB_LOCK_DEADLOCK)
1491 trackdb_abort_transaction(tid);
1493 trackdb_commit_transaction(tid);
1497 int trackdb_isalias(const char *track) {
1498 const char *actual = trackdb_resolve(track);
1500 return strcmp(actual, track);
1503 /* test whether a track exists (perhaps an alias) */
1504 int trackdb_exists(const char *track) {
1509 tid = trackdb_begin_transaction();
1510 /* unusually, here we want the return value */
1511 if((err = gettrackdata(track, 0, 0, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1515 trackdb_abort_transaction(tid);
1517 trackdb_commit_transaction(tid);
1521 /* return the list of tags */
1522 char **trackdb_alltags(void) {
1527 WITH_TRANSACTION(trackdb_listkeys(trackdb_tagsdb, v, tid));
1531 /** @brief List all the keys in @p db
1532 * @param db Database
1533 * @param v Vector to store keys in
1534 * @param tid Transaction ID
1535 * @return 0 or DB_LOCK_DEADLOCK
1537 int trackdb_listkeys(DB *db, struct vector *v, DB_TXN *tid) {
1540 DBC *const c = trackdb_opencursor(db, tid);
1543 memset(&k, 0, sizeof k);
1544 while(!(e = c->c_get(c, &k, prepare_data(&d), DB_NEXT_NODUP)))
1545 vector_append(v, xstrndup(k.data, k.size));
1549 case DB_LOCK_DEADLOCK:
1552 fatal(0, "c->c_get: %s", db_strerror(e));
1554 if((e = trackdb_closecursor(c)))
1556 vector_terminate(v);
1560 /* return 1 iff sorted tag lists A and B have at least one member in common */
1561 static int tag_intersection(char **a, char **b) {
1564 /* Same sort of logic as trackdb_set() above */
1566 if(!(cmp = strcmp(*a, *b))) return 1;
1567 else if(cmp < 0) ++a;
1573 /* Check whether a track is suitable for random play. Returns 0 if it is,
1574 * DB_NOTFOUND if it is not or DB_LOCK_DEADLOCK if the database gave us
1576 static int check_suitable(const char *track,
1578 char **required_tags,
1579 char **prohibited_tags) {
1583 const char *pick_at_random, *played_time;
1585 /* don't pick tracks that aren't in any surviving collection (for instance
1586 * you've edited the config but the rescan hasn't done its job yet) */
1587 if(!find_track_root(track)) {
1588 info("found track not in any collection: %s", track);
1591 /* don't pick aliases - only pick the canonical form */
1592 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1593 return DB_LOCK_DEADLOCK;
1594 if(kvp_get(t, "_alias_for"))
1596 /* check that random play is not suppressed for this track */
1597 if((pick_at_random = kvp_get(p, "pick_at_random"))
1598 && !strcmp(pick_at_random, "0"))
1600 /* don't pick a track that's been played in the last 8 hours */
1601 if((played_time = kvp_get(p, "played_time"))) {
1602 last = atoll(played_time);
1604 if(now < last + 8 * 3600) /* TODO configurable */
1607 track_tags = parsetags(kvp_get(p, "tags"));
1608 /* check that no prohibited tag is present for this track */
1609 if(prohibited_tags && tag_intersection(track_tags, prohibited_tags))
1611 /* check that at least one required tags is present for this track */
1612 if(*required_tags && !tag_intersection(track_tags, required_tags))
1617 /* attempt to pick a random non-alias track */
1618 const char *trackdb_random(int tries) {
1623 const char *track, *candidate;
1626 char **required_tags, **prohibited_tags, **tp;
1631 tid = trackdb_begin_transaction();
1632 if((err = trackdb_get_global_tid("required-tags", tid, &tags)))
1634 required_tags = parsetags(tags);
1635 if((err = trackdb_get_global_tid("prohibited-tags", tid, &tags)))
1637 prohibited_tags = parsetags(tags);
1639 if(*required_tags) {
1640 /* Bung all the suitable tracks into a hash and convert to a list of keys
1641 * (to eliminate duplicates). We cache this list since it is possible
1642 * that it will be very large. */
1645 for(tp = required_tags; *tp; ++tp) {
1646 c = trackdb_opencursor(trackdb_tagsdb, tid);
1647 memset(&key, 0, sizeof key);
1649 key.size = strlen(*tp);
1651 err = c->c_get(c, &key, prepare_data(&data), DB_SET);
1653 hash_add(h, xstrndup(data.data, data.size), 0,
1654 HASH_INSERT_OR_REPLACE);
1656 err = c->c_get(c, &key, prepare_data(&data), DB_NEXT_DUP);
1662 case DB_LOCK_DEADLOCK:
1665 fatal(0, "error querying tags.db: %s", db_strerror(err));
1667 trackdb_closecursor(c);
1670 error(0, "required tag %s does not match any tracks", *tp);
1672 nreqtracks = hash_count(h);
1673 reqtracks = hash_keys(h);
1675 while(nreqtracks && !track && tries-- > 0) {
1676 r = (rand() * (double)nreqtracks / (RAND_MAX + 1.0));
1677 candidate = reqtracks[r];
1678 switch(check_suitable(candidate, tid,
1679 required_tags, prohibited_tags)) {
1685 case DB_LOCK_DEADLOCK:
1690 /* No required tags. We pick random record numbers in the database
1692 switch(err = trackdb_tracksdb->stat(trackdb_tracksdb, tid, &sp, 0)) {
1695 case DB_LOCK_DEADLOCK:
1696 error(0, "error querying tracks.db: %s", db_strerror(err));
1699 fatal(0, "error querying tracks.db: %s", db_strerror(err));
1702 error(0, "cannot pick tracks at random from an empty database");
1703 while(sp->bt_nkeys && !track && tries-- > 0) {
1704 /* record numbers count from 1 upwards */
1705 r = 1 + (rand() * (double)sp->bt_nkeys / (RAND_MAX + 1.0));
1706 memset(&key, sizeof key, 0);
1707 key.flags = DB_DBT_MALLOC;
1708 key.size = sizeof r;
1710 switch(err = trackdb_tracksdb->get(trackdb_tracksdb, tid, &key, prepare_data(&data),
1714 case DB_LOCK_DEADLOCK:
1715 error(0, "error querying tracks.db: %s", db_strerror(err));
1718 fatal(0, "error querying tracks.db: %s", db_strerror(err));
1720 candidate = xstrndup(key.data, key.size);
1721 switch(check_suitable(candidate, tid,
1722 required_tags, prohibited_tags)) {
1728 case DB_LOCK_DEADLOCK:
1735 trackdb_closecursor(c);
1737 trackdb_abort_transaction(tid);
1739 trackdb_commit_transaction(tid);
1741 error(0, "could not pick a random track");
1745 /* get a track name given the prefs. Set *used_db to 1 if we got the answer
1746 * from the prefs. */
1747 static const char *getpart(const char *track,
1748 const char *context,
1750 const struct kvp *p,
1755 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
1756 if((result = kvp_get(p, pref)))
1759 result = trackname_part(track, context, part);
1760 assert(result != 0);
1764 /* get a track name part, like trackname_part(), but taking the database into
1766 const char *trackdb_getpart(const char *track,
1767 const char *context,
1775 /* construct the full pref */
1776 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
1778 tid = trackdb_begin_transaction();
1779 if((err = gettrackdata(track, 0, &p, &actual, 0, tid)) == DB_LOCK_DEADLOCK)
1783 trackdb_abort_transaction(tid);
1785 trackdb_commit_transaction(tid);
1786 return getpart(actual, context, part, p, &used_db);
1789 /* get the raw path name for @track@ (might be an alias) */
1790 const char *trackdb_rawpath(const char *track) {
1796 tid = trackdb_begin_transaction();
1797 if(gettrackdata(track, &t, 0, 0, 0, tid) == DB_LOCK_DEADLOCK)
1801 trackdb_abort_transaction(tid);
1803 trackdb_commit_transaction(tid);
1804 if(!(path = kvp_get(t, "_path"))) path = track;
1808 /* trackdb_list **************************************************************/
1810 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
1811 * readable at some point */
1813 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
1814 * If RE is a null pointer then it matches everything. */
1815 static int track_matches(size_t dl, const char *track, size_t tl,
1823 switch(rc = pcre_exec(re, 0, track, tl, 0, 0, ovec, 3)) {
1824 case PCRE_ERROR_NOMATCH: return 0;
1827 error(0, "pcre_exec returned %d, subject '%s'", rc, track);
1834 static int do_list(struct vector *v, const char *dir,
1835 enum trackdb_listable what, const pcre *re, DB_TXN *tid) {
1841 size_t l, last_dir_len = 0;
1842 char *last_dir = 0, *track, *alias;
1846 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
1849 /* find the first key >= dir */
1850 err = cursor->c_get(cursor, &k, &d, DB_SET_RANGE);
1851 /* keep going while we're dealing with <dir/anything> */
1854 && ((char *)k.data)[dl] == '/'
1855 && !memcmp(k.data, dir, dl)) {
1856 ptr = memchr((char *)k.data + dl + 1, '/', k.size - (dl + 1));
1858 /* we have <dir/component/anything>, so <dir/component> is a directory */
1859 l = ptr - (char *)k.data;
1860 if(what & trackdb_directories)
1862 && l == last_dir_len
1863 && !memcmp(last_dir, k.data, l))) {
1864 last_dir = xstrndup(k.data, last_dir_len = l);
1865 if(track_matches(dl, k.data, l, re))
1866 vector_append(v, last_dir);
1869 /* found a plain file */
1870 if((what & trackdb_files)) {
1871 track = xstrndup(k.data, k.size);
1872 if((err = trackdb_getdata(trackdb_prefsdb,
1873 track, &p, tid)) == DB_LOCK_DEADLOCK)
1875 /* if this file has an alias in the same directory then we skip it */
1876 if((err = compute_alias(&alias, track, p, tid)))
1878 if(!(alias && !strcmp(d_dirname(alias), d_dirname(track))))
1879 if(track_matches(dl, k.data, k.size, re))
1880 vector_append(v, track);
1883 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
1891 case DB_LOCK_DEADLOCK:
1892 error(0, "error querying database: %s", db_strerror(err));
1895 fatal(0, "error querying database: %s", db_strerror(err));
1898 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1902 /* return the directories or files below @dir@ */
1903 char **trackdb_list(const char *dir, int *np, enum trackdb_listable what,
1911 tid = trackdb_begin_transaction();
1914 if(do_list(&v, dir, what, re, tid))
1917 for(n = 0; n < config->collection.n; ++n)
1918 if(do_list(&v, config->collection.s[n].root, what, re, tid))
1923 trackdb_abort_transaction(tid);
1925 trackdb_commit_transaction(tid);
1926 vector_terminate(&v);
1932 /* If S is tag:something, return something. Else return 0. */
1933 static const char *checktag(const char *s) {
1934 if(!strncmp(s, "tag:", 4))
1940 /* return a list of tracks containing all of the words given. If you
1941 * ask for only stopwords you get no tracks. */
1942 char **trackdb_search(char **wordlist, int nwordlist, int *ntracks) {
1943 const char **w, *best = 0, *tag;
1944 char **twords, **tags;
1946 int i, j, n, err, what;
1956 *ntracks = 0; /* for early returns */
1957 /* normalize all the words */
1958 w = xmalloc(nwordlist * sizeof (char *));
1959 istag = xmalloc_noptr(nwordlist);
1960 for(n = 0; n < nwordlist; ++n) {
1964 w[n] = utf8_casefold_compat(wordlist[n], strlen(wordlist[n]), 0);
1965 if(checktag(w[n])) {
1966 ++ntags; /* count up tags */
1967 /* Normalize the tag */
1968 w[n] = normalize_tag(w[n] + 4, strlen(w[n] + 4));
1971 /* Normalize the search term by removing combining characters */
1972 if(!(w32 = utf8_to_utf32(w[n], strlen(w[n]), &nw32)))
1974 nw32 = remove_combining_chars(w32, nw32);
1975 if(!(w[n] = utf32_to_utf8(w32, nw32, 0)))
1980 /* find the longest non-stopword */
1981 for(n = 0; n < nwordlist; ++n)
1982 if(!istag[n] && !stopword(w[n]))
1983 if(!best || strlen(w[n]) > strlen(best))
1985 /* TODO: we should at least in principal be able to identify the word or tag
1986 * with the least matches in log time, and choose that as our primary search
1988 if(ntags && !best) {
1989 /* Only tags are listed. We limit to the first and narrow down with the
1991 best = istag[0] ? w[0] : 0;
1992 db = trackdb_tagsdb;
1995 /* We can limit to some word. */
1996 db = trackdb_searchdb;
1999 /* Only stopwords */
2005 tid = trackdb_begin_transaction();
2006 /* find all the tracks that have that word */
2011 cursor = trackdb_opencursor(db, tid);
2012 while(!(err = cursor->c_get(cursor, &k, &d, what))) {
2013 vector_append(&v, xstrndup(d.data, d.size));
2020 case DB_LOCK_DEADLOCK:
2021 error(0, "error querying %s database: %s", dbname, db_strerror(err));
2024 fatal(0, "error querying %s database: %s", dbname, db_strerror(err));
2026 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2028 /* do a naive search over that (hopefuly fairly small) list of tracks */
2030 for(n = 0; n < v.nvec; ++n) {
2031 if((err = gettrackdata(v.vec[n], 0, &p, 0, 0, tid) == DB_LOCK_DEADLOCK))
2034 error(0, "track %s unexpected error: %s", v.vec[n], db_strerror(err));
2037 twords = track_to_words(v.vec[n], p);
2038 tags = parsetags(kvp_get(p, "tags"));
2039 for(i = 0; i < nwordlist; ++i) {
2042 /* Track must have this tag */
2043 for(j = 0; tags[j]; ++j)
2044 if(!strcmp(tag, tags[j])) break; /* tag found */
2045 if(!tags[j]) break; /* tag not found */
2047 /* Track must contain this word */
2048 for(j = 0; twords[j]; ++j)
2049 if(!strcmp(w[i], twords[j])) break; /* word found */
2050 if(!twords[j]) break; /* word not found */
2053 if(i >= nwordlist) /* all words found */
2054 vector_append(&u, v.vec[n]);
2058 trackdb_closecursor(cursor);
2060 trackdb_abort_transaction(tid);
2061 info("retrying search");
2063 trackdb_commit_transaction(tid);
2064 vector_terminate(&u);
2070 /* trackdb_scan **************************************************************/
2072 int trackdb_scan(const char *root,
2073 int (*callback)(const char *track,
2081 const size_t root_len = root ? strlen(root) : 0;
2086 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2088 err = cursor->c_get(cursor, make_key(&k, root), prepare_data(&d),
2091 memset(&k, 0, sizeof k);
2092 err = cursor->c_get(cursor, &k, prepare_data(&d),
2097 || (k.size > root_len
2098 && !strncmp(k.data, root, root_len)
2099 && ((char *)k.data)[root_len] == '/')) {
2100 data = kvp_urldecode(d.data, d.size);
2101 if(kvp_get(data, "_path")) {
2102 track = xstrndup(k.data, k.size);
2103 /* Advance to the next track before the callback so that the callback
2104 * may safely delete the track */
2105 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2106 if((cberr = callback(track, data, u, tid))) {
2111 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2115 trackdb_closecursor(cursor);
2122 case DB_LOCK_DEADLOCK:
2123 error(0, "c->c_get: %s", db_strerror(err));
2126 fatal(0, "c->c_get: %s", db_strerror(err));
2130 /* trackdb_rescan ************************************************************/
2132 /* called when the rescanner terminates */
2133 static int reap_rescan(ev_source attribute((unused)) *ev,
2136 const struct rusage attribute((unused)) *rusage,
2137 void attribute((unused)) *u) {
2138 if(pid == rescan_pid) rescan_pid = -1;
2140 error(0, RESCAN": %s", wstat(status));
2142 D((RESCAN" terminated: %s", wstat(status)));
2143 /* Our cache of file lookups is out of date now */
2144 cache_clean(&cache_files_type);
2145 eventlog("rescanned", (char *)0);
2149 void trackdb_rescan(ev_source *ev) {
2152 if(rescan_pid != -1) {
2153 error(0, "rescan already underway");
2156 rescan_pid = subprogram(ev, RESCAN, -1);
2158 ev_child(ev, rescan_pid, 0, reap_rescan, 0);
2159 D(("started rescanner"));
2161 /* This is the first rescan, we block until it is complete */
2162 while(waitpid(rescan_pid, &w, 0) < 0 && errno == EINTR)
2164 reap_rescan(0, rescan_pid, w, 0, 0);
2168 int trackdb_rescan_cancel(void) {
2169 if(rescan_pid == -1) return 0;
2170 if(kill(rescan_pid, SIGTERM) < 0)
2171 fatal(errno, "error killing rescanner");
2176 /* global prefs **************************************************************/
2178 void trackdb_set_global(const char *name,
2186 tid = trackdb_begin_transaction();
2187 if(!(err = trackdb_set_global_tid(name, value, tid)))
2189 trackdb_abort_transaction(tid);
2191 trackdb_commit_transaction(tid);
2192 /* log important state changes */
2193 if(!strcmp(name, "playing")) {
2194 state = !value || !strcmp(value, "yes");
2195 info("playing %s by %s",
2196 state ? "enabled" : "disabled",
2198 eventlog("state", state ? "enable_play" : "disable_play", (char *)0);
2200 if(!strcmp(name, "random-play")) {
2201 state = !value || !strcmp(value, "yes");
2202 info("random play %s by %s",
2203 state ? "enabled" : "disabled",
2205 eventlog("state", state ? "enable_random" : "disable_random", (char *)0);
2207 if(!strcmp(name, "required-tags"))
2211 int trackdb_set_global_tid(const char *name,
2217 memset(&k, 0, sizeof k);
2218 memset(&d, 0, sizeof d);
2219 k.data = (void *)name;
2220 k.size = strlen(name);
2222 d.data = (void *)value;
2223 d.size = strlen(value);
2226 err = trackdb_globaldb->put(trackdb_globaldb, tid, &k, &d, 0);
2228 err = trackdb_globaldb->del(trackdb_globaldb, tid, &k, 0);
2229 if(err == DB_LOCK_DEADLOCK) return err;
2231 fatal(0, "error updating database: %s", db_strerror(err));
2235 const char *trackdb_get_global(const char *name) {
2241 tid = trackdb_begin_transaction();
2242 if(!(err = trackdb_get_global_tid(name, tid, &r)))
2244 trackdb_abort_transaction(tid);
2246 trackdb_commit_transaction(tid);
2250 int trackdb_get_global_tid(const char *name,
2256 memset(&k, 0, sizeof k);
2257 k.data = (void *)name;
2258 k.size = strlen(name);
2259 switch(err = trackdb_globaldb->get(trackdb_globaldb, tid, &k,
2260 prepare_data(&d), 0)) {
2262 *rp = xstrndup(d.data, d.size);
2267 case DB_LOCK_DEADLOCK:
2270 fatal(0, "error reading database: %s", db_strerror(err));
2274 /** @brief Retrieve the most recently added tracks
2275 * @param ntracksp Where to put count, or 0
2276 * @param maxtracks Maximum number of tracks to retrieve
2277 * @return null-terminated array of track names
2279 * The most recently added track is first in the array.
2281 char **trackdb_new(int *ntracksp,
2287 tid = trackdb_begin_transaction();
2288 tracks = trackdb_new_tid(ntracksp, maxtracks, tid);
2291 trackdb_abort_transaction(tid);
2293 trackdb_commit_transaction(tid);
2297 /** @brief Retrieve the most recently added tracks
2298 * @param ntracksp Where to put count, or 0
2299 * @param maxtracks Maximum number of tracks to retrieve, or 0 for all
2300 * @param tid Transaction ID
2301 * @return null-terminated array of track names, or NULL on deadlock
2303 * The most recently added track is first in the array.
2305 static char **trackdb_new_tid(int *ntracksp,
2311 struct vector tracks[1];
2313 vector_init(tracks);
2314 c = trackdb_opencursor(trackdb_noticeddb, tid);
2315 while((maxtracks <= 0 || tracks->nvec < maxtracks)
2316 && !(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_PREV)))
2317 vector_append(tracks, xstrndup(d.data, d.size));
2319 case 0: /* hit maxtracks */
2320 case DB_NOTFOUND: /* ran out of tracks */
2322 case DB_LOCK_DEADLOCK:
2323 trackdb_closecursor(c);
2326 fatal(0, "error reading noticed.db: %s", db_strerror(err));
2328 if((err = trackdb_closecursor(c)))
2329 return 0; /* deadlock */
2330 vector_terminate(tracks);
2332 *ntracksp = tracks->nvec;
2336 /** @brief Expire noticed.db
2337 * @param earliest Earliest timestamp to keep
2339 void trackdb_expire_noticed(time_t earliest) {
2343 tid = trackdb_begin_transaction();
2344 if(!trackdb_expire_noticed_tid(earliest, tid))
2346 trackdb_abort_transaction(tid);
2348 trackdb_commit_transaction(tid);
2351 /** @brief Expire noticed.db
2352 * @param earliest Earliest timestamp to keep
2353 * @param tid Transaction ID
2354 * @return 0 or DB_LOCK_DEADLOCK
2356 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid) {
2364 c = trackdb_opencursor(trackdb_noticeddb, tid);
2365 while(!(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_NEXT))) {
2367 when = (time_t)(((uint64_t)ntohl(kk[0]) << 32) + ntohl(kk[1]));
2368 if(when >= earliest)
2370 if((err = c->c_del(c, 0))) {
2371 if(err != DB_LOCK_DEADLOCK)
2372 fatal(0, "error deleting expired noticed.db entry: %s",
2378 if(err == DB_NOTFOUND)
2380 if(err && err != DB_LOCK_DEADLOCK)
2381 fatal(0, "error expiring noticed.db: %s", db_strerror(err));
2383 if((err = trackdb_closecursor(c))) {
2384 if(err != DB_LOCK_DEADLOCK)
2385 fatal(0, "error closing cursor: %s", db_strerror(err));
2389 info("expired %d tracks from noticed.db", count);
2393 /* tidying up ****************************************************************/
2395 void trackdb_gc(void) {
2399 if((err = trackdb_env->txn_checkpoint(trackdb_env,
2400 config->checkpoint_kbyte,
2401 config->checkpoint_min,
2403 fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err));
2404 if((err = trackdb_env->log_archive(trackdb_env, &logfiles, DB_ARCH_REMOVE)))
2405 fatal(0, "trackdb_env->log_archive: %s", db_strerror(err));
2406 /* This makes catastrophic recovery impossible. However, the user can still
2407 * preserve the important data by using disorder-dump to snapshot their
2408 * prefs, and later to restore it. This is likely to have much small
2409 * long-term storage requirements than record the db logfiles. */
2412 /* user database *************************************************************/
2414 /** @brief Return true if @p user is trusted */
2415 static int trusted(const char *user) {
2418 for(n = 0; (n < config->trust.n
2419 && strcmp(config->trust.s[n], user)); ++n)
2421 return n < config->trust.n;
2424 /** @brief Return non-zero for a valid username
2426 * Currently we only allow the letters and digits in ASCII. We could be more
2427 * liberal than this but it is a nice simple test. It is critical that
2428 * semicolons are never allowed.
2430 static int valid_username(const char *user) {
2434 const uint8_t c = *user++;
2435 /* For now we are very strict */
2436 if((c >= 'a' && c <= 'z')
2437 || (c >= 'A' && c <= 'Z')
2438 || (c >= '0' && c <= '9'))
2446 /** @brief Add a user */
2447 static int create_user(const char *user,
2448 const char *password,
2451 const char *confirmation,
2457 /* sanity check user */
2458 if(!valid_username(user)) {
2459 error(0, "invalid username '%s'", user);
2462 if(parse_rights(rights, 0, 1)) {
2463 error(0, "invalid rights string");
2466 /* data for this user */
2468 kvp_set(&k, "password", password);
2469 kvp_set(&k, "rights", rights);
2471 kvp_set(&k, "email", email);
2473 kvp_set(&k, "confirmation", confirmation);
2474 snprintf(s, sizeof s, "%jd", (intmax_t)time(0));
2475 kvp_set(&k, "created", s);
2476 return trackdb_putdata(trackdb_usersdb, user, k, tid, flags);
2479 /** @brief Add one pre-existing user */
2480 static int one_old_user(const char *user, const char *password,
2484 /* www-data doesn't get added */
2485 if(!strcmp(user, "www-data")) {
2486 info("not adding www-data to user database");
2490 if(!strcmp(user, "root"))
2492 else if(trusted(user)) {
2495 parse_rights(config->default_rights, &r, 1);
2496 r &= ~(rights_type)(RIGHT_SCRATCH__MASK|RIGHT_MOVE__MASK|RIGHT_REMOVE__MASK);
2497 r |= (RIGHT_ADMIN|RIGHT_RESCAN
2498 |RIGHT_SCRATCH_ANY|RIGHT_MOVE_ANY|RIGHT_REMOVE_ANY);
2499 rights = rights_string(r);
2501 rights = config->default_rights;
2502 return create_user(user, password, rights, 0/*email*/, 0/*confirmation*/,
2503 tid, DB_NOOVERWRITE);
2506 static int trackdb_old_users_tid(DB_TXN *tid) {
2509 for(n = 0; n < config->allow.n; ++n) {
2510 switch(one_old_user(config->allow.s[n].s[0], config->allow.s[n].s[1],
2513 info("created user %s from 'allow' directive", config->allow.s[n].s[0]);
2516 error(0, "user %s already exists, delete 'allow' directive",
2517 config->allow.s[n].s[0]);
2518 /* This won't ever become fatal - eventually 'allow' will be
2521 case DB_LOCK_DEADLOCK:
2522 return DB_LOCK_DEADLOCK;
2528 /** @brief Read old 'allow' directives and copy them to the users database */
2529 void trackdb_old_users(void) {
2533 WITH_TRANSACTION(trackdb_old_users_tid(tid));
2536 /** @brief Create a root user in the user database if there is none */
2537 void trackdb_create_root(void) {
2542 /* Choose a new root password */
2543 gcry_randomize(pwbin, sizeof pwbin, GCRY_STRONG_RANDOM);
2544 pw = mime_to_base64(pwbin, sizeof pwbin);
2545 /* Create the root user if it does not exist */
2546 WITH_TRANSACTION(create_user("root", pw, "all",
2547 0/*email*/, 0/*confirmation*/,
2548 tid, DB_NOOVERWRITE));
2550 info("created root user");
2553 /** @brief Find a user's password from the database
2554 * @param user Username
2555 * @return Password or NULL
2557 * Only works if running as a user that can read the database!
2559 * If the user exists but has no password, "" is returned.
2561 const char *trackdb_get_password(const char *user) {
2564 const char *password;
2566 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
2569 password = kvp_get(k, "password");
2570 return password ? password : "";
2573 /** @brief Add a new user
2574 * @param user Username
2575 * @param password Password or NULL
2576 * @param rights Initial rights
2577 * @param email Email address or NULL
2578 * @param confirmation Confirmation string or NULL
2579 * @return 0 on success, non-0 on error
2581 int trackdb_adduser(const char *user,
2582 const char *password,
2585 const char *confirmation) {
2588 WITH_TRANSACTION(create_user(user, password, rights, email, confirmation,
2589 tid, DB_NOOVERWRITE));
2591 error(0, "cannot created user '%s' because they already exist", user);
2595 info("created user '%s' with rights '%s' and email address '%s'",
2596 user, rights, email);
2598 info("created user '%s' with rights '%s'", user, rights);
2603 /** @brief Delete a user
2604 * @param user User to delete
2605 * @return 0 on success, non-0 if the user didn't exist anyway
2607 int trackdb_deluser(const char *user) {
2610 WITH_TRANSACTION(trackdb_delkey(trackdb_usersdb, user, tid));
2612 error(0, "cannot delete user '%s' because they do not exist", user);
2615 info("deleted user '%s'", user);
2619 /** @brief Get user information
2620 * @param user User to query
2621 * @return Linked list of user information or NULL if user does not exist
2623 * Every user has at least a @c rights entry so NULL can be used to mean no
2626 struct kvp *trackdb_getuserinfo(const char *user) {
2630 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
2637 /** @brief Edit user information
2638 * @param user User to edit
2639 * @param key Key to change
2640 * @param value Value to set, or NULL to remove
2641 * @param tid Transaction ID
2642 * @return 0, DB_LOCK_DEADLOCK or DB_NOTFOUND
2644 static int trackdb_edituserinfo_tid(const char *user, const char *key,
2645 const char *value, DB_TXN *tid) {
2649 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
2651 if(!kvp_set(&k, key, value))
2652 return 0; /* no change */
2653 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
2656 /** @brief Edit user information
2657 * @param user User to edit
2658 * @param key Key to change
2659 * @param value Value to set, or NULL to remove
2660 * @return 0 on success, non-0 on error
2662 int trackdb_edituserinfo(const char *user,
2663 const char *key, const char *value) {
2666 if(!strcmp(key, "rights")) {
2668 error(0, "cannot remove 'rights' key from user '%s'", user);
2671 if(parse_rights(value, 0, 1)) {
2672 error(0, "invalid rights string");
2675 } else if(!strcmp(key, "email")) {
2676 if(!strchr(value, '@')) {
2677 error(0, "invalid email address '%s' for user '%s'", user, value);
2680 } else if(!strcmp(key, "created")) {
2681 error(0, "cannot change creation date for user '%s'", user);
2683 } else if(strcmp(key, "password")
2684 && !strcmp(key, "confirmation")) {
2685 error(0, "unknown user info key '%s' for user '%s'", key, user);
2688 WITH_TRANSACTION(trackdb_edituserinfo_tid(user, key, value, tid));
2690 error(0, "unknown user '%s'", user);
2696 /** @brief List all users
2697 * @return NULL-terminated list of users
2699 char **trackdb_listusers(void) {
2704 WITH_TRANSACTION(trackdb_listkeys(trackdb_usersdb, v, tid));
2708 static int trackdb_confirm_tid(const char *user, const char *confirmation,
2710 const char *stored_confirmation;
2714 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
2716 if(!(stored_confirmation = kvp_get(k, "confirmation"))) {
2717 error(0, "already confirmed user '%s'", user);
2718 /* DB claims -30,800 to -30,999 so -1 should be a safe bet */
2721 if(strcmp(confirmation, stored_confirmation)) {
2722 error(0, "wrong confirmation string for user '%s'", user);
2726 kvp_set(&k, "confirmation", 0);
2727 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
2730 /** @brief Confirm a user registration
2731 * @param user Username
2732 * @param confirmation Confirmation string
2733 * @return 0 on success, non-0 on error
2735 int trackdb_confirm(const char *user, const char *confirmation) {
2738 WITH_TRANSACTION(trackdb_confirm_tid(user, confirmation, tid));
2741 info("registration confirmed for user '%s'", user);
2744 error(0, "confirmation for nonexistent user '%s'", user);
2746 default: /* already reported */
2756 indent-tabs-mode:nil