2 * This file is part of DisOrder
3 * Copyright (C) 2005-2008 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 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU 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, see <http://www.gnu.org/licenses/>.
18 /** @file lib/trackdb.c
19 * @brief Track database
21 * This file is getting in desparate need of splitting up...
27 #include <sys/socket.h>
33 #include <sys/resource.h>
35 #include <arpa/inet.h>
47 #include "configuration.h"
52 #include "trackname.h"
53 #include "trackdb-int.h"
63 #define RESCAN "disorder-rescan"
64 #define DEADLOCK "disorder-deadlock"
66 static const char *getpart(const char *track,
71 static char **trackdb_new_tid(int *ntracksp,
74 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid);
75 static char *normalize_tag(const char *s, size_t ns);
77 const struct cache_type cache_files_type = { 86400 };
78 unsigned long cache_files_hits, cache_files_misses;
80 /** @brief Set by trackdb_open() */
81 int trackdb_existing_database;
83 /* setup and teardown ********************************************************/
85 /** @brief Database home directory
87 * All database files live below here. It had better never change.
89 static const char *home;
91 /** @brief Database 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 schedule database
150 * - Keys are ID strings, generated at random
151 * - Values are encoded key-value pairs
152 * - There can be more than one value per key
153 * - Data cannot be reconstructed
155 * See @ref server/schedule.c for further information.
157 DB *trackdb_scheduledb;
159 /** @brief The user database
160 * - Keys are usernames
161 * - Values are encoded key-value pairs
162 * - Data is user data and cannot be reconstructed
166 /** @brief The playlists database
167 * - Keys are playlist names
168 * - Values are encoded key-value pairs
169 * - Data is user data and cannot be reconstructed
171 DB *trackdb_playlistsdb;
173 /** @brief Deadlock manager PID */
174 static pid_t db_deadlock_pid = -1;
176 /** @brief Rescanner PID */
177 static pid_t rescan_pid = -1;
179 /** @brief Set when the database environment exists */
180 static int initialized;
182 /** @brief Set when databases are open */
185 /** @brief Current stats subprocess PIDs */
186 static hash *stats_pids;
188 /** @brief PID of current random track chooser (disorder-choose) */
189 static pid_t choose_pid = -1;
191 /** @brief Our end of pipe from disorder-choose */
192 static int choose_fd;
194 /** @brief Callback to supply random track to */
195 static random_callback *choose_callback;
197 /** @brief Accumulator for output from disorder-choose */
198 static struct dynstr choose_output;
200 /** @brief Current completion status of disorder-choose
201 * A bitmap of @ref CHOOSE_READING and @ref CHOOSE_RUNNING.
203 static unsigned choose_complete;
205 /* @brief Exit status from disorder-choose */
206 static int choose_status;
208 /** @brief disorder-choose process is running */
209 #define CHOOSE_RUNNING 1
211 /** @brief disorder-choose pipe is still open */
212 #define CHOOSE_READING 2
214 /** @brief Comparison function for filename-based keys */
215 static int compare(DB attribute((unused)) *db_,
216 const DBT *a, const DBT *b) {
217 return compare_path_raw(a->data, a->size, b->data, b->size);
220 /** @brief Test whether the track database can be read
221 * @return 1 if it can, 0 if it cannot
223 int trackdb_readable(void) {
226 byte_xasprintf(&usersdb, "%s/users.db", config->home);
227 return access(usersdb, R_OK) == 0;
230 /** @brief Open database environment
231 * @param flags Flags word
233 * Flags should be one of:
234 * - @ref TRACKDB_NO_RECOVER
235 * - @ref TRACKDB_NORMAL_RECOVER
236 * - @ref TRACKDB_FATAL_RECOVER
237 * - @ref TRACKDB_MAY_CREATE
239 void trackdb_init(int flags) {
241 const int recover = flags & TRACKDB_RECOVER_MASK;
242 static int recover_type[] = { 0, DB_RECOVER, DB_RECOVER_FATAL };
245 assert(initialized == 0);
248 if(strcmp(home, config->home))
249 fatal(0, "cannot change db home without server restart");
253 if(flags & TRACKDB_MAY_CREATE) {
259 /* Remove world/group permissions on any regular files already in the
260 * database directory. Actually we don't care about all of them but it's
261 * easier to just do the lot. This can be revisited if it's a serious
262 * practical inconvenience for anyone.
264 * The socket, not being a regular file, is excepted.
266 if(!(dp = opendir(config->home)))
267 fatal(errno, "error reading %s", config->home);
268 while((de = readdir(dp))) {
269 byte_xasprintf(&p, "%s/%s", config->home, de->d_name);
270 if(lstat(p, &st) == 0
271 && S_ISREG(st.st_mode)
272 && (st.st_mode & 077)) {
273 if(chmod(p, st.st_mode & 07700) < 0)
274 fatal(errno, "cannot chmod %s", p);
281 /* create environment */
282 if((err = db_env_create(&trackdb_env, 0))) fatal(0, "db_env_create: %s",
284 if((err = trackdb_env->set_alloc(trackdb_env,
285 xmalloc_noptr, xrealloc_noptr, xfree)))
286 fatal(0, "trackdb_env->set_alloc: %s", db_strerror(err));
287 if((err = trackdb_env->set_lk_max_locks(trackdb_env, 10000)))
288 fatal(0, "trackdb_env->set_lk_max_locks: %s", db_strerror(err));
289 if((err = trackdb_env->set_lk_max_objects(trackdb_env, 10000)))
290 fatal(0, "trackdb_env->set_lk_max_objects: %s", db_strerror(err));
291 if((err = trackdb_env->open(trackdb_env, config->home,
297 |recover_type[recover],
299 fatal(0, "trackdb_env->open %s: %s", config->home, db_strerror(err));
300 trackdb_env->set_errpfx(trackdb_env, "DB");
301 trackdb_env->set_errfile(trackdb_env, stderr);
302 trackdb_env->set_verbose(trackdb_env, DB_VERB_DEADLOCK, 1);
303 trackdb_env->set_verbose(trackdb_env, DB_VERB_RECOVERY, 1);
304 trackdb_env->set_verbose(trackdb_env, DB_VERB_REPLICATION, 1);
305 D(("initialized database environment"));
308 /** @brief Called when deadlock manager terminates */
309 static int reap_db_deadlock(ev_source attribute((unused)) *ev,
310 pid_t attribute((unused)) pid,
312 const struct rusage attribute((unused)) *rusage,
313 void attribute((unused)) *u) {
314 db_deadlock_pid = -1;
316 fatal(0, "deadlock manager unexpectedly terminated: %s",
319 D(("deadlock manager terminated: %s", wstat(status)));
323 /** @brief Start a subprogram
324 * @param ev Event loop
325 * @param outputfd File descriptor to redirect @c stdout to, or -1
326 * @param prog Program name
327 * @param ... Arguments
330 * Starts a subprocess. Adds the following arguments:
331 * - @c --config to ensure the right config file is used
332 * - @c --debug or @c --no-debug to match debug settings
333 * - @c --syslog or @c --no-syslog to match log settings
335 static pid_t subprogram(ev_source *ev, int outputfd, const char *prog,
339 const char *args[1024], **argp, *a;
343 *argp++ = "--config";
344 *argp++ = configfile;
345 *argp++ = debugging ? "--debug" : "--no-debug";
346 *argp++ = log_default == &log_syslog ? "--syslog" : "--no-syslog";
348 while((a = va_arg(ap, const char *)))
352 /* If we're in the background then trap subprocess stdout/stderr */
353 if(!(pid = xfork())) {
356 ev_signal_atfork(ev);
357 signal(SIGPIPE, SIG_DFL);
362 /* ensure we don't leak privilege anywhere */
363 if(setuid(geteuid()) < 0)
364 fatal(errno, "error calling setuid");
365 /* If we were negatively niced, undo it. We don't bother checking for
366 * error, it's not that important. */
367 setpriority(PRIO_PROCESS, 0, 0);
368 execvp(prog, (char **)args);
369 fatal(errno, "error invoking %s", prog);
374 /** @brief Start deadlock manager
375 * @param ev Event loop
377 * Called from the main server (only).
379 void trackdb_master(ev_source *ev) {
380 assert(db_deadlock_pid == -1);
381 db_deadlock_pid = subprogram(ev, -1, DEADLOCK, (char *)0);
382 ev_child(ev, db_deadlock_pid, 0, reap_db_deadlock, 0);
383 D(("started deadlock manager"));
386 /** @brief Kill a subprocess and wait for it to terminate
387 * @param ev Event loop or NULL
388 * @param pid Process ID or -1
389 * @param what Description of subprocess
391 * Used during trackdb_deinit(). This function blocks so don't use it for
392 * normal teardown as that will hang the server.
394 static void terminate_and_wait(ev_source *ev,
401 if(kill(pid, SIGTERM) < 0)
402 fatal(errno, "error killing %s", what);
403 /* wait for the rescanner to finish */
404 while(waitpid(pid, &err, 0) == -1 && errno == EINTR)
407 ev_child_cancel(ev, pid);
410 /** @brief Close database environment
411 * @param ev Event loop
413 void trackdb_deinit(ev_source *ev) {
417 assert(initialized == 1);
420 /* close the environment */
421 if((err = trackdb_env->close(trackdb_env, 0)))
422 fatal(0, "trackdb_env->close: %s", db_strerror(err));
424 terminate_and_wait(ev, rescan_pid, "disorder-rescan");
426 terminate_and_wait(ev, choose_pid, "disorder-choose");
430 char **ks = hash_keys(stats_pids);
433 pid_t pid = atoi(*ks++);
434 terminate_and_wait(ev, pid, "disorder-stats");
439 terminate_and_wait(ev, db_deadlock_pid, "disorder-deadlock");
440 db_deadlock_pid = -1;
441 D(("deinitialized database environment"));
444 /** @brief Open a specific database
445 * @param path Relative path to database
446 * @param dbflags Database flags: DB_DUP, DB_DUPSORT, etc
447 * @param dbtype Database type: DB_HASH, DB_BTREE, etc
448 * @param openflags Open flags: DB_RDONLY, DB_CREATE, etc
449 * @param mode Permission mask: usually 0666
450 * @return Database handle
452 static DB *open_db(const char *path,
460 D(("open %s", path));
461 path = config_get_file(path);
462 if((err = db_create(&db, trackdb_env, 0)))
463 fatal(0, "db_create %s: %s", path, db_strerror(err));
465 if((err = db->set_flags(db, dbflags)))
466 fatal(0, "db->set_flags %s: %s", path, db_strerror(err));
467 if(dbtype == DB_BTREE)
468 if((err = db->set_bt_compare(db, compare)))
469 fatal(0, "db->set_bt_compare %s: %s", path, db_strerror(err));
470 if((err = db->open(db, 0, path, 0, dbtype,
471 openflags | DB_AUTO_COMMIT, mode))) {
472 if((openflags & DB_CREATE) || errno != ENOENT) {
473 if((err2 = db->close(db, 0)))
474 error(0, "db->close: %s", db_strerror(err2));
476 trackdb_env->close(trackdb_env,0);
478 fatal(0, "db->open %s: %s", path, db_strerror(err));
486 /** @brief Open track databases
487 * @param flags Flags flags word
489 * @p flags should have one of:
490 * - @p TRACKDB_NO_UPGRADE, if no upgrade should be attempted
491 * - @p TRACKDB_CAN_UPGRADE, if an upgrade may be attempted
492 * - @p TRACKDB_OPEN_FOR_UPGRADE, if this is disorder-dbupgrade
494 * - @p TRACKDB_READ_ONLY, read only access
496 void trackdb_open(int flags) {
499 uint32_t dbflags = flags & TRACKDB_READ_ONLY ? DB_RDONLY : DB_CREATE;
504 /* check the database version first */
505 trackdb_globaldb = open_db("global.db", 0, DB_HASH, DB_RDONLY, 0666);
506 if(trackdb_globaldb) {
507 /* This is an existing database */
511 s = trackdb_get_global("_dbversion");
512 /* Close the database again, we'll open it property below */
513 if((err = trackdb_globaldb->close(trackdb_globaldb, 0)))
514 fatal(0, "error closing global.db: %s", db_strerror(err));
515 trackdb_globaldb = 0;
516 /* Convert version string to an integer */
517 oldversion = s ? atol(s) : 1;
518 if(oldversion > config->dbversion) {
519 /* Database is from the future; we never allow this. */
520 fatal(0, "this version of DisOrder is too old for database version %ld",
523 if(oldversion < config->dbversion) {
524 /* Database version is out of date */
525 switch(flags & TRACKDB_UPGRADE_MASK) {
526 case TRACKDB_NO_UPGRADE:
527 /* This database needs upgrading but this is not permitted */
528 fatal(0, "database needs upgrading from %ld to %ld",
529 oldversion, config->dbversion);
530 case TRACKDB_CAN_UPGRADE:
531 /* This database needs upgrading */
532 info("invoking disorder-dbupgrade to upgrade from %ld to %ld",
533 oldversion, config->dbversion);
534 pid = subprogram(0, -1, "disorder-dbupgrade", (char *)0);
535 while(waitpid(pid, &err, 0) == -1 && errno == EINTR)
538 fatal(0, "disorder-dbupgrade %s", wstat(err));
539 info("disorder-dbupgrade succeeded");
541 case TRACKDB_OPEN_FOR_UPGRADE:
547 if(oldversion == config->dbversion && (flags & TRACKDB_OPEN_FOR_UPGRADE)) {
548 /* This doesn't make any sense */
549 fatal(0, "database is already at current version");
551 trackdb_existing_database = 1;
553 if(flags & TRACKDB_OPEN_FOR_UPGRADE) {
554 /* Cannot upgrade a new database */
555 fatal(0, "cannot upgrade a database that does not exist");
557 /* This is a brand new database */
558 trackdb_existing_database = 0;
560 /* open the databases */
561 if(!(trackdb_usersdb = open_db("users.db",
562 0, DB_HASH, dbflags, 0600)))
563 fatal(0, "cannot open users.db");
564 trackdb_tracksdb = open_db("tracks.db",
565 DB_RECNUM, DB_BTREE, dbflags, 0666);
566 trackdb_searchdb = open_db("search.db",
567 DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
568 trackdb_tagsdb = open_db("tags.db",
569 DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
570 trackdb_prefsdb = open_db("prefs.db", 0, DB_HASH, dbflags, 0666);
571 trackdb_globaldb = open_db("global.db", 0, DB_HASH, dbflags, 0666);
572 trackdb_noticeddb = open_db("noticed.db",
573 DB_DUPSORT, DB_BTREE, dbflags, 0666);
574 trackdb_scheduledb = open_db("schedule.db", 0, DB_HASH, dbflags, 0666);
575 trackdb_playlistsdb = open_db("playlists.db", 0, DB_HASH, dbflags, 0666);
576 if(!trackdb_existing_database && !(flags & TRACKDB_READ_ONLY)) {
577 /* Stash the database version */
580 assert(!(flags & TRACKDB_OPEN_FOR_UPGRADE));
581 snprintf(buf, sizeof buf, "%ld", config->dbversion);
582 trackdb_set_global("_dbversion", buf, 0);
584 D(("opened databases"));
587 /** @brief Close track databases */
588 void trackdb_close(void) {
594 #define CLOSE(N, V) do { \
595 if(V && (err = V->close(V, 0))) \
596 fatal(0, "error closing %s: %s", N, db_strerror(err)); \
599 CLOSE("tracks.db", trackdb_tracksdb);
600 CLOSE("search.db", trackdb_searchdb);
601 CLOSE("tags.db", trackdb_tagsdb);
602 CLOSE("prefs.db", trackdb_prefsdb);
603 CLOSE("global.db", trackdb_globaldb);
604 CLOSE("noticed.db", trackdb_noticeddb);
605 CLOSE("schedule.db", trackdb_scheduledb);
606 CLOSE("users.db", trackdb_usersdb);
607 CLOSE("playlists.db", trackdb_playlistsdb);
608 D(("closed databases"));
611 /* generic db routines *******************************************************/
613 /** @brief Fetch and decode a database entry
615 * @param track Track name
616 * @param kp Where to put decoded list (or NULL if you don't care)
617 * @param tid Owning transaction
618 * @return 0, @c DB_NOTFOUND or @c DB_LOCK_DEADLOCK
620 int trackdb_getdata(DB *db,
627 switch(err = db->get(db, tid, make_key(&key, track),
628 prepare_data(&data), 0)) {
631 *kp = kvp_urldecode(data.data, data.size);
637 case DB_LOCK_DEADLOCK:
638 error(0, "error querying database: %s", db_strerror(err));
641 fatal(0, "error querying database: %s", db_strerror(err));
645 /** @brief Encode and store a database entry
647 * @param track Track name
648 * @param k List of key/value pairs to store
649 * @param tid Owning transaction
650 * @param flags DB flags e.g. DB_NOOVERWRITE
651 * @return 0, DB_KEYEXIST or DB_LOCK_DEADLOCK
653 int trackdb_putdata(DB *db,
661 switch(err = db->put(db, tid, make_key(&key, track),
662 encode_data(&data, k), flags)) {
666 case DB_LOCK_DEADLOCK:
667 error(0, "error updating database: %s", db_strerror(err));
670 fatal(0, "error updating database: %s", db_strerror(err));
674 /** @brief Delete a database entry
676 * @param track Key to delete
677 * @param tid Transaction ID
678 * @return 0, DB_NOTFOUND or DB_LOCK_DEADLOCK
680 int trackdb_delkey(DB *db,
686 switch(err = db->del(db, tid, make_key(&key, track), 0)) {
690 case DB_LOCK_DEADLOCK:
691 error(0, "error updating database: %s", db_strerror(err));
694 fatal(0, "error updating database: %s", db_strerror(err));
698 /** @brief Open a database cursor
700 * @param tid Owning transaction
703 DBC *trackdb_opencursor(DB *db, DB_TXN *tid) {
707 switch(err = db->cursor(db, tid, &c, 0)) {
709 default: fatal(0, "error creating cursor: %s", db_strerror(err));
714 /** @brief Close a database cursor
716 * @return 0 or DB_LOCK_DEADLOCK
718 int trackdb_closecursor(DBC *c) {
722 switch(err = c->c_close(c)) {
725 case DB_LOCK_DEADLOCK:
726 error(0, "error closing cursor: %s", db_strerror(err));
729 fatal(0, "error closing cursor: %s", db_strerror(err));
733 /** @brief Delete a key/data pair
737 * @param tid Owning transaction
738 * @return 0, DB_NOTFOUND or DB_LOCK_DEADLOCK
740 * Used by the search and tags databases, hence the odd parameter names.
741 * See also register_word().
743 int trackdb_delkeydata(DB *db,
751 c = trackdb_opencursor(db, tid);
752 switch(err = c->c_get(c, make_key(&key, word),
753 make_key(&data, track), DB_GET_BOTH)) {
755 switch(err = c->c_del(c, 0)) {
761 case DB_LOCK_DEADLOCK:
762 error(0, "error updating database: %s", db_strerror(err));
765 fatal(0, "c->c_del: %s", db_strerror(err));
770 case DB_LOCK_DEADLOCK:
771 error(0, "error updating database: %s", db_strerror(err));
774 fatal(0, "c->c_get: %s", db_strerror(err));
776 if(trackdb_closecursor(c)) err = DB_LOCK_DEADLOCK;
780 /** @brief Start a transaction
781 * @return Transaction
783 DB_TXN *trackdb_begin_transaction(void) {
787 if((err = trackdb_env->txn_begin(trackdb_env, 0, &tid, 0)))
788 fatal(0, "trackdb_env->txn_begin: %s", db_strerror(err));
792 /** @brief Abort transaction
793 * @param tid Transaction (or NULL)
795 * If @p tid is NULL then nothing happens.
797 void trackdb_abort_transaction(DB_TXN *tid) {
801 if((err = tid->abort(tid)))
802 fatal(0, "tid->abort: %s", db_strerror(err));
805 /** @brief Commit transaction
806 * @param tid Transaction (must not be NULL)
808 void trackdb_commit_transaction(DB_TXN *tid) {
811 if((err = tid->commit(tid, 0)))
812 fatal(0, "tid->commit: %s", db_strerror(err));
815 /* search/tags shared code ***************************************************/
817 /** @brief Comparison function used by dedupe()
818 * @param a Pointer to first key
819 * @param b Pointer to second key
824 static int wordcmp(const void *a, const void *b) {
825 return strcmp(*(const char **)a, *(const char **)b);
828 /** @brief Sort and de-duplicate @p vec
829 * @param vec Vector to sort
830 * @param nvec Length of @p vec
833 * The returned vector is NULL-terminated, and there must be room for this NULL
834 * even if there are no duplicates (i.e. it must have more than @p nvec
837 static char **dedupe(char **vec, int nvec) {
840 qsort(vec, nvec, sizeof (char *), wordcmp);
844 for(n = 1; n < nvec; ++n)
845 if(strcmp(vec[n], vec[m - 1]))
852 /** @brief Store a key/data pair
854 * @param what Description
857 * @param tid Owning transaction
858 * @return 0 or DB_DEADLOCK
860 * Used by the search and tags databases, hence the odd parameter names.
861 * See also trackdb_delkeydata().
863 static int register_word(DB *db, const char *what,
864 const char *track, const char *word,
869 switch(err = db->put(db, tid, make_key(&key, word),
870 make_key(&data, track), DB_NODUPDATA)) {
874 case DB_LOCK_DEADLOCK:
875 error(0, "error updating %s.db: %s", what, db_strerror(err));
878 fatal(0, "error updating %s.db: %s", what, db_strerror(err));
882 /* search primitives *********************************************************/
884 /** @brief Return true iff @p name is a trackname_display_ pref
885 * @param name Preference name
886 * @return Non-zero iff @p name is a trackname_display_ pref
888 static int is_display_pref(const char *name) {
889 static const char prefix[] = "trackname_display_";
890 return !strncmp(name, prefix, (sizeof prefix) - 1);
893 /** @brief Word_Break property tailor that treats underscores as spaces
894 * @param c Code point
895 * @return Tailored property or -1 to use standard value
897 * Passed to utf32_word_split() when splitting a track name into words.
898 * See word_split() and @ref unicode_property_tailor.
900 static int tailor_underscore_Word_Break_Other(uint32_t c) {
904 case 0x005F: /* LOW LINE (SPACING UNDERSCORE) */
905 return unicode_Word_Break_Other;
909 /** @brief Remove all combining characters in-place
910 * @param s Pointer to start of string
911 * @param ns Length of string
912 * @return New, possiblby reduced, length
914 static size_t remove_combining_chars(uint32_t *s, size_t ns) {
915 uint32_t *start = s, *t = s, *end = s + ns;
918 const uint32_t c = *s++;
919 if(!utf32_combining_class(c))
925 /** @brief Normalize and split a string using a given tailoring
926 * @param v Where to store words from string
927 * @param s Input string
928 * @param pt Word_Break property tailor, or NULL
930 * The output words will be:
932 * - have any combination characters stripped
933 * - not include any word break code points (as tailored)
935 * Used by track_to_words(), with @p pt set to @ref
936 * tailor_underscore_Word_Break_Other, and by normalize_tag() with no
939 static void word_split(struct vector *v,
941 unicode_property_tailor *pt) {
943 uint32_t *t32, **w32;
945 /* Convert to UTF-32 */
946 if(!(t32 = utf8_to_utf32(s, strlen(s), &nt32)))
948 /* Erase case distinctions */
949 if(!(t32 = utf32_casefold_compat(t32, nt32, &nt32)))
951 /* Drop combining characters */
952 nt32 = remove_combining_chars(t32, nt32);
953 /* Split into words, treating _ as a space */
954 w32 = utf32_word_split(t32, nt32, &nw, pt);
955 /* Convert words back to UTF-8 and append to result */
956 for(i = 0; i < nw; ++i)
957 vector_append(v, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
960 /** @brief Normalize a tag
962 * @param ns Length of tag
963 * @return Normalized string or NULL on error
965 * The return value will be:
967 * - have no leading or trailing space
968 * - have no combining characters
969 * - all spacing between words will be a single U+0020 SPACE
971 static char *normalize_tag(const char *s, size_t ns) {
972 uint32_t *s32, **w32;
973 size_t ns32, nw32, i;
976 if(!(s32 = utf8_to_utf32(s, ns, &ns32)))
978 if(!(s32 = utf32_casefold_compat(s32, ns32, &ns32))) /* ->NFKD */
980 ns32 = remove_combining_chars(s32, ns32);
981 /* Split into words, no Word_Break tailoring */
982 w32 = utf32_word_split(s32, ns32, &nw32, 0);
983 /* Compose back into a string */
985 for(i = 0; i < nw32; ++i) {
987 dynstr_append(d, ' ');
988 dynstr_append_string(d, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
994 /** @brief Compute the words of a track name
995 * @param track Track name
996 * @param p Preferences (for display prefs)
997 * @return NULL-terminated, de-duplicated list or words
999 static char **track_to_words(const char *track,
1000 const struct kvp *p) {
1002 const char *rootless = track_rootless(track);
1005 rootless = track; /* bodge */
1007 rootless = strip_extension(rootless);
1008 word_split(&v, strip_extension(rootless), tailor_underscore_Word_Break_Other);
1009 for(; p; p = p->next)
1010 if(is_display_pref(p->name))
1011 word_split(&v, p->value, 0);
1012 vector_terminate(&v);
1013 return dedupe(v.vec, v.nvec);
1016 /** @brief Test for a stopword
1018 * @return Non-zero if @p word is a stopword
1020 static int stopword(const char *word) {
1023 for(n = 0; n < config->stopword.n
1024 && strcmp(word, config->stopword.s[n]); ++n)
1026 return n < config->stopword.n;
1029 /** @brief Register a search term
1030 * @param track Track name
1031 * @param word A word that appears in the name of @p track
1032 * @param tid Owning transaction
1033 * @return 0 or DB_LOCK_DEADLOCK
1035 static int register_search_word(const char *track, const char *word,
1037 if(stopword(word)) return 0;
1038 return register_word(trackdb_searchdb, "search", track, word, tid);
1041 /* Tags **********************************************************************/
1043 /** @brief Test for tag characters
1044 * @param c Character
1045 * @return Non-zero if @p c is a tag character
1047 * The current rule is that commas and the control characters 0-31 are not
1048 * allowed but anything else is permitted. This is arguably a bit loose.
1050 static int tagchar(int c) {
1059 /** @brief Parse a tag list
1060 * @param s Tag list or NULL (equivalent to "")
1061 * @return Parsed tag list
1063 * The tags will be normalized (as per normalize_tag()) and de-duplicated.
1065 char **parsetags(const char *s) {
1071 /* skip initial separators */
1072 while(*s && (!tagchar(*s) || *s == ' '))
1075 /* find the extent of the tag */
1077 while(*s && tagchar(*s))
1079 /* strip trailing spaces */
1080 while(s > t && s[-1] == ' ')
1082 /* add tag to list */
1083 vector_append(&v, normalize_tag(t, (size_t)(s - t)));
1084 /* skip intermediate and trailing separators */
1085 while(*s && (!tagchar(*s) || *s == ' '))
1089 vector_terminate(&v);
1090 return dedupe(v.vec, v.nvec);
1093 /** @brief Register a tag
1094 * @param track Track name
1095 * @param tag Tag name
1096 * @param tid Owning transaction
1097 * @return 0 or DB_LOCK_DEADLOCK
1099 static int register_tag(const char *track, const char *tag, DB_TXN *tid) {
1100 return register_word(trackdb_tagsdb, "tags", track, tag, tid);
1103 /* aliases *******************************************************************/
1105 /* compute the alias and store at aliasp. Returns 0 or DB_LOCK_DEADLOCK. If
1106 * there is no alias sets *aliasp to 0. */
1107 static int compute_alias(char **aliasp,
1109 const struct kvp *p,
1112 const char *s = config->alias, *t, *expansion, *part;
1113 int c, used_db = 0, slash_prefix, err;
1115 const char *const root = find_track_root(track);
1118 /* Bodge for tracks with no root */
1123 dynstr_append_string(&d, root);
1124 while((c = (unsigned char)*s++)) {
1126 dynstr_append(&d, c);
1129 if((slash_prefix = (*s == '/')))
1132 assert(t != 0); /* validated at startup */
1133 part = xstrndup(s, t - s);
1134 expansion = getpart(track, "display", part, p, &used_db);
1136 if(slash_prefix) dynstr_append(&d, '/');
1137 dynstr_append_string(&d, expansion);
1139 s = t + 1; /* skip {part} */
1141 /* only admit to the alias if we used the db... */
1146 dynstr_terminate(&d);
1147 /* ...and the answer differs from the original... */
1148 if(!strcmp(track, d.vec)) {
1152 /* ...and there isn't already a different track with that name (including as
1154 switch(err = trackdb_getdata(trackdb_tracksdb, d.vec, &at, tid)) {
1156 if((s = kvp_get(at, "_alias_for"))
1157 && !strcmp(s, track)) {
1169 /* get track and prefs data (if tp/pp not null pointers). Returns 0 on
1170 * success, DB_NOTFOUND if the track does not exist or DB_LOCK_DEADLOCK.
1171 * Always sets the return values, even if only to null pointers. */
1172 static int gettrackdata(const char *track,
1175 const char **actualp,
1177 #define GTD_NOALIAS 0x0001
1180 const char *actual = track;
1181 struct kvp *t = 0, *p = 0;
1183 if((err = trackdb_getdata(trackdb_tracksdb, track, &t, tid))) goto done;
1184 if((actual = kvp_get(t, "_alias_for"))) {
1185 if(flags & GTD_NOALIAS) {
1186 error(0, "alias passed to gettrackdata where real path required");
1189 if((err = trackdb_getdata(trackdb_tracksdb, actual, &t, tid))) goto done;
1192 assert(actual != 0);
1194 if((err = trackdb_getdata(trackdb_prefsdb, actual, &p, tid)) == DB_LOCK_DEADLOCK)
1199 if(actualp) *actualp = actual;
1205 /* trackdb_notice() **********************************************************/
1207 /** @brief notice a possibly new track
1208 * @return @c DB_NOTFOUND if new, 0 if already known
1210 int trackdb_notice(const char *track,
1216 tid = trackdb_begin_transaction();
1217 err = trackdb_notice_tid(track, path, tid);
1218 if((err == DB_LOCK_DEADLOCK)) goto fail;
1221 trackdb_abort_transaction(tid);
1223 trackdb_commit_transaction(tid);
1227 /** @brief notice a possibly new track
1228 * @param track NFC UTF-8 track name
1229 * @param path Raw path name
1230 * @param tid Transaction ID
1231 * @return @c DB_NOTFOUND if new, 0 if already known, @c DB_LOCK_DEADLOCK also
1233 int trackdb_notice_tid(const char *track,
1237 struct kvp *t, *a, *p;
1239 char *alias, **w, *noticed;
1242 /* notice whether the tracks.db entry changes */
1244 /* get any existing tracks entry */
1245 if((err = gettrackdata(track, &t, &p, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1247 ret = err; /* 0 or DB_NOTFOUND */
1248 /* this is a real track */
1249 t_changed += kvp_set(&t, "_alias_for", 0);
1250 t_changed += kvp_set(&t, "_path", path);
1252 if(ret == DB_NOTFOUND) {
1253 /* It's a new track; record the time */
1254 byte_xasprintf(¬iced, "%lld", (long long)now);
1255 t_changed += kvp_set(&t, "_noticed", noticed);
1257 /* if we have an alias record it in the database */
1258 if((err = compute_alias(&alias, track, p, tid))) return err;
1260 /* won't overwrite someone else's alias as compute_alias() checks */
1261 D(("%s: alias %s", track, alias));
1263 kvp_set(&a, "_alias_for", track);
1264 if((err = trackdb_putdata(trackdb_tracksdb, alias, a, tid, 0))) return err;
1266 /* update search.db */
1267 w = track_to_words(track, p);
1268 for(n = 0; w[n]; ++n)
1269 if((err = register_search_word(track, w[n], tid)))
1271 /* update tags.db */
1272 w = parsetags(kvp_get(p, "tags"));
1273 for(n = 0; w[n]; ++n)
1274 if((err = register_tag(track, w[n], tid)))
1276 /* only store the tracks.db entry if it has changed */
1277 if(t_changed && (err = trackdb_putdata(trackdb_tracksdb, track, t, tid, 0)))
1279 if(ret == DB_NOTFOUND) {
1280 uint32_t timestamp[2];
1283 timestamp[0] = htonl((uint64_t)now >> 32);
1284 timestamp[1] = htonl((uint32_t)now);
1285 memset(&key, 0, sizeof key);
1286 key.data = timestamp;
1287 key.size = sizeof timestamp;
1288 switch(err = trackdb_noticeddb->put(trackdb_noticeddb, tid, &key,
1289 make_key(&data, track), 0)) {
1291 case DB_LOCK_DEADLOCK: return err;
1292 default: fatal(0, "error updating noticed.db: %s", db_strerror(err));
1298 /* trackdb_obsolete() ********************************************************/
1300 /* obsolete a track */
1301 int trackdb_obsolete(const char *track, DB_TXN *tid) {
1306 if((err = gettrackdata(track, 0, &p, 0,
1307 GTD_NOALIAS, tid)) == DB_LOCK_DEADLOCK)
1309 else if(err == DB_NOTFOUND) return 0;
1310 /* compute the alias, if any, and delete it */
1311 if((err = compute_alias(&alias, track, p, tid))) return err;
1313 /* if the alias points to some other track then compute_alias won't
1315 if((err = trackdb_delkey(trackdb_tracksdb, alias, tid))
1316 && err != DB_NOTFOUND)
1319 /* update search.db */
1320 w = track_to_words(track, p);
1321 for(n = 0; w[n]; ++n)
1322 if(trackdb_delkeydata(trackdb_searchdb,
1323 w[n], track, tid) == DB_LOCK_DEADLOCK)
1325 /* update tags.db */
1326 w = parsetags(kvp_get(p, "tags"));
1327 for(n = 0; w[n]; ++n)
1328 if(trackdb_delkeydata(trackdb_tagsdb,
1329 w[n], track, tid) == DB_LOCK_DEADLOCK)
1331 /* update tracks.db */
1332 if(trackdb_delkey(trackdb_tracksdb, track, tid) == DB_LOCK_DEADLOCK)
1334 /* We don't delete the prefs, so they survive temporary outages of the
1335 * (possibly virtual) track filesystem */
1339 /* trackdb_stats() ***********************************************************/
1341 #define H(name) { #name, offsetof(DB_HASH_STAT, name) }
1342 #define B(name) { #name, offsetof(DB_BTREE_STAT, name) }
1344 static const struct statinfo {
1347 } statinfo_hash[] = {
1363 }, statinfo_btree[] = {
1384 /* look up stats for DB */
1385 static int get_stats(struct vector *v,
1387 const struct statinfo *si,
1396 switch(err = database->stat(database, tid, &sp, 0)) {
1399 case DB_LOCK_DEADLOCK:
1400 error(0, "error querying database: %s", db_strerror(err));
1403 fatal(0, "error querying database: %s", db_strerror(err));
1405 for(n = 0; n < nsi; ++n) {
1406 byte_xasprintf(&str, "%s=%"PRIuMAX, si[n].name,
1407 (uintmax_t)*(u_int32_t *)((char *)sp + si[n].offset));
1408 vector_append(v, str);
1414 /** @brief One entry in the search league */
1415 struct search_entry {
1420 /** @brief Add a word to the search league
1421 * @param se Pointer to search league
1422 * @param count Maximum size for search league
1423 * @param nse Current size of search league
1424 * @param word New word, or NULL
1425 * @param n How often @p word appears
1426 * @return New size of search league
1428 static int register_search_entry(struct search_entry *se,
1435 if(word && (nse < count || n > se[nse - 1].n)) {
1436 /* Find the starting point */
1441 /* Find the insertion point */
1442 while(i > 0 && n > se[i - 1].n)
1444 memmove(&se[i + 1], &se[i], (nse - i - 1) * sizeof *se);
1451 /* find the top COUNT words in the search database */
1452 static int search_league(struct vector *v, int count, DB_TXN *tid) {
1453 struct search_entry *se;
1456 int err, n = 0, nse = 0, i;
1461 cursor = trackdb_opencursor(trackdb_searchdb, tid);
1462 se = xmalloc(count * sizeof *se);
1463 /* Walk across the whole database counting up the number of times each
1465 while(!(err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
1467 if(word && wl == k.size && !strncmp(word, k.data, wl))
1468 ++n; /* same word again */
1470 nse = register_search_entry(se, count, nse, word, n);
1471 word = xstrndup(k.data, wl = k.size);
1479 case DB_LOCK_DEADLOCK:
1480 error(0, "error querying search database: %s", db_strerror(err));
1483 fatal(0, "error querying search database: %s", db_strerror(err));
1485 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1487 nse = register_search_entry(se, count, nse, word, n);
1488 byte_xasprintf(&str, "Top %d search words:", nse);
1489 vector_append(v, str);
1490 for(i = 0; i < nse; ++i) {
1491 byte_xasprintf(&str, "%4d: %5d %s", i + 1, se[i].n, se[i].word);
1492 vector_append(v, str);
1497 #define SI(what) statinfo_##what, \
1498 sizeof statinfo_##what / sizeof (struct statinfo)
1500 /* return a list of database stats */
1501 char **trackdb_stats(int *nstatsp) {
1507 tid = trackdb_begin_transaction();
1509 vector_append(&v, (char *)"Tracks database stats:");
1510 if(get_stats(&v, trackdb_tracksdb, SI(btree), tid)) goto fail;
1511 vector_append(&v, (char *)"");
1512 vector_append(&v, (char *)"Search database stats:");
1513 if(get_stats(&v, trackdb_searchdb, SI(hash), tid)) goto fail;
1514 vector_append(&v, (char *)"");
1515 vector_append(&v, (char *)"Prefs database stats:");
1516 if(get_stats(&v, trackdb_prefsdb, SI(hash), tid)) goto fail;
1517 vector_append(&v, (char *)"");
1518 if(search_league(&v, 10, tid)) goto fail;
1519 vector_terminate(&v);
1522 trackdb_abort_transaction(tid);
1524 trackdb_commit_transaction(tid);
1525 if(nstatsp) *nstatsp = v.nvec;
1529 struct stats_details {
1530 void (*done)(char *data, void *u);
1532 int exited; /* subprocess exited */
1533 int closed; /* pipe close */
1534 int wstat; /* wait status from subprocess */
1535 struct dynstr data[1]; /* data read from pipe */
1538 static void stats_complete(struct stats_details *d) {
1541 if(!(d->exited && d->closed))
1543 byte_xasprintf(&s, "\n"
1545 "track lookup cache hits: %lu\n"
1546 "track lookup cache misses: %lu\n",
1548 cache_files_misses);
1549 dynstr_append_string(d->data, s);
1550 dynstr_terminate(d->data);
1551 d->done(d->data->vec, d->u);
1554 static int stats_finished(ev_source attribute((unused)) *ev,
1557 const struct rusage attribute((unused)) *rusage,
1559 struct stats_details *const d = u;
1563 error(0, "disorder-stats %s", wstat(status));
1566 byte_xasprintf(&k, "%lu", (unsigned long)pid);
1567 hash_remove(stats_pids, k);
1571 static int stats_read(ev_source attribute((unused)) *ev,
1577 struct stats_details *const d = u;
1579 dynstr_append_bytes(d->data, ptr, bytes);
1580 ev_reader_consume(reader, bytes);
1587 static int stats_error(ev_source attribute((unused)) *ev,
1590 struct stats_details *const d = u;
1592 error(errno_value, "error reading from pipe to disorder-stats");
1598 void trackdb_stats_subprocess(ev_source *ev,
1599 void (*done)(char *data, void *u),
1603 struct stats_details *d = xmalloc(sizeof *d);
1605 dynstr_init(d->data);
1609 pid = subprogram(ev, p[1], "disorder-stats", (char *)0);
1611 ev_child(ev, pid, 0, stats_finished, d);
1612 if(!ev_reader_new(ev, p[0], stats_read, stats_error, d,
1613 "disorder-stats reader"))
1614 fatal(0, "ev_reader_new for disorder-stats reader failed");
1615 /* Remember the PID */
1617 stats_pids = hash_new(1);
1619 byte_xasprintf(&k, "%lu", (unsigned long)pid);
1620 hash_add(stats_pids, k, "", HASH_INSERT);
1623 /** @brief Parse a track name part preference
1624 * @param name Preference name
1625 * @param partp Where to store part name
1626 * @param contextp Where to store context name
1627 * @return 0 on success, non-0 if parse fails
1629 static int trackdb__parse_namepref(const char *name,
1633 static const char prefix[] = "trackname_";
1635 if(strncmp(name, prefix, strlen(prefix)))
1636 return -1; /* not trackname_* at all */
1637 name += strlen(prefix);
1638 /* There had better be a _ between context and part */
1639 c = strchr(name, '_');
1642 /* Context is first in the pref name even though most APIs have the part
1643 * first. Confusing; sorry. */
1644 *contextp = xstrndup(name, c - name);
1646 /* There had better NOT be a second _ */
1649 *partp = xstrdup(c);
1653 /** @brief Compute the default value for a track preference
1654 * @param track Track name
1655 * @param name Preference name
1656 * @return Default value or 0 if none/not known
1658 static const char *trackdb__default(const char *track, const char *name) {
1659 char *context, *part;
1661 if(!trackdb__parse_namepref(name, &part, &context)) {
1662 /* We can work out the default for a trackname_ pref */
1663 return trackname_part(track, context, part);
1664 } else if(!strcmp(name, "weight")) {
1665 /* We know the default weight */
1667 } else if(!strcmp(name, "pick_at_random")) {
1668 /* By default everything is eligible for picking at random */
1670 } else if(!strcmp(name, "tags")) {
1671 /* By default everything no track has any tags */
1677 /* set a pref (remove if value=0) */
1678 int trackdb_set(const char *track,
1680 const char *value) {
1681 struct kvp *t, *p, *a;
1684 char *oldalias, *newalias, **oldtags = 0, **newtags;
1687 /* If the value matches the default then unset instead, to keep the database
1688 * tidy. Older versions did not have this feature so your database may yet
1689 * have some default values stored in it. */
1691 def = trackdb__default(track, name);
1692 if(def && !strcmp(value, def))
1697 tid = trackdb_begin_transaction();
1698 if((err = gettrackdata(track, &t, &p, 0,
1699 0, tid)) == DB_LOCK_DEADLOCK)
1701 if(err == DB_NOTFOUND) break;
1702 if(name[0] == '_') {
1703 if(kvp_set(&t, name, value))
1704 if(trackdb_putdata(trackdb_tracksdb, track, t, tid, 0))
1707 /* get the old alias name */
1708 if(compute_alias(&oldalias, track, p, tid)) goto fail;
1709 /* get the old tags */
1710 if(!strcmp(name, "tags"))
1711 oldtags = parsetags(kvp_get(p, "tags"));
1713 if(kvp_set(&p, name, value))
1714 if(trackdb_putdata(trackdb_prefsdb, track, p, tid, 0))
1716 /* compute the new alias name */
1717 if((err = compute_alias(&newalias, track, p, tid))) goto fail;
1718 /* check whether alias has changed */
1719 if(!(oldalias == newalias
1720 || (oldalias && newalias && !strcmp(oldalias, newalias)))) {
1721 /* adjust alias records to fit change */
1723 && trackdb_delkey(trackdb_tracksdb, oldalias, tid) == DB_LOCK_DEADLOCK)
1727 kvp_set(&a, "_alias_for", track);
1728 if(trackdb_putdata(trackdb_tracksdb, newalias, a, tid, 0)) goto fail;
1731 /* check whether tags have changed */
1732 if(!strcmp(name, "tags")) {
1733 newtags = parsetags(value);
1734 while(*oldtags || *newtags) {
1735 if(*oldtags && *newtags) {
1736 cmp = strcmp(*oldtags, *newtags);
1738 /* keeping this tag */
1742 /* old tag fits into a gap in the new list, so delete old */
1745 /* new tag fits into a gap in the old list, so insert new */
1747 } else if(*oldtags) {
1748 /* we've run out of new tags, so remaining old ones are to be
1751 if(trackdb_delkeydata(trackdb_tagsdb,
1752 *oldtags, track, tid) == DB_LOCK_DEADLOCK)
1756 /* we've run out of old tags, so remainig new ones are to be
1759 if(register_tag(track, *newtags, tid)) goto fail;
1768 trackdb_abort_transaction(tid);
1770 trackdb_commit_transaction(tid);
1771 return err == 0 ? 0 : -1;
1775 const char *trackdb_get(const char *track,
1777 return kvp_get(trackdb_get_all(track), name);
1780 /* get all prefs as a 0-terminated array */
1781 struct kvp *trackdb_get_all(const char *track) {
1782 struct kvp *t, *p, **pp;
1786 tid = trackdb_begin_transaction();
1787 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1791 trackdb_abort_transaction(tid);
1793 trackdb_commit_transaction(tid);
1794 for(pp = &p; *pp; pp = &(*pp)->next)
1801 const char *trackdb_resolve(const char *track) {
1806 tid = trackdb_begin_transaction();
1807 if(gettrackdata(track, 0, 0, &actual, 0, tid) == DB_LOCK_DEADLOCK)
1811 trackdb_abort_transaction(tid);
1813 trackdb_commit_transaction(tid);
1817 int trackdb_isalias(const char *track) {
1818 const char *actual = trackdb_resolve(track);
1820 return strcmp(actual, track);
1823 /* test whether a track exists (perhaps an alias) */
1824 int trackdb_exists(const char *track) {
1829 tid = trackdb_begin_transaction();
1830 /* unusually, here we want the return value */
1831 if((err = gettrackdata(track, 0, 0, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1835 trackdb_abort_transaction(tid);
1837 trackdb_commit_transaction(tid);
1841 /* return the list of tags */
1842 char **trackdb_alltags(void) {
1847 WITH_TRANSACTION(trackdb_listkeys(trackdb_tagsdb, v, tid));
1851 /** @brief List all the keys in @p db
1852 * @param db Database
1853 * @param v Vector to store keys in
1854 * @param tid Transaction ID
1855 * @return 0 or DB_LOCK_DEADLOCK
1857 int trackdb_listkeys(DB *db, struct vector *v, DB_TXN *tid) {
1860 DBC *const c = trackdb_opencursor(db, tid);
1863 memset(&k, 0, sizeof k);
1864 while(!(e = c->c_get(c, &k, prepare_data(&d), DB_NEXT_NODUP)))
1865 vector_append(v, xstrndup(k.data, k.size));
1869 case DB_LOCK_DEADLOCK:
1872 fatal(0, "c->c_get: %s", db_strerror(e));
1874 if((e = trackdb_closecursor(c)))
1876 vector_terminate(v);
1880 /* return 1 iff sorted tag lists A and B have at least one member in common */
1881 int tag_intersection(char **a, char **b) {
1884 /* Same sort of logic as trackdb_set() above */
1886 if(!(cmp = strcmp(*a, *b))) return 1;
1887 else if(cmp < 0) ++a;
1893 static void choose_finished(ev_source *ev, unsigned which) {
1894 choose_complete |= which;
1895 if(choose_complete != (CHOOSE_RUNNING|CHOOSE_READING))
1898 if(choose_status == 0 && choose_output.nvec > 0) {
1899 dynstr_terminate(&choose_output);
1900 choose_callback(ev, xstrdup(choose_output.vec));
1902 choose_callback(ev, 0);
1905 /** @brief Called when @c disorder-choose terminates */
1906 static int choose_exited(ev_source *ev,
1907 pid_t attribute((unused)) pid,
1909 const struct rusage attribute((unused)) *rusage,
1910 void attribute((unused)) *u) {
1912 error(0, "disorder-choose %s", wstat(status));
1913 choose_status = status;
1914 choose_finished(ev, CHOOSE_RUNNING);
1918 /** @brief Called with data from @c disorder-choose pipe */
1919 static int choose_readable(ev_source *ev,
1924 void attribute((unused)) *u) {
1925 dynstr_append_bytes(&choose_output, ptr, bytes);
1926 ev_reader_consume(reader, bytes);
1928 choose_finished(ev, CHOOSE_READING);
1932 static int choose_read_error(ev_source *ev,
1934 void attribute((unused)) *u) {
1935 error(errno_value, "error reading disorder-choose pipe");
1936 choose_finished(ev, CHOOSE_READING);
1940 /** @brief Request a random track
1941 * @param ev Event source
1942 * @param callback Called with random track or NULL
1943 * @return 0 if a request was initiated, else -1
1945 * Initiates a random track choice. @p callback will later be called back with
1946 * the choice (or NULL on error). If a choice is already underway then -1 is
1947 * returned and there will be no additional callback.
1949 * The caller shouldn't assume that the track returned actually exists (it
1950 * might be removed between the choice and the callback, or between being added
1951 * to the queue and being played).
1953 int trackdb_request_random(ev_source *ev,
1954 random_callback *callback) {
1957 if(choose_pid != -1)
1958 return -1; /* don't run concurrent chooses */
1961 choose_pid = subprogram(ev, p[1], "disorder-choose", (char *)0);
1964 choose_callback = callback;
1965 choose_output.nvec = 0;
1966 choose_complete = 0;
1967 if(!ev_reader_new(ev, p[0], choose_readable, choose_read_error, 0,
1968 "disorder-choose reader")) /* owns p[0] */
1969 fatal(0, "ev_reader_new for disorder-choose reader failed");
1970 ev_child(ev, choose_pid, 0, choose_exited, 0); /* owns the subprocess */
1974 /* get a track name given the prefs. Set *used_db to 1 if we got the answer
1975 * from the prefs. */
1976 static const char *getpart(const char *track,
1977 const char *context,
1979 const struct kvp *p,
1984 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
1985 if((result = kvp_get(p, pref)))
1988 result = trackname_part(track, context, part);
1989 assert(result != 0);
1993 /* get a track name part, like trackname_part(), but taking the database into
1995 const char *trackdb_getpart(const char *track,
1996 const char *context,
2004 /* construct the full pref */
2005 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2007 tid = trackdb_begin_transaction();
2008 if((err = gettrackdata(track, 0, &p, &actual, 0, tid)) == DB_LOCK_DEADLOCK)
2012 trackdb_abort_transaction(tid);
2014 trackdb_commit_transaction(tid);
2015 return getpart(actual, context, part, p, &used_db);
2018 /* get the raw path name for @track@ (might be an alias) */
2019 const char *trackdb_rawpath(const char *track) {
2025 tid = trackdb_begin_transaction();
2026 if(gettrackdata(track, &t, 0, 0, 0, tid) == DB_LOCK_DEADLOCK)
2030 trackdb_abort_transaction(tid);
2032 trackdb_commit_transaction(tid);
2033 if(!(path = kvp_get(t, "_path"))) path = track;
2037 /* trackdb_list **************************************************************/
2039 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
2040 * readable at some point */
2042 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
2043 * If RE is a null pointer then it matches everything. */
2044 static int track_matches(size_t dl, const char *track, size_t tl,
2052 switch(rc = pcre_exec(re, 0, track, tl, 0, 0, ovec, 3)) {
2053 case PCRE_ERROR_NOMATCH: return 0;
2056 error(0, "pcre_exec returned %d, subject '%s'", rc, track);
2063 static int do_list(struct vector *v, const char *dir,
2064 enum trackdb_listable what, const pcre *re, DB_TXN *tid) {
2070 size_t l, last_dir_len = 0;
2071 char *last_dir = 0, *track;
2075 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2078 /* find the first key >= dir */
2079 err = cursor->c_get(cursor, &k, &d, DB_SET_RANGE);
2080 /* keep going while we're dealing with <dir/anything> */
2083 && ((char *)k.data)[dl] == '/'
2084 && !memcmp(k.data, dir, dl)) {
2085 ptr = memchr((char *)k.data + dl + 1, '/', k.size - (dl + 1));
2087 /* we have <dir/component/anything>, so <dir/component> is a directory */
2088 l = ptr - (char *)k.data;
2089 if(what & trackdb_directories)
2091 && l == last_dir_len
2092 && !memcmp(last_dir, k.data, l))) {
2093 last_dir = xstrndup(k.data, last_dir_len = l);
2094 if(track_matches(dl, k.data, l, re))
2095 vector_append(v, last_dir);
2098 /* found a plain file */
2099 if((what & trackdb_files)) {
2100 track = xstrndup(k.data, k.size);
2101 if((err = trackdb_getdata(trackdb_prefsdb,
2102 track, &p, tid)) == DB_LOCK_DEADLOCK)
2104 /* There's an awkward question here...
2106 * If a track shares a directory with its alias then we could
2107 * do one of three things:
2108 * - report both. Looks ridiculuous in most UIs.
2109 * - report just the alias. Remarkably inconvenient to write
2111 * - report just the real name. Ugly if the UI doesn't prettify
2112 * names via the name parts.
2115 /* If this file is an alias for a track in the same directory then we
2117 struct kvp *t = kvp_urldecode(d.data, d.size);
2118 const char *alias_target = kvp_get(t, "_alias_for");
2120 && !strcmp(d_dirname(alias_target),
2122 if(track_matches(dl, k.data, k.size, re))
2123 vector_append(v, track);
2125 /* if this file has an alias in the same directory then we skip it */
2127 if((err = compute_alias(&alias, track, p, tid)))
2129 if(!(alias && !strcmp(d_dirname(alias), d_dirname(track))))
2130 if(track_matches(dl, k.data, k.size, re))
2131 vector_append(v, track);
2135 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2143 case DB_LOCK_DEADLOCK:
2144 error(0, "error querying database: %s", db_strerror(err));
2147 fatal(0, "error querying database: %s", db_strerror(err));
2150 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2154 /* return the directories or files below @dir@ */
2155 char **trackdb_list(const char *dir, int *np, enum trackdb_listable what,
2163 tid = trackdb_begin_transaction();
2166 if(do_list(&v, dir, what, re, tid))
2169 for(n = 0; n < config->collection.n; ++n)
2170 if(do_list(&v, config->collection.s[n].root, what, re, tid))
2175 trackdb_abort_transaction(tid);
2177 trackdb_commit_transaction(tid);
2178 vector_terminate(&v);
2184 /* If S is tag:something, return something. Else return 0. */
2185 static const char *checktag(const char *s) {
2186 if(!strncmp(s, "tag:", 4))
2192 /* return a list of tracks containing all of the words given. If you
2193 * ask for only stopwords you get no tracks. */
2194 char **trackdb_search(char **wordlist, int nwordlist, int *ntracks) {
2195 const char **w, *best = 0, *tag;
2196 char **twords, **tags;
2198 int i, j, n, err, what;
2208 *ntracks = 0; /* for early returns */
2209 /* normalize all the words */
2210 w = xmalloc(nwordlist * sizeof (char *));
2211 istag = xmalloc_noptr(nwordlist);
2212 for(n = 0; n < nwordlist; ++n) {
2216 w[n] = utf8_casefold_compat(wordlist[n], strlen(wordlist[n]), 0);
2217 if(checktag(w[n])) {
2218 ++ntags; /* count up tags */
2219 /* Normalize the tag */
2220 w[n] = normalize_tag(w[n] + 4, strlen(w[n] + 4));
2223 /* Normalize the search term by removing combining characters */
2224 if(!(w32 = utf8_to_utf32(w[n], strlen(w[n]), &nw32)))
2226 nw32 = remove_combining_chars(w32, nw32);
2227 if(!(w[n] = utf32_to_utf8(w32, nw32, 0)))
2232 /* find the longest non-stopword */
2233 for(n = 0; n < nwordlist; ++n)
2234 if(!istag[n] && !stopword(w[n]))
2235 if(!best || strlen(w[n]) > strlen(best))
2237 /* TODO: we should at least in principal be able to identify the word or tag
2238 * with the least matches in log time, and choose that as our primary search
2240 if(ntags && !best) {
2241 /* Only tags are listed. We limit to the first and narrow down with the
2243 best = istag[0] ? w[0] : 0;
2244 db = trackdb_tagsdb;
2247 /* We can limit to some word. */
2248 db = trackdb_searchdb;
2251 /* Only stopwords */
2257 tid = trackdb_begin_transaction();
2258 /* find all the tracks that have that word */
2263 cursor = trackdb_opencursor(db, tid);
2264 while(!(err = cursor->c_get(cursor, &k, &d, what))) {
2265 vector_append(&v, xstrndup(d.data, d.size));
2272 case DB_LOCK_DEADLOCK:
2273 error(0, "error querying %s database: %s", dbname, db_strerror(err));
2276 fatal(0, "error querying %s database: %s", dbname, db_strerror(err));
2278 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2280 /* do a naive search over that (hopefuly fairly small) list of tracks */
2282 for(n = 0; n < v.nvec; ++n) {
2283 if((err = gettrackdata(v.vec[n], 0, &p, 0, 0, tid) == DB_LOCK_DEADLOCK))
2286 error(0, "track %s unexpected error: %s", v.vec[n], db_strerror(err));
2289 twords = track_to_words(v.vec[n], p);
2290 tags = parsetags(kvp_get(p, "tags"));
2291 for(i = 0; i < nwordlist; ++i) {
2294 /* Track must have this tag */
2295 for(j = 0; tags[j]; ++j)
2296 if(!strcmp(tag, tags[j])) break; /* tag found */
2297 if(!tags[j]) break; /* tag not found */
2299 /* Track must contain this word */
2300 for(j = 0; twords[j]; ++j)
2301 if(!strcmp(w[i], twords[j])) break; /* word found */
2302 if(!twords[j]) break; /* word not found */
2305 if(i >= nwordlist) /* all words found */
2306 vector_append(&u, v.vec[n]);
2310 trackdb_closecursor(cursor);
2312 trackdb_abort_transaction(tid);
2313 info("retrying search");
2315 trackdb_commit_transaction(tid);
2316 vector_terminate(&u);
2322 /* trackdb_scan **************************************************************/
2324 int trackdb_scan(const char *root,
2325 int (*callback)(const char *track,
2334 const size_t root_len = root ? strlen(root) : 0;
2336 struct kvp *data, *prefs;
2339 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2341 err = cursor->c_get(cursor, make_key(&k, root), prepare_data(&d),
2344 memset(&k, 0, sizeof k);
2345 err = cursor->c_get(cursor, &k, prepare_data(&d),
2350 || (k.size > root_len
2351 && !strncmp(k.data, root, root_len)
2352 && ((char *)k.data)[root_len] == '/')) {
2353 data = kvp_urldecode(d.data, d.size);
2354 if(kvp_get(data, "_path")) {
2355 track = xstrndup(k.data, k.size);
2356 /* TODO: trackdb_prefsdb is currently a DB_HASH. This means we have to
2357 * do a lookup for every single track. In fact this is quite quick:
2358 * with around 10,000 tracks a complete scan is around 0.3s on my
2359 * 2.2GHz Athlon. However, if it were a DB_BTREE, we could do the same
2360 * linear walk as we already do over trackdb_tracksdb, and probably get
2361 * even higher performance. That would require upgrade logic to
2362 * translate old databases though.
2364 switch(err = trackdb_prefsdb->get(trackdb_prefsdb, tid, &k,
2365 prepare_data(&pd), 0)) {
2367 prefs = kvp_urldecode(pd.data, pd.size);
2372 case DB_LOCK_DEADLOCK:
2373 error(0, "getting prefs: %s", db_strerror(err));
2374 trackdb_closecursor(cursor);
2377 fatal(0, "getting prefs: %s", db_strerror(err));
2379 /* Advance to the next track before the callback so that the callback
2380 * may safely delete the track */
2381 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2382 if((cberr = callback(track, data, prefs, u, tid))) {
2387 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2391 trackdb_closecursor(cursor);
2398 case DB_LOCK_DEADLOCK:
2399 error(0, "c->c_get: %s", db_strerror(err));
2402 fatal(0, "c->c_get: %s", db_strerror(err));
2406 /* trackdb_rescan ************************************************************/
2408 /** @brief Node in the list of rescan-complete callbacks */
2409 struct rescanned_node {
2410 struct rescanned_node *next;
2411 void (*rescanned)(void *ru);
2415 /** @brief List of rescan-complete callbacks */
2416 static struct rescanned_node *rescanned_list;
2418 /** @brief Add a rescan completion callback */
2419 void trackdb_add_rescanned(void (*rescanned)(void *ru),
2422 struct rescanned_node *n = xmalloc(sizeof *n);
2423 n->next = rescanned_list;
2424 n->rescanned = rescanned;
2430 /* called when the rescanner terminates */
2431 static int reap_rescan(ev_source attribute((unused)) *ev,
2434 const struct rusage attribute((unused)) *rusage,
2435 void attribute((unused)) *u) {
2436 if(pid == rescan_pid) rescan_pid = -1;
2438 error(0, RESCAN": %s", wstat(status));
2440 D((RESCAN" terminated: %s", wstat(status)));
2441 /* Our cache of file lookups is out of date now */
2442 cache_clean(&cache_files_type);
2443 eventlog("rescanned", (char *)0);
2444 /* Call rescanned callbacks */
2445 while(rescanned_list) {
2446 void (*rescanned)(void *u_) = rescanned_list->rescanned;
2447 void *ru = rescanned_list->ru;
2449 rescanned_list = rescanned_list->next;
2455 /** @brief Initiate a rescan
2456 * @param ev Event loop or 0 to block
2457 * @param recheck 1 to recheck lengths, 0 to suppress check
2458 * @param rescanned Called on completion (if not NULL)
2459 * @param ru Passed to @p rescanned
2461 void trackdb_rescan(ev_source *ev, int recheck,
2462 void (*rescanned)(void *ru),
2466 if(rescan_pid != -1) {
2467 trackdb_add_rescanned(rescanned, ru);
2468 error(0, "rescan already underway");
2471 rescan_pid = subprogram(ev, -1, RESCAN,
2472 recheck ? "--check" : "--no-check",
2474 trackdb_add_rescanned(rescanned, ru);
2476 ev_child(ev, rescan_pid, 0, reap_rescan, 0);
2477 D(("started rescanner"));
2479 /* This is the first rescan, we block until it is complete */
2480 while(waitpid(rescan_pid, &w, 0) < 0 && errno == EINTR)
2482 reap_rescan(0, rescan_pid, w, 0, 0);
2486 int trackdb_rescan_cancel(void) {
2487 if(rescan_pid == -1) return 0;
2488 if(kill(rescan_pid, SIGTERM) < 0)
2489 fatal(errno, "error killing rescanner");
2494 /** @brief Return true if a rescan is underway */
2495 int trackdb_rescan_underway(void) {
2496 return rescan_pid != -1;
2499 /* global prefs **************************************************************/
2501 void trackdb_set_global(const char *name,
2509 tid = trackdb_begin_transaction();
2510 if(!(err = trackdb_set_global_tid(name, value, tid)))
2512 trackdb_abort_transaction(tid);
2514 trackdb_commit_transaction(tid);
2515 /* log important state changes */
2516 if(!strcmp(name, "playing")) {
2517 state = !value || !strcmp(value, "yes");
2518 info("playing %s by %s",
2519 state ? "enabled" : "disabled",
2521 eventlog("state", state ? "enable_play" : "disable_play", (char *)0);
2523 if(!strcmp(name, "random-play")) {
2524 state = !value || !strcmp(value, "yes");
2525 info("random play %s by %s",
2526 state ? "enabled" : "disabled",
2528 eventlog("state", state ? "enable_random" : "disable_random", (char *)0);
2532 int trackdb_set_global_tid(const char *name,
2538 memset(&k, 0, sizeof k);
2539 memset(&d, 0, sizeof d);
2540 k.data = (void *)name;
2541 k.size = strlen(name);
2543 d.data = (void *)value;
2544 d.size = strlen(value);
2547 err = trackdb_globaldb->put(trackdb_globaldb, tid, &k, &d, 0);
2549 err = trackdb_globaldb->del(trackdb_globaldb, tid, &k, 0);
2550 if(err == DB_LOCK_DEADLOCK) return err;
2552 fatal(0, "error updating database: %s", db_strerror(err));
2556 const char *trackdb_get_global(const char *name) {
2562 tid = trackdb_begin_transaction();
2563 if(!(err = trackdb_get_global_tid(name, tid, &r)))
2565 trackdb_abort_transaction(tid);
2567 trackdb_commit_transaction(tid);
2571 int trackdb_get_global_tid(const char *name,
2577 memset(&k, 0, sizeof k);
2578 k.data = (void *)name;
2579 k.size = strlen(name);
2580 switch(err = trackdb_globaldb->get(trackdb_globaldb, tid, &k,
2581 prepare_data(&d), 0)) {
2583 *rp = xstrndup(d.data, d.size);
2588 case DB_LOCK_DEADLOCK:
2591 fatal(0, "error reading database: %s", db_strerror(err));
2595 /** @brief Retrieve the most recently added tracks
2596 * @param ntracksp Where to put count, or 0
2597 * @param maxtracks Maximum number of tracks to retrieve
2598 * @return null-terminated array of track names
2600 * The most recently added track is first in the array.
2602 char **trackdb_new(int *ntracksp,
2608 tid = trackdb_begin_transaction();
2609 tracks = trackdb_new_tid(ntracksp, maxtracks, tid);
2612 trackdb_abort_transaction(tid);
2614 trackdb_commit_transaction(tid);
2618 /** @brief Retrieve the most recently added tracks
2619 * @param ntracksp Where to put count, or 0
2620 * @param maxtracks Maximum number of tracks to retrieve, or 0 for all
2621 * @param tid Transaction ID
2622 * @return null-terminated array of track names, or NULL on deadlock
2624 * The most recently added track is first in the array.
2626 static char **trackdb_new_tid(int *ntracksp,
2632 struct vector tracks[1];
2633 hash *h = hash_new(1);
2635 vector_init(tracks);
2636 c = trackdb_opencursor(trackdb_noticeddb, tid);
2637 while((maxtracks <= 0 || tracks->nvec < maxtracks)
2638 && !(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_PREV))) {
2639 char *const track = xstrndup(d.data, d.size);
2640 /* Don't add any track more than once */
2641 if(hash_add(h, track, "", HASH_INSERT))
2643 /* See if the track still exists */
2644 err = trackdb_getdata(trackdb_tracksdb, track, NULL/*kp*/, tid);
2645 if(err == DB_NOTFOUND)
2646 continue; /* It doesn't, skip it */
2647 if(err == DB_LOCK_DEADLOCK)
2649 vector_append(tracks, track);
2652 case 0: /* hit maxtracks */
2653 case DB_NOTFOUND: /* ran out of tracks */
2655 case DB_LOCK_DEADLOCK:
2656 trackdb_closecursor(c);
2659 fatal(0, "error reading noticed.db: %s", db_strerror(err));
2661 if((err = trackdb_closecursor(c)))
2662 return 0; /* deadlock */
2663 vector_terminate(tracks);
2665 *ntracksp = tracks->nvec;
2669 /** @brief Expire noticed.db
2670 * @param earliest Earliest timestamp to keep
2672 void trackdb_expire_noticed(time_t earliest) {
2676 tid = trackdb_begin_transaction();
2677 if(!trackdb_expire_noticed_tid(earliest, tid))
2679 trackdb_abort_transaction(tid);
2681 trackdb_commit_transaction(tid);
2684 /** @brief Expire noticed.db
2685 * @param earliest Earliest timestamp to keep
2686 * @param tid Transaction ID
2687 * @return 0 or DB_LOCK_DEADLOCK
2689 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid) {
2697 c = trackdb_opencursor(trackdb_noticeddb, tid);
2698 while(!(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_NEXT))) {
2700 when = (time_t)(((uint64_t)ntohl(kk[0]) << 32) + ntohl(kk[1]));
2701 if(when >= earliest)
2703 if((err = c->c_del(c, 0))) {
2704 if(err != DB_LOCK_DEADLOCK)
2705 fatal(0, "error deleting expired noticed.db entry: %s",
2711 if(err == DB_NOTFOUND)
2713 if(err && err != DB_LOCK_DEADLOCK)
2714 fatal(0, "error expiring noticed.db: %s", db_strerror(err));
2716 if((err = trackdb_closecursor(c))) {
2717 if(err != DB_LOCK_DEADLOCK)
2718 fatal(0, "error closing cursor: %s", db_strerror(err));
2722 info("expired %d tracks from noticed.db", count);
2726 /* tidying up ****************************************************************/
2728 void trackdb_gc(void) {
2732 if((err = trackdb_env->txn_checkpoint(trackdb_env,
2733 config->checkpoint_kbyte,
2734 config->checkpoint_min,
2736 fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err));
2737 if((err = trackdb_env->log_archive(trackdb_env, &logfiles, DB_ARCH_REMOVE)))
2738 fatal(0, "trackdb_env->log_archive: %s", db_strerror(err));
2739 /* This makes catastrophic recovery impossible. However, the user can still
2740 * preserve the important data by using disorder-dump to snapshot their
2741 * prefs, and later to restore it. This is likely to have much small
2742 * long-term storage requirements than record the db logfiles. */
2745 /* user database *************************************************************/
2747 /** @brief Return true if @p user is trusted */
2748 static int trusted(const char *user) {
2751 for(n = 0; (n < config->trust.n
2752 && strcmp(config->trust.s[n], user)); ++n)
2754 return n < config->trust.n;
2757 /** @brief Return non-zero for a valid username
2759 * Currently we only allow the letters and digits in ASCII. We could be more
2760 * liberal than this but it is a nice simple test. It is critical that
2761 * semicolons are never allowed.
2763 * NB also used by playlist_parse_name() to validate playlist names!
2765 int valid_username(const char *user) {
2769 const uint8_t c = *user++;
2770 /* For now we are very strict */
2771 if((c >= 'a' && c <= 'z')
2772 || (c >= 'A' && c <= 'Z')
2773 || (c >= '0' && c <= '9'))
2781 /** @brief Add a user */
2782 static int create_user(const char *user,
2783 const char *password,
2786 const char *confirmation,
2792 /* sanity check user */
2793 if(!valid_username(user)) {
2794 error(0, "invalid username '%s'", user);
2797 if(parse_rights(rights, 0, 1)) {
2798 error(0, "invalid rights string");
2801 /* data for this user */
2803 kvp_set(&k, "password", password);
2804 kvp_set(&k, "rights", rights);
2806 kvp_set(&k, "email", email);
2808 kvp_set(&k, "confirmation", confirmation);
2809 snprintf(s, sizeof s, "%jd", (intmax_t)xtime(0));
2810 kvp_set(&k, "created", s);
2811 return trackdb_putdata(trackdb_usersdb, user, k, tid, flags);
2814 /** @brief Add one pre-existing user */
2815 static int one_old_user(const char *user, const char *password,
2819 /* www-data doesn't get added */
2820 if(!strcmp(user, "www-data")) {
2821 info("not adding www-data to user database");
2825 if(!strcmp(user, "root"))
2827 else if(trusted(user)) {
2830 parse_rights(config->default_rights, &r, 1);
2831 r &= ~(rights_type)(RIGHT_SCRATCH__MASK|RIGHT_MOVE__MASK|RIGHT_REMOVE__MASK);
2832 r |= (RIGHT_ADMIN|RIGHT_RESCAN
2833 |RIGHT_SCRATCH_ANY|RIGHT_MOVE_ANY|RIGHT_REMOVE_ANY);
2834 rights = rights_string(r);
2836 rights = config->default_rights;
2837 return create_user(user, password, rights, 0/*email*/, 0/*confirmation*/,
2838 tid, DB_NOOVERWRITE);
2841 static int trackdb_old_users_tid(DB_TXN *tid) {
2844 for(n = 0; n < config->allow.n; ++n) {
2845 switch(one_old_user(config->allow.s[n].s[0], config->allow.s[n].s[1],
2848 info("created user %s from 'allow' directive", config->allow.s[n].s[0]);
2851 error(0, "user %s already exists, delete 'allow' directive",
2852 config->allow.s[n].s[0]);
2853 /* This won't ever become fatal - eventually 'allow' will be
2856 case DB_LOCK_DEADLOCK:
2857 return DB_LOCK_DEADLOCK;
2863 /** @brief Read old 'allow' directives and copy them to the users database */
2864 void trackdb_old_users(void) {
2868 WITH_TRANSACTION(trackdb_old_users_tid(tid));
2871 /** @brief Create a root user in the user database if there is none */
2872 void trackdb_create_root(void) {
2877 /* Choose a new root password */
2878 gcry_randomize(pwbin, sizeof pwbin, GCRY_STRONG_RANDOM);
2879 pw = mime_to_base64(pwbin, sizeof pwbin);
2880 /* Create the root user if it does not exist */
2881 WITH_TRANSACTION(create_user("root", pw, "all",
2882 0/*email*/, 0/*confirmation*/,
2883 tid, DB_NOOVERWRITE));
2885 info("created root user");
2888 /** @brief Find a user's password from the database
2889 * @param user Username
2890 * @return Password or NULL
2892 * Only works if running as a user that can read the database!
2894 * If the user exists but has no password, "" is returned.
2896 const char *trackdb_get_password(const char *user) {
2899 const char *password;
2901 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
2904 password = kvp_get(k, "password");
2905 return password ? password : "";
2908 /** @brief Add a new user
2909 * @param user Username
2910 * @param password Password or NULL
2911 * @param rights Initial rights
2912 * @param email Email address or NULL
2913 * @param confirmation Confirmation string or NULL
2914 * @return 0 on success, non-0 on error
2916 int trackdb_adduser(const char *user,
2917 const char *password,
2920 const char *confirmation) {
2923 WITH_TRANSACTION(create_user(user, password, rights, email, confirmation,
2924 tid, DB_NOOVERWRITE));
2926 error(0, "cannot create user '%s' because they already exist", user);
2930 info("created user '%s' with rights '%s' and email address '%s'",
2931 user, rights, email);
2933 info("created user '%s' with rights '%s'", user, rights);
2934 eventlog("user_add", user, (char *)0);
2939 /** @brief Delete a user
2940 * @param user User to delete
2941 * @return 0 on success, non-0 if the user didn't exist anyway
2943 int trackdb_deluser(const char *user) {
2946 WITH_TRANSACTION(trackdb_delkey(trackdb_usersdb, user, tid));
2948 error(0, "cannot delete user '%s' because they do not exist", user);
2951 info("deleted user '%s'", user);
2952 eventlog("user_delete", user, (char *)0);
2956 /** @brief Get user information
2957 * @param user User to query
2958 * @return Linked list of user information or NULL if user does not exist
2960 * Every user has at least a @c rights entry so NULL can be used to mean no
2963 struct kvp *trackdb_getuserinfo(const char *user) {
2967 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
2974 /** @brief Edit user information
2975 * @param user User to edit
2976 * @param key Key to change
2977 * @param value Value to set, or NULL to remove
2978 * @param tid Transaction ID
2979 * @return 0, DB_LOCK_DEADLOCK or DB_NOTFOUND
2981 static int trackdb_edituserinfo_tid(const char *user, const char *key,
2982 const char *value, DB_TXN *tid) {
2986 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
2988 if(!kvp_set(&k, key, value))
2989 return 0; /* no change */
2990 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
2993 /** @brief Edit user information
2994 * @param user User to edit
2995 * @param key Key to change
2996 * @param value Value to set, or NULL to remove
2997 * @return 0 on success, non-0 on error
2999 int trackdb_edituserinfo(const char *user,
3000 const char *key, const char *value) {
3003 if(!strcmp(key, "rights")) {
3005 error(0, "cannot remove 'rights' key from user '%s'", user);
3008 if(parse_rights(value, 0, 1)) {
3009 error(0, "invalid rights string");
3012 } else if(!strcmp(key, "email")) {
3014 if(!email_valid(value)) {
3015 error(0, "invalid email address '%s' for user '%s'", value, user);
3019 value = 0; /* no email -> remove key */
3020 } else if(!strcmp(key, "created")) {
3021 error(0, "cannot change creation date for user '%s'", user);
3023 } else if(strcmp(key, "password")
3024 && !strcmp(key, "confirmation")) {
3025 error(0, "unknown user info key '%s' for user '%s'", key, user);
3028 WITH_TRANSACTION(trackdb_edituserinfo_tid(user, key, value, tid));
3030 error(0, "unknown user '%s'", user);
3033 eventlog("user_edit", user, key, (char *)0);
3038 /** @brief List all users
3039 * @return NULL-terminated list of users
3041 char **trackdb_listusers(void) {
3046 WITH_TRANSACTION(trackdb_listkeys(trackdb_usersdb, v, tid));
3050 /** @brief Confirm a user registration
3051 * @param user Username
3052 * @param confirmation Confirmation string
3053 * @param rightsp Where to put user rights
3054 * @param tid Transaction ID
3055 * @return 0 on success, non-0 on error
3057 static int trackdb_confirm_tid(const char *user, const char *confirmation,
3058 rights_type *rightsp,
3060 const char *stored_confirmation;
3065 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3067 if(!(stored_confirmation = kvp_get(k, "confirmation"))) {
3068 error(0, "already confirmed user '%s'", user);
3069 /* DB claims -30,800 to -30,999 so -1 should be a safe bet */
3072 if(!(rights = kvp_get(k, "rights"))) {
3073 error(0, "no rights for unconfirmed user '%s'", user);
3076 if(parse_rights(rights, rightsp, 1))
3078 if(strcmp(confirmation, stored_confirmation)) {
3079 error(0, "wrong confirmation string for user '%s'", user);
3083 kvp_set(&k, "confirmation", 0);
3084 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3087 /** @brief Confirm a user registration
3088 * @param user Username
3089 * @param confirmation Confirmation string
3090 * @param rightsp Where to put user rights
3091 * @return 0 on success, non-0 on error
3093 int trackdb_confirm(const char *user, const char *confirmation,
3094 rights_type *rightsp) {
3097 WITH_TRANSACTION(trackdb_confirm_tid(user, confirmation, rightsp, tid));
3100 info("registration confirmed for user '%s'", user);
3101 eventlog("user_confirm", user, (char *)0);
3104 error(0, "confirmation for nonexistent user '%s'", user);
3106 default: /* already reported */
3116 indent-tabs-mode:nil