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 /** @brief Compute an alias
1106 * @param aliasp Where to put alias (gets NULL if none)
1107 * @param track Track to find alias for
1108 * @param p Prefs for @p track
1109 * @param tid Owning transaction
1110 * @return 0 or DB_LOCK_DEADLOCK
1112 * This function looks up the track name parts for @p track. By default these
1113 * amount to the original values from the track name but are overridden by
1116 * These values are then substituted into the pattern defined by the @b alias
1117 * command; see disorder_config(5) for the syntax.
1119 * The track is only considered to have an alias if all of the following are
1121 * - a preference was used for at least one name part
1122 * - the result differs from the original track name
1123 * - the result does not match any existing track or alias
1125 static int compute_alias(char **aliasp,
1127 const struct kvp *p,
1130 const char *s = config->alias, *t, *expansion, *part;
1131 int c, used_db = 0, slash_prefix, err;
1133 const char *const root = find_track_root(track);
1136 /* Bodge for tracks with no root */
1141 dynstr_append_string(&d, root);
1142 while((c = (unsigned char)*s++)) {
1144 dynstr_append(&d, c);
1147 if((slash_prefix = (*s == '/')))
1150 assert(t != 0); /* validated at startup */
1151 part = xstrndup(s, t - s);
1152 expansion = getpart(track, "display", part, p, &used_db);
1154 if(slash_prefix) dynstr_append(&d, '/');
1155 dynstr_append_string(&d, expansion);
1157 s = t + 1; /* skip {part} */
1159 /* only admit to the alias if we used the db... */
1164 dynstr_terminate(&d);
1165 /* ...and the answer differs from the original... */
1166 if(!strcmp(track, d.vec)) {
1170 /* ...and there isn't already a different track with that name (including as
1172 switch(err = trackdb_getdata(trackdb_tracksdb, d.vec, &at, tid)) {
1174 if((s = kvp_get(at, "_alias_for"))
1175 && !strcmp(s, track)) {
1187 /** @brief Assert that no alias is allowed for gettrackdata() */
1188 #define GTD_NOALIAS 0x0001
1190 /** @brief Get all track data
1191 * @param track Track to look up; aliases allowed unless @ref GTD_NOALIAS
1192 * @param tp Where to put track data (if not NULL)
1193 * @param pp Where to put preferences (if not NULL)
1194 * @param actualp Where to put real (i.e. non-alias) path (if not NULL)
1195 * @param flags Flag values, see below
1196 * @param tid Owning transaction
1197 * @return 0, DB_NOTFOUND (track doesn't exist) or DB_LOCK_DEADLOCK
1199 * Possible flags values are:
1200 * - @ref GTD_NOALIAS to assert that an alias is not allowed
1202 * The return values are always set (even if to NULL).
1204 static int gettrackdata(const char *track,
1207 const char **actualp,
1211 const char *actual = track;
1212 struct kvp *t = 0, *p = 0;
1214 if((err = trackdb_getdata(trackdb_tracksdb, track, &t, tid))) goto done;
1215 if((actual = kvp_get(t, "_alias_for"))) {
1216 if(flags & GTD_NOALIAS) {
1217 error(0, "alias passed to gettrackdata where real path required");
1220 if((err = trackdb_getdata(trackdb_tracksdb, actual, &t, tid))) goto done;
1223 assert(actual != 0);
1225 if((err = trackdb_getdata(trackdb_prefsdb, actual, &p, tid)) == DB_LOCK_DEADLOCK)
1230 if(actualp) *actualp = actual;
1236 /* trackdb_notice() **********************************************************/
1238 /** @brief Notice a possibly new track
1239 * @param track NFC UTF-8 track name
1240 * @param path Raw path name (i.e. the bytes that came out of readdir())
1241 * @return @c DB_NOTFOUND if new, 0 if already known
1243 * @c disorder-rescan is responsible for normalizing the track name.
1245 int trackdb_notice(const char *track,
1251 tid = trackdb_begin_transaction();
1252 err = trackdb_notice_tid(track, path, tid);
1253 if((err == DB_LOCK_DEADLOCK)) goto fail;
1256 trackdb_abort_transaction(tid);
1258 trackdb_commit_transaction(tid);
1262 /** @brief Notice a possibly new track
1263 * @param track NFC UTF-8 track name
1264 * @param path Raw path name (i.e. the bytes that came out of readdir())
1265 * @param tid Owning transaction
1266 * @return @c DB_NOTFOUND if new, 0 if already known, @c DB_LOCK_DEADLOCK also
1268 * @c disorder-rescan is responsible for normalizing the track name.
1270 int trackdb_notice_tid(const char *track,
1274 struct kvp *t, *a, *p;
1276 char *alias, **w, *noticed;
1279 /* notice whether the tracks.db entry changes */
1281 /* get any existing tracks entry */
1282 if((err = gettrackdata(track, &t, &p, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1284 ret = err; /* 0 or DB_NOTFOUND */
1285 /* this is a real track */
1286 t_changed += kvp_set(&t, "_alias_for", 0);
1287 t_changed += kvp_set(&t, "_path", path);
1289 if(ret == DB_NOTFOUND) {
1290 /* It's a new track; record the time */
1291 byte_xasprintf(¬iced, "%lld", (long long)now);
1292 t_changed += kvp_set(&t, "_noticed", noticed);
1294 /* if we have an alias record it in the database */
1295 if((err = compute_alias(&alias, track, p, tid))) return err;
1297 /* won't overwrite someone else's alias as compute_alias() checks */
1298 D(("%s: alias %s", track, alias));
1300 kvp_set(&a, "_alias_for", track);
1301 if((err = trackdb_putdata(trackdb_tracksdb, alias, a, tid, 0))) return err;
1303 /* update search.db */
1304 w = track_to_words(track, p);
1305 for(n = 0; w[n]; ++n)
1306 if((err = register_search_word(track, w[n], tid)))
1308 /* update tags.db */
1309 w = parsetags(kvp_get(p, "tags"));
1310 for(n = 0; w[n]; ++n)
1311 if((err = register_tag(track, w[n], tid)))
1313 /* only store the tracks.db entry if it has changed */
1314 if(t_changed && (err = trackdb_putdata(trackdb_tracksdb, track, t, tid, 0)))
1316 if(ret == DB_NOTFOUND) {
1317 uint32_t timestamp[2];
1320 timestamp[0] = htonl((uint64_t)now >> 32);
1321 timestamp[1] = htonl((uint32_t)now);
1322 memset(&key, 0, sizeof key);
1323 key.data = timestamp;
1324 key.size = sizeof timestamp;
1325 switch(err = trackdb_noticeddb->put(trackdb_noticeddb, tid, &key,
1326 make_key(&data, track), 0)) {
1328 case DB_LOCK_DEADLOCK: return err;
1329 default: fatal(0, "error updating noticed.db: %s", db_strerror(err));
1335 /* trackdb_obsolete() ********************************************************/
1337 /** @brief Obsolete a track
1338 * @param track Track name
1339 * @param tid Owning transaction
1340 * @return 0 or DB_LOCK_DEADLOCK
1342 * Discards a track from the database when it's known not to exist any more.
1343 * Returns 0 even if it wasn't recorded.
1345 int trackdb_obsolete(const char *track, DB_TXN *tid) {
1350 if((err = gettrackdata(track, 0, &p, 0,
1351 GTD_NOALIAS, tid)) == DB_LOCK_DEADLOCK)
1353 else if(err == DB_NOTFOUND) return 0;
1354 /* compute the alias, if any, and delete it */
1355 if((err = compute_alias(&alias, track, p, tid))) return err;
1357 /* if the alias points to some other track then compute_alias won't
1359 if((err = trackdb_delkey(trackdb_tracksdb, alias, tid))
1360 && err != DB_NOTFOUND)
1363 /* update search.db */
1364 w = track_to_words(track, p);
1365 for(n = 0; w[n]; ++n)
1366 if(trackdb_delkeydata(trackdb_searchdb,
1367 w[n], track, tid) == DB_LOCK_DEADLOCK)
1369 /* update tags.db */
1370 w = parsetags(kvp_get(p, "tags"));
1371 for(n = 0; w[n]; ++n)
1372 if(trackdb_delkeydata(trackdb_tagsdb,
1373 w[n], track, tid) == DB_LOCK_DEADLOCK)
1375 /* update tracks.db */
1376 if(trackdb_delkey(trackdb_tracksdb, track, tid) == DB_LOCK_DEADLOCK)
1378 /* We don't delete the prefs, so they survive temporary outages of the
1379 * (possibly virtual) track filesystem */
1383 /* trackdb_stats() ***********************************************************/
1385 #define H(name) { #name, offsetof(DB_HASH_STAT, name) }
1386 #define B(name) { #name, offsetof(DB_BTREE_STAT, name) }
1388 static const struct statinfo {
1391 } statinfo_hash[] = {
1407 }, statinfo_btree[] = {
1428 /** @brief Look up DB statistics
1429 * @param v Where to store stats
1430 * @param database Database
1431 * @param si Pointer to table of stats
1432 * @param nsi Size of @p si
1433 * @param tid Owning transaction
1434 * @return 0 or DB_LOCK_DEADLOCK
1436 static int get_stats(struct vector *v,
1438 const struct statinfo *si,
1447 switch(err = database->stat(database, tid, &sp, 0)) {
1450 case DB_LOCK_DEADLOCK:
1451 error(0, "error querying database: %s", db_strerror(err));
1454 fatal(0, "error querying database: %s", db_strerror(err));
1456 for(n = 0; n < nsi; ++n) {
1457 byte_xasprintf(&str, "%s=%"PRIuMAX, si[n].name,
1458 (uintmax_t)*(u_int32_t *)((char *)sp + si[n].offset));
1459 vector_append(v, str);
1465 /** @brief One entry in the search league */
1466 struct search_entry {
1471 /** @brief Add a word to the search league
1472 * @param se Pointer to search league
1473 * @param count Maximum size for search league
1474 * @param nse Current size of search league
1475 * @param word New word, or NULL
1476 * @param n How often @p word appears
1477 * @return New size of search league
1479 static int register_search_entry(struct search_entry *se,
1486 if(word && (nse < count || n > se[nse - 1].n)) {
1487 /* Find the starting point */
1492 /* Find the insertion point */
1493 while(i > 0 && n > se[i - 1].n)
1495 memmove(&se[i + 1], &se[i], (nse - i - 1) * sizeof *se);
1502 /** @brief Find the top @p count words in the search database
1503 * @param v Where to format the result
1504 * @param count Maximum number of words
1505 * @param tid Owning transaction
1506 * @return 0 or DB_LOCK_DEADLOCK
1508 static int search_league(struct vector *v, int count, DB_TXN *tid) {
1509 struct search_entry *se;
1512 int err, n = 0, nse = 0, i;
1517 cursor = trackdb_opencursor(trackdb_searchdb, tid);
1518 se = xmalloc(count * sizeof *se);
1519 /* Walk across the whole database counting up the number of times each
1521 while(!(err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
1523 if(word && wl == k.size && !strncmp(word, k.data, wl))
1524 ++n; /* same word again */
1526 nse = register_search_entry(se, count, nse, word, n);
1527 word = xstrndup(k.data, wl = k.size);
1535 case DB_LOCK_DEADLOCK:
1536 error(0, "error querying search database: %s", db_strerror(err));
1539 fatal(0, "error querying search database: %s", db_strerror(err));
1541 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1543 nse = register_search_entry(se, count, nse, word, n);
1544 byte_xasprintf(&str, "Top %d search words:", nse);
1545 vector_append(v, str);
1546 for(i = 0; i < nse; ++i) {
1547 byte_xasprintf(&str, "%4d: %5d %s", i + 1, se[i].n, se[i].word);
1548 vector_append(v, str);
1553 #define SI(what) statinfo_##what, \
1554 sizeof statinfo_##what / sizeof (struct statinfo)
1556 /** @brief Return a list of database stats
1557 * @param nstatsp Where to store number of lines (or NULL)
1558 * @return Database stats output
1560 * This is called by @c disorder-stats. Don't call it directly from elsewhere
1561 * as it can take unreasonably long.
1563 char **trackdb_stats(int *nstatsp) {
1569 tid = trackdb_begin_transaction();
1571 vector_append(&v, (char *)"Tracks database stats:");
1572 if(get_stats(&v, trackdb_tracksdb, SI(btree), tid)) goto fail;
1573 vector_append(&v, (char *)"");
1574 vector_append(&v, (char *)"Search database stats:");
1575 if(get_stats(&v, trackdb_searchdb, SI(hash), tid)) goto fail;
1576 vector_append(&v, (char *)"");
1577 vector_append(&v, (char *)"Prefs database stats:");
1578 if(get_stats(&v, trackdb_prefsdb, SI(hash), tid)) goto fail;
1579 vector_append(&v, (char *)"");
1580 if(search_league(&v, 10, tid)) goto fail;
1581 vector_terminate(&v);
1584 trackdb_abort_transaction(tid);
1586 trackdb_commit_transaction(tid);
1587 if(nstatsp) *nstatsp = v.nvec;
1591 /** @brief State structure tracking @c disorder-stats */
1592 struct stats_details {
1593 void (*done)(char *data, void *u);
1595 int exited; /* subprocess exited */
1596 int closed; /* pipe close */
1597 int wstat; /* wait status from subprocess */
1598 struct dynstr data[1]; /* data read from pipe */
1601 /** @brief Called when @c disorder-stats may have completed
1602 * @param d Pointer to state structure
1604 * Called from stats_finished() and stats_read(). Only proceeds when the
1605 * process has terminated and the output is complete.
1607 static void stats_complete(struct stats_details *d) {
1610 if(!(d->exited && d->closed))
1612 byte_xasprintf(&s, "\n"
1614 "track lookup cache hits: %lu\n"
1615 "track lookup cache misses: %lu\n",
1617 cache_files_misses);
1618 dynstr_append_string(d->data, s);
1619 dynstr_terminate(d->data);
1620 d->done(d->data->vec, d->u);
1623 /** @brief Called when @c disorder-stats exits
1624 * @param ev Event loop
1625 * @param pid Process ID
1626 * @param status Exit status
1627 * @param rusage Resource usage
1628 * @param u Pointer to state structure (@ref stats_details)
1631 static int stats_finished(ev_source attribute((unused)) *ev,
1634 const struct rusage attribute((unused)) *rusage,
1636 struct stats_details *const d = u;
1640 error(0, "disorder-stats %s", wstat(status));
1643 byte_xasprintf(&k, "%lu", (unsigned long)pid);
1644 hash_remove(stats_pids, k);
1648 /** @brief Called when pipe from @c disorder-stats is readable
1649 * @param ev Event loop
1650 * @param reader Reader state
1651 * @param ptr Pointer to bytes read
1652 * @param bytes Number of bytes available
1653 * @param eof Set at end of file
1654 * @param u Pointer to state structure (@ref stats_details)
1657 static int stats_read(ev_source attribute((unused)) *ev,
1663 struct stats_details *const d = u;
1665 dynstr_append_bytes(d->data, ptr, bytes);
1666 ev_reader_consume(reader, bytes);
1673 /** @brief Called when pipe from @c disorder-stats errors
1674 * @param ev Event loop
1675 * @param errno_value Error code
1676 * @param u Pointer to state structure (@ref stats_details)
1679 static int stats_error(ev_source attribute((unused)) *ev,
1682 struct stats_details *const d = u;
1684 error(errno_value, "error reading from pipe to disorder-stats");
1690 /** @brief Get database statistics via background process
1691 * @param ev Event loop
1692 * @param done Called on completion
1693 * @param u Passed to @p done
1695 * Within the main server use this instead of trackdb_stats(), which can take
1696 * unreasonably long.
1698 void trackdb_stats_subprocess(ev_source *ev,
1699 void (*done)(char *data, void *u),
1703 struct stats_details *d = xmalloc(sizeof *d);
1705 dynstr_init(d->data);
1709 pid = subprogram(ev, p[1], "disorder-stats", (char *)0);
1711 ev_child(ev, pid, 0, stats_finished, d);
1712 if(!ev_reader_new(ev, p[0], stats_read, stats_error, d,
1713 "disorder-stats reader"))
1714 fatal(0, "ev_reader_new for disorder-stats reader failed");
1715 /* Remember the PID */
1717 stats_pids = hash_new(1);
1719 byte_xasprintf(&k, "%lu", (unsigned long)pid);
1720 hash_add(stats_pids, k, "", HASH_INSERT);
1723 /** @brief Parse a track name part preference
1724 * @param name Preference name
1725 * @param partp Where to store part name
1726 * @param contextp Where to store context name
1727 * @return 0 on success, non-0 if parse fails
1729 static int trackdb__parse_namepref(const char *name,
1733 static const char prefix[] = "trackname_";
1735 if(strncmp(name, prefix, strlen(prefix)))
1736 return -1; /* not trackname_* at all */
1737 name += strlen(prefix);
1738 /* There had better be a _ between context and part */
1739 c = strchr(name, '_');
1742 /* Context is first in the pref name even though most APIs have the part
1743 * first. Confusing; sorry. */
1744 *contextp = xstrndup(name, c - name);
1746 /* There had better NOT be a second _ */
1749 *partp = xstrdup(c);
1753 /** @brief Compute the default value for a track preference
1754 * @param track Track name
1755 * @param name Preference name
1756 * @return Default value or 0 if none/not known
1758 static const char *trackdb__default(const char *track, const char *name) {
1759 char *context, *part;
1761 if(!trackdb__parse_namepref(name, &part, &context)) {
1762 /* We can work out the default for a trackname_ pref */
1763 return trackname_part(track, context, part);
1764 } else if(!strcmp(name, "weight")) {
1765 /* We know the default weight */
1767 } else if(!strcmp(name, "pick_at_random")) {
1768 /* By default everything is eligible for picking at random */
1770 } else if(!strcmp(name, "tags")) {
1771 /* By default everything no track has any tags */
1777 /* set a pref (remove if value=0) */
1778 int trackdb_set(const char *track,
1780 const char *value) {
1781 struct kvp *t, *p, *a;
1784 char *oldalias, *newalias, **oldtags = 0, **newtags;
1787 /* If the value matches the default then unset instead, to keep the database
1788 * tidy. Older versions did not have this feature so your database may yet
1789 * have some default values stored in it. */
1791 def = trackdb__default(track, name);
1792 if(def && !strcmp(value, def))
1797 tid = trackdb_begin_transaction();
1798 if((err = gettrackdata(track, &t, &p, 0,
1799 0, tid)) == DB_LOCK_DEADLOCK)
1801 if(err == DB_NOTFOUND) break;
1802 if(name[0] == '_') {
1803 if(kvp_set(&t, name, value))
1804 if(trackdb_putdata(trackdb_tracksdb, track, t, tid, 0))
1807 /* get the old alias name */
1808 if(compute_alias(&oldalias, track, p, tid)) goto fail;
1809 /* get the old tags */
1810 if(!strcmp(name, "tags"))
1811 oldtags = parsetags(kvp_get(p, "tags"));
1813 if(kvp_set(&p, name, value))
1814 if(trackdb_putdata(trackdb_prefsdb, track, p, tid, 0))
1816 /* compute the new alias name */
1817 if((err = compute_alias(&newalias, track, p, tid))) goto fail;
1818 /* check whether alias has changed */
1819 if(!(oldalias == newalias
1820 || (oldalias && newalias && !strcmp(oldalias, newalias)))) {
1821 /* adjust alias records to fit change */
1823 && trackdb_delkey(trackdb_tracksdb, oldalias, tid) == DB_LOCK_DEADLOCK)
1827 kvp_set(&a, "_alias_for", track);
1828 if(trackdb_putdata(trackdb_tracksdb, newalias, a, tid, 0)) goto fail;
1831 /* check whether tags have changed */
1832 if(!strcmp(name, "tags")) {
1833 newtags = parsetags(value);
1834 while(*oldtags || *newtags) {
1835 if(*oldtags && *newtags) {
1836 cmp = strcmp(*oldtags, *newtags);
1838 /* keeping this tag */
1842 /* old tag fits into a gap in the new list, so delete old */
1845 /* new tag fits into a gap in the old list, so insert new */
1847 } else if(*oldtags) {
1848 /* we've run out of new tags, so remaining old ones are to be
1851 if(trackdb_delkeydata(trackdb_tagsdb,
1852 *oldtags, track, tid) == DB_LOCK_DEADLOCK)
1856 /* we've run out of old tags, so remainig new ones are to be
1859 if(register_tag(track, *newtags, tid)) goto fail;
1868 trackdb_abort_transaction(tid);
1870 trackdb_commit_transaction(tid);
1871 return err == 0 ? 0 : -1;
1875 const char *trackdb_get(const char *track,
1877 return kvp_get(trackdb_get_all(track), name);
1880 /* get all prefs as a 0-terminated array */
1881 struct kvp *trackdb_get_all(const char *track) {
1882 struct kvp *t, *p, **pp;
1886 tid = trackdb_begin_transaction();
1887 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1891 trackdb_abort_transaction(tid);
1893 trackdb_commit_transaction(tid);
1894 for(pp = &p; *pp; pp = &(*pp)->next)
1901 const char *trackdb_resolve(const char *track) {
1906 tid = trackdb_begin_transaction();
1907 if(gettrackdata(track, 0, 0, &actual, 0, tid) == DB_LOCK_DEADLOCK)
1911 trackdb_abort_transaction(tid);
1913 trackdb_commit_transaction(tid);
1917 int trackdb_isalias(const char *track) {
1918 const char *actual = trackdb_resolve(track);
1920 return strcmp(actual, track);
1923 /* test whether a track exists (perhaps an alias) */
1924 int trackdb_exists(const char *track) {
1929 tid = trackdb_begin_transaction();
1930 /* unusually, here we want the return value */
1931 if((err = gettrackdata(track, 0, 0, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1935 trackdb_abort_transaction(tid);
1937 trackdb_commit_transaction(tid);
1941 /* return the list of tags */
1942 char **trackdb_alltags(void) {
1947 WITH_TRANSACTION(trackdb_listkeys(trackdb_tagsdb, v, tid));
1951 /** @brief List all the keys in @p db
1952 * @param db Database
1953 * @param v Vector to store keys in
1954 * @param tid Transaction ID
1955 * @return 0 or DB_LOCK_DEADLOCK
1957 int trackdb_listkeys(DB *db, struct vector *v, DB_TXN *tid) {
1960 DBC *const c = trackdb_opencursor(db, tid);
1963 memset(&k, 0, sizeof k);
1964 while(!(e = c->c_get(c, &k, prepare_data(&d), DB_NEXT_NODUP)))
1965 vector_append(v, xstrndup(k.data, k.size));
1969 case DB_LOCK_DEADLOCK:
1972 fatal(0, "c->c_get: %s", db_strerror(e));
1974 if((e = trackdb_closecursor(c)))
1976 vector_terminate(v);
1980 /* return 1 iff sorted tag lists A and B have at least one member in common */
1981 int tag_intersection(char **a, char **b) {
1984 /* Same sort of logic as trackdb_set() above */
1986 if(!(cmp = strcmp(*a, *b))) return 1;
1987 else if(cmp < 0) ++a;
1993 static void choose_finished(ev_source *ev, unsigned which) {
1994 choose_complete |= which;
1995 if(choose_complete != (CHOOSE_RUNNING|CHOOSE_READING))
1998 if(choose_status == 0 && choose_output.nvec > 0) {
1999 dynstr_terminate(&choose_output);
2000 choose_callback(ev, xstrdup(choose_output.vec));
2002 choose_callback(ev, 0);
2005 /** @brief Called when @c disorder-choose terminates */
2006 static int choose_exited(ev_source *ev,
2007 pid_t attribute((unused)) pid,
2009 const struct rusage attribute((unused)) *rusage,
2010 void attribute((unused)) *u) {
2012 error(0, "disorder-choose %s", wstat(status));
2013 choose_status = status;
2014 choose_finished(ev, CHOOSE_RUNNING);
2018 /** @brief Called with data from @c disorder-choose pipe */
2019 static int choose_readable(ev_source *ev,
2024 void attribute((unused)) *u) {
2025 dynstr_append_bytes(&choose_output, ptr, bytes);
2026 ev_reader_consume(reader, bytes);
2028 choose_finished(ev, CHOOSE_READING);
2032 static int choose_read_error(ev_source *ev,
2034 void attribute((unused)) *u) {
2035 error(errno_value, "error reading disorder-choose pipe");
2036 choose_finished(ev, CHOOSE_READING);
2040 /** @brief Request a random track
2041 * @param ev Event source
2042 * @param callback Called with random track or NULL
2043 * @return 0 if a request was initiated, else -1
2045 * Initiates a random track choice. @p callback will later be called back with
2046 * the choice (or NULL on error). If a choice is already underway then -1 is
2047 * returned and there will be no additional callback.
2049 * The caller shouldn't assume that the track returned actually exists (it
2050 * might be removed between the choice and the callback, or between being added
2051 * to the queue and being played).
2053 int trackdb_request_random(ev_source *ev,
2054 random_callback *callback) {
2057 if(choose_pid != -1)
2058 return -1; /* don't run concurrent chooses */
2061 choose_pid = subprogram(ev, p[1], "disorder-choose", (char *)0);
2064 choose_callback = callback;
2065 choose_output.nvec = 0;
2066 choose_complete = 0;
2067 if(!ev_reader_new(ev, p[0], choose_readable, choose_read_error, 0,
2068 "disorder-choose reader")) /* owns p[0] */
2069 fatal(0, "ev_reader_new for disorder-choose reader failed");
2070 ev_child(ev, choose_pid, 0, choose_exited, 0); /* owns the subprocess */
2074 /* get a track name given the prefs. Set *used_db to 1 if we got the answer
2075 * from the prefs. */
2076 static const char *getpart(const char *track,
2077 const char *context,
2079 const struct kvp *p,
2084 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2085 if((result = kvp_get(p, pref)))
2088 result = trackname_part(track, context, part);
2089 assert(result != 0);
2093 /* get a track name part, like trackname_part(), but taking the database into
2095 const char *trackdb_getpart(const char *track,
2096 const char *context,
2104 /* construct the full pref */
2105 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2107 tid = trackdb_begin_transaction();
2108 if((err = gettrackdata(track, 0, &p, &actual, 0, tid)) == DB_LOCK_DEADLOCK)
2112 trackdb_abort_transaction(tid);
2114 trackdb_commit_transaction(tid);
2115 return getpart(actual, context, part, p, &used_db);
2118 /* get the raw path name for @track@ (might be an alias) */
2119 const char *trackdb_rawpath(const char *track) {
2125 tid = trackdb_begin_transaction();
2126 if(gettrackdata(track, &t, 0, 0, 0, tid) == DB_LOCK_DEADLOCK)
2130 trackdb_abort_transaction(tid);
2132 trackdb_commit_transaction(tid);
2133 if(!(path = kvp_get(t, "_path"))) path = track;
2137 /* trackdb_list **************************************************************/
2139 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
2140 * readable at some point */
2142 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
2143 * If RE is a null pointer then it matches everything. */
2144 static int track_matches(size_t dl, const char *track, size_t tl,
2152 switch(rc = pcre_exec(re, 0, track, tl, 0, 0, ovec, 3)) {
2153 case PCRE_ERROR_NOMATCH: return 0;
2156 error(0, "pcre_exec returned %d, subject '%s'", rc, track);
2163 static int do_list(struct vector *v, const char *dir,
2164 enum trackdb_listable what, const pcre *re, DB_TXN *tid) {
2170 size_t l, last_dir_len = 0;
2171 char *last_dir = 0, *track;
2175 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2178 /* find the first key >= dir */
2179 err = cursor->c_get(cursor, &k, &d, DB_SET_RANGE);
2180 /* keep going while we're dealing with <dir/anything> */
2183 && ((char *)k.data)[dl] == '/'
2184 && !memcmp(k.data, dir, dl)) {
2185 ptr = memchr((char *)k.data + dl + 1, '/', k.size - (dl + 1));
2187 /* we have <dir/component/anything>, so <dir/component> is a directory */
2188 l = ptr - (char *)k.data;
2189 if(what & trackdb_directories)
2191 && l == last_dir_len
2192 && !memcmp(last_dir, k.data, l))) {
2193 last_dir = xstrndup(k.data, last_dir_len = l);
2194 if(track_matches(dl, k.data, l, re))
2195 vector_append(v, last_dir);
2198 /* found a plain file */
2199 if((what & trackdb_files)) {
2200 track = xstrndup(k.data, k.size);
2201 if((err = trackdb_getdata(trackdb_prefsdb,
2202 track, &p, tid)) == DB_LOCK_DEADLOCK)
2204 /* There's an awkward question here...
2206 * If a track shares a directory with its alias then we could
2207 * do one of three things:
2208 * - report both. Looks ridiculuous in most UIs.
2209 * - report just the alias. Remarkably inconvenient to write
2211 * - report just the real name. Ugly if the UI doesn't prettify
2212 * names via the name parts.
2215 /* If this file is an alias for a track in the same directory then we
2217 struct kvp *t = kvp_urldecode(d.data, d.size);
2218 const char *alias_target = kvp_get(t, "_alias_for");
2220 && !strcmp(d_dirname(alias_target),
2222 if(track_matches(dl, k.data, k.size, re))
2223 vector_append(v, track);
2225 /* if this file has an alias in the same directory then we skip it */
2227 if((err = compute_alias(&alias, track, p, tid)))
2229 if(!(alias && !strcmp(d_dirname(alias), d_dirname(track))))
2230 if(track_matches(dl, k.data, k.size, re))
2231 vector_append(v, track);
2235 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2243 case DB_LOCK_DEADLOCK:
2244 error(0, "error querying database: %s", db_strerror(err));
2247 fatal(0, "error querying database: %s", db_strerror(err));
2250 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2254 /* return the directories or files below @dir@ */
2255 char **trackdb_list(const char *dir, int *np, enum trackdb_listable what,
2263 tid = trackdb_begin_transaction();
2266 if(do_list(&v, dir, what, re, tid))
2269 for(n = 0; n < config->collection.n; ++n)
2270 if(do_list(&v, config->collection.s[n].root, what, re, tid))
2275 trackdb_abort_transaction(tid);
2277 trackdb_commit_transaction(tid);
2278 vector_terminate(&v);
2284 /* If S is tag:something, return something. Else return 0. */
2285 static const char *checktag(const char *s) {
2286 if(!strncmp(s, "tag:", 4))
2292 /* return a list of tracks containing all of the words given. If you
2293 * ask for only stopwords you get no tracks. */
2294 char **trackdb_search(char **wordlist, int nwordlist, int *ntracks) {
2295 const char **w, *best = 0, *tag;
2296 char **twords, **tags;
2298 int i, j, n, err, what;
2308 *ntracks = 0; /* for early returns */
2309 /* normalize all the words */
2310 w = xmalloc(nwordlist * sizeof (char *));
2311 istag = xmalloc_noptr(nwordlist);
2312 for(n = 0; n < nwordlist; ++n) {
2316 w[n] = utf8_casefold_compat(wordlist[n], strlen(wordlist[n]), 0);
2317 if(checktag(w[n])) {
2318 ++ntags; /* count up tags */
2319 /* Normalize the tag */
2320 w[n] = normalize_tag(w[n] + 4, strlen(w[n] + 4));
2323 /* Normalize the search term by removing combining characters */
2324 if(!(w32 = utf8_to_utf32(w[n], strlen(w[n]), &nw32)))
2326 nw32 = remove_combining_chars(w32, nw32);
2327 if(!(w[n] = utf32_to_utf8(w32, nw32, 0)))
2332 /* find the longest non-stopword */
2333 for(n = 0; n < nwordlist; ++n)
2334 if(!istag[n] && !stopword(w[n]))
2335 if(!best || strlen(w[n]) > strlen(best))
2337 /* TODO: we should at least in principal be able to identify the word or tag
2338 * with the least matches in log time, and choose that as our primary search
2340 if(ntags && !best) {
2341 /* Only tags are listed. We limit to the first and narrow down with the
2343 best = istag[0] ? w[0] : 0;
2344 db = trackdb_tagsdb;
2347 /* We can limit to some word. */
2348 db = trackdb_searchdb;
2351 /* Only stopwords */
2357 tid = trackdb_begin_transaction();
2358 /* find all the tracks that have that word */
2363 cursor = trackdb_opencursor(db, tid);
2364 while(!(err = cursor->c_get(cursor, &k, &d, what))) {
2365 vector_append(&v, xstrndup(d.data, d.size));
2372 case DB_LOCK_DEADLOCK:
2373 error(0, "error querying %s database: %s", dbname, db_strerror(err));
2376 fatal(0, "error querying %s database: %s", dbname, db_strerror(err));
2378 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2380 /* do a naive search over that (hopefuly fairly small) list of tracks */
2382 for(n = 0; n < v.nvec; ++n) {
2383 if((err = gettrackdata(v.vec[n], 0, &p, 0, 0, tid) == DB_LOCK_DEADLOCK))
2386 error(0, "track %s unexpected error: %s", v.vec[n], db_strerror(err));
2389 twords = track_to_words(v.vec[n], p);
2390 tags = parsetags(kvp_get(p, "tags"));
2391 for(i = 0; i < nwordlist; ++i) {
2394 /* Track must have this tag */
2395 for(j = 0; tags[j]; ++j)
2396 if(!strcmp(tag, tags[j])) break; /* tag found */
2397 if(!tags[j]) break; /* tag not found */
2399 /* Track must contain this word */
2400 for(j = 0; twords[j]; ++j)
2401 if(!strcmp(w[i], twords[j])) break; /* word found */
2402 if(!twords[j]) break; /* word not found */
2405 if(i >= nwordlist) /* all words found */
2406 vector_append(&u, v.vec[n]);
2410 trackdb_closecursor(cursor);
2412 trackdb_abort_transaction(tid);
2413 info("retrying search");
2415 trackdb_commit_transaction(tid);
2416 vector_terminate(&u);
2422 /* trackdb_scan **************************************************************/
2424 int trackdb_scan(const char *root,
2425 int (*callback)(const char *track,
2434 const size_t root_len = root ? strlen(root) : 0;
2436 struct kvp *data, *prefs;
2439 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2441 err = cursor->c_get(cursor, make_key(&k, root), prepare_data(&d),
2444 memset(&k, 0, sizeof k);
2445 err = cursor->c_get(cursor, &k, prepare_data(&d),
2450 || (k.size > root_len
2451 && !strncmp(k.data, root, root_len)
2452 && ((char *)k.data)[root_len] == '/')) {
2453 data = kvp_urldecode(d.data, d.size);
2454 if(kvp_get(data, "_path")) {
2455 track = xstrndup(k.data, k.size);
2456 /* TODO: trackdb_prefsdb is currently a DB_HASH. This means we have to
2457 * do a lookup for every single track. In fact this is quite quick:
2458 * with around 10,000 tracks a complete scan is around 0.3s on my
2459 * 2.2GHz Athlon. However, if it were a DB_BTREE, we could do the same
2460 * linear walk as we already do over trackdb_tracksdb, and probably get
2461 * even higher performance. That would require upgrade logic to
2462 * translate old databases though.
2464 switch(err = trackdb_prefsdb->get(trackdb_prefsdb, tid, &k,
2465 prepare_data(&pd), 0)) {
2467 prefs = kvp_urldecode(pd.data, pd.size);
2472 case DB_LOCK_DEADLOCK:
2473 error(0, "getting prefs: %s", db_strerror(err));
2474 trackdb_closecursor(cursor);
2477 fatal(0, "getting prefs: %s", db_strerror(err));
2479 /* Advance to the next track before the callback so that the callback
2480 * may safely delete the track */
2481 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2482 if((cberr = callback(track, data, prefs, u, tid))) {
2487 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2491 trackdb_closecursor(cursor);
2498 case DB_LOCK_DEADLOCK:
2499 error(0, "c->c_get: %s", db_strerror(err));
2502 fatal(0, "c->c_get: %s", db_strerror(err));
2506 /* trackdb_rescan ************************************************************/
2508 /** @brief Node in the list of rescan-complete callbacks */
2509 struct rescanned_node {
2510 struct rescanned_node *next;
2511 void (*rescanned)(void *ru);
2515 /** @brief List of rescan-complete callbacks */
2516 static struct rescanned_node *rescanned_list;
2518 /** @brief Add a rescan completion callback */
2519 void trackdb_add_rescanned(void (*rescanned)(void *ru),
2522 struct rescanned_node *n = xmalloc(sizeof *n);
2523 n->next = rescanned_list;
2524 n->rescanned = rescanned;
2530 /* called when the rescanner terminates */
2531 static int reap_rescan(ev_source attribute((unused)) *ev,
2534 const struct rusage attribute((unused)) *rusage,
2535 void attribute((unused)) *u) {
2536 if(pid == rescan_pid) rescan_pid = -1;
2538 error(0, RESCAN": %s", wstat(status));
2540 D((RESCAN" terminated: %s", wstat(status)));
2541 /* Our cache of file lookups is out of date now */
2542 cache_clean(&cache_files_type);
2543 eventlog("rescanned", (char *)0);
2544 /* Call rescanned callbacks */
2545 while(rescanned_list) {
2546 void (*rescanned)(void *u_) = rescanned_list->rescanned;
2547 void *ru = rescanned_list->ru;
2549 rescanned_list = rescanned_list->next;
2555 /** @brief Initiate a rescan
2556 * @param ev Event loop or 0 to block
2557 * @param recheck 1 to recheck lengths, 0 to suppress check
2558 * @param rescanned Called on completion (if not NULL)
2559 * @param ru Passed to @p rescanned
2561 void trackdb_rescan(ev_source *ev, int recheck,
2562 void (*rescanned)(void *ru),
2566 if(rescan_pid != -1) {
2567 trackdb_add_rescanned(rescanned, ru);
2568 error(0, "rescan already underway");
2571 rescan_pid = subprogram(ev, -1, RESCAN,
2572 recheck ? "--check" : "--no-check",
2574 trackdb_add_rescanned(rescanned, ru);
2576 ev_child(ev, rescan_pid, 0, reap_rescan, 0);
2577 D(("started rescanner"));
2579 /* This is the first rescan, we block until it is complete */
2580 while(waitpid(rescan_pid, &w, 0) < 0 && errno == EINTR)
2582 reap_rescan(0, rescan_pid, w, 0, 0);
2586 int trackdb_rescan_cancel(void) {
2587 if(rescan_pid == -1) return 0;
2588 if(kill(rescan_pid, SIGTERM) < 0)
2589 fatal(errno, "error killing rescanner");
2594 /** @brief Return true if a rescan is underway */
2595 int trackdb_rescan_underway(void) {
2596 return rescan_pid != -1;
2599 /* global prefs **************************************************************/
2601 void trackdb_set_global(const char *name,
2609 tid = trackdb_begin_transaction();
2610 if(!(err = trackdb_set_global_tid(name, value, tid)))
2612 trackdb_abort_transaction(tid);
2614 trackdb_commit_transaction(tid);
2615 /* log important state changes */
2616 if(!strcmp(name, "playing")) {
2617 state = !value || !strcmp(value, "yes");
2618 info("playing %s by %s",
2619 state ? "enabled" : "disabled",
2621 eventlog("state", state ? "enable_play" : "disable_play", (char *)0);
2623 if(!strcmp(name, "random-play")) {
2624 state = !value || !strcmp(value, "yes");
2625 info("random play %s by %s",
2626 state ? "enabled" : "disabled",
2628 eventlog("state", state ? "enable_random" : "disable_random", (char *)0);
2632 int trackdb_set_global_tid(const char *name,
2638 memset(&k, 0, sizeof k);
2639 memset(&d, 0, sizeof d);
2640 k.data = (void *)name;
2641 k.size = strlen(name);
2643 d.data = (void *)value;
2644 d.size = strlen(value);
2647 err = trackdb_globaldb->put(trackdb_globaldb, tid, &k, &d, 0);
2649 err = trackdb_globaldb->del(trackdb_globaldb, tid, &k, 0);
2650 if(err == DB_LOCK_DEADLOCK) return err;
2652 fatal(0, "error updating database: %s", db_strerror(err));
2656 const char *trackdb_get_global(const char *name) {
2662 tid = trackdb_begin_transaction();
2663 if(!(err = trackdb_get_global_tid(name, tid, &r)))
2665 trackdb_abort_transaction(tid);
2667 trackdb_commit_transaction(tid);
2671 int trackdb_get_global_tid(const char *name,
2677 memset(&k, 0, sizeof k);
2678 k.data = (void *)name;
2679 k.size = strlen(name);
2680 switch(err = trackdb_globaldb->get(trackdb_globaldb, tid, &k,
2681 prepare_data(&d), 0)) {
2683 *rp = xstrndup(d.data, d.size);
2688 case DB_LOCK_DEADLOCK:
2691 fatal(0, "error reading database: %s", db_strerror(err));
2695 /** @brief Retrieve the most recently added tracks
2696 * @param ntracksp Where to put count, or 0
2697 * @param maxtracks Maximum number of tracks to retrieve
2698 * @return null-terminated array of track names
2700 * The most recently added track is first in the array.
2702 char **trackdb_new(int *ntracksp,
2708 tid = trackdb_begin_transaction();
2709 tracks = trackdb_new_tid(ntracksp, maxtracks, tid);
2712 trackdb_abort_transaction(tid);
2714 trackdb_commit_transaction(tid);
2718 /** @brief Retrieve the most recently added tracks
2719 * @param ntracksp Where to put count, or 0
2720 * @param maxtracks Maximum number of tracks to retrieve, or 0 for all
2721 * @param tid Transaction ID
2722 * @return null-terminated array of track names, or NULL on deadlock
2724 * The most recently added track is first in the array.
2726 static char **trackdb_new_tid(int *ntracksp,
2732 struct vector tracks[1];
2733 hash *h = hash_new(1);
2735 vector_init(tracks);
2736 c = trackdb_opencursor(trackdb_noticeddb, tid);
2737 while((maxtracks <= 0 || tracks->nvec < maxtracks)
2738 && !(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_PREV))) {
2739 char *const track = xstrndup(d.data, d.size);
2740 /* Don't add any track more than once */
2741 if(hash_add(h, track, "", HASH_INSERT))
2743 /* See if the track still exists */
2744 err = trackdb_getdata(trackdb_tracksdb, track, NULL/*kp*/, tid);
2745 if(err == DB_NOTFOUND)
2746 continue; /* It doesn't, skip it */
2747 if(err == DB_LOCK_DEADLOCK)
2749 vector_append(tracks, track);
2752 case 0: /* hit maxtracks */
2753 case DB_NOTFOUND: /* ran out of tracks */
2755 case DB_LOCK_DEADLOCK:
2756 trackdb_closecursor(c);
2759 fatal(0, "error reading noticed.db: %s", db_strerror(err));
2761 if((err = trackdb_closecursor(c)))
2762 return 0; /* deadlock */
2763 vector_terminate(tracks);
2765 *ntracksp = tracks->nvec;
2769 /** @brief Expire noticed.db
2770 * @param earliest Earliest timestamp to keep
2772 void trackdb_expire_noticed(time_t earliest) {
2776 tid = trackdb_begin_transaction();
2777 if(!trackdb_expire_noticed_tid(earliest, tid))
2779 trackdb_abort_transaction(tid);
2781 trackdb_commit_transaction(tid);
2784 /** @brief Expire noticed.db
2785 * @param earliest Earliest timestamp to keep
2786 * @param tid Transaction ID
2787 * @return 0 or DB_LOCK_DEADLOCK
2789 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid) {
2797 c = trackdb_opencursor(trackdb_noticeddb, tid);
2798 while(!(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_NEXT))) {
2800 when = (time_t)(((uint64_t)ntohl(kk[0]) << 32) + ntohl(kk[1]));
2801 if(when >= earliest)
2803 if((err = c->c_del(c, 0))) {
2804 if(err != DB_LOCK_DEADLOCK)
2805 fatal(0, "error deleting expired noticed.db entry: %s",
2811 if(err == DB_NOTFOUND)
2813 if(err && err != DB_LOCK_DEADLOCK)
2814 fatal(0, "error expiring noticed.db: %s", db_strerror(err));
2816 if((err = trackdb_closecursor(c))) {
2817 if(err != DB_LOCK_DEADLOCK)
2818 fatal(0, "error closing cursor: %s", db_strerror(err));
2822 info("expired %d tracks from noticed.db", count);
2826 /* tidying up ****************************************************************/
2828 void trackdb_gc(void) {
2832 if((err = trackdb_env->txn_checkpoint(trackdb_env,
2833 config->checkpoint_kbyte,
2834 config->checkpoint_min,
2836 fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err));
2837 if((err = trackdb_env->log_archive(trackdb_env, &logfiles, DB_ARCH_REMOVE)))
2838 fatal(0, "trackdb_env->log_archive: %s", db_strerror(err));
2839 /* This makes catastrophic recovery impossible. However, the user can still
2840 * preserve the important data by using disorder-dump to snapshot their
2841 * prefs, and later to restore it. This is likely to have much small
2842 * long-term storage requirements than record the db logfiles. */
2845 /* user database *************************************************************/
2847 /** @brief Return true if @p user is trusted */
2848 static int trusted(const char *user) {
2851 for(n = 0; (n < config->trust.n
2852 && strcmp(config->trust.s[n], user)); ++n)
2854 return n < config->trust.n;
2857 /** @brief Return non-zero for a valid username
2859 * Currently we only allow the letters and digits in ASCII. We could be more
2860 * liberal than this but it is a nice simple test. It is critical that
2861 * semicolons are never allowed.
2863 * NB also used by playlist_parse_name() to validate playlist names!
2865 int valid_username(const char *user) {
2869 const uint8_t c = *user++;
2870 /* For now we are very strict */
2871 if((c >= 'a' && c <= 'z')
2872 || (c >= 'A' && c <= 'Z')
2873 || (c >= '0' && c <= '9'))
2881 /** @brief Add a user */
2882 static int create_user(const char *user,
2883 const char *password,
2886 const char *confirmation,
2892 /* sanity check user */
2893 if(!valid_username(user)) {
2894 error(0, "invalid username '%s'", user);
2897 if(parse_rights(rights, 0, 1)) {
2898 error(0, "invalid rights string");
2901 /* data for this user */
2903 kvp_set(&k, "password", password);
2904 kvp_set(&k, "rights", rights);
2906 kvp_set(&k, "email", email);
2908 kvp_set(&k, "confirmation", confirmation);
2909 snprintf(s, sizeof s, "%jd", (intmax_t)xtime(0));
2910 kvp_set(&k, "created", s);
2911 return trackdb_putdata(trackdb_usersdb, user, k, tid, flags);
2914 /** @brief Add one pre-existing user */
2915 static int one_old_user(const char *user, const char *password,
2919 /* www-data doesn't get added */
2920 if(!strcmp(user, "www-data")) {
2921 info("not adding www-data to user database");
2925 if(!strcmp(user, "root"))
2927 else if(trusted(user)) {
2930 parse_rights(config->default_rights, &r, 1);
2931 r &= ~(rights_type)(RIGHT_SCRATCH__MASK|RIGHT_MOVE__MASK|RIGHT_REMOVE__MASK);
2932 r |= (RIGHT_ADMIN|RIGHT_RESCAN
2933 |RIGHT_SCRATCH_ANY|RIGHT_MOVE_ANY|RIGHT_REMOVE_ANY);
2934 rights = rights_string(r);
2936 rights = config->default_rights;
2937 return create_user(user, password, rights, 0/*email*/, 0/*confirmation*/,
2938 tid, DB_NOOVERWRITE);
2941 static int trackdb_old_users_tid(DB_TXN *tid) {
2944 for(n = 0; n < config->allow.n; ++n) {
2945 switch(one_old_user(config->allow.s[n].s[0], config->allow.s[n].s[1],
2948 info("created user %s from 'allow' directive", config->allow.s[n].s[0]);
2951 error(0, "user %s already exists, delete 'allow' directive",
2952 config->allow.s[n].s[0]);
2953 /* This won't ever become fatal - eventually 'allow' will be
2956 case DB_LOCK_DEADLOCK:
2957 return DB_LOCK_DEADLOCK;
2963 /** @brief Read old 'allow' directives and copy them to the users database */
2964 void trackdb_old_users(void) {
2968 WITH_TRANSACTION(trackdb_old_users_tid(tid));
2971 /** @brief Create a root user in the user database if there is none */
2972 void trackdb_create_root(void) {
2977 /* Choose a new root password */
2978 gcry_randomize(pwbin, sizeof pwbin, GCRY_STRONG_RANDOM);
2979 pw = mime_to_base64(pwbin, sizeof pwbin);
2980 /* Create the root user if it does not exist */
2981 WITH_TRANSACTION(create_user("root", pw, "all",
2982 0/*email*/, 0/*confirmation*/,
2983 tid, DB_NOOVERWRITE));
2985 info("created root user");
2988 /** @brief Find a user's password from the database
2989 * @param user Username
2990 * @return Password or NULL
2992 * Only works if running as a user that can read the database!
2994 * If the user exists but has no password, "" is returned.
2996 const char *trackdb_get_password(const char *user) {
2999 const char *password;
3001 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3004 password = kvp_get(k, "password");
3005 return password ? password : "";
3008 /** @brief Add a new user
3009 * @param user Username
3010 * @param password Password or NULL
3011 * @param rights Initial rights
3012 * @param email Email address or NULL
3013 * @param confirmation Confirmation string or NULL
3014 * @return 0 on success, non-0 on error
3016 int trackdb_adduser(const char *user,
3017 const char *password,
3020 const char *confirmation) {
3023 WITH_TRANSACTION(create_user(user, password, rights, email, confirmation,
3024 tid, DB_NOOVERWRITE));
3026 error(0, "cannot create user '%s' because they already exist", user);
3030 info("created user '%s' with rights '%s' and email address '%s'",
3031 user, rights, email);
3033 info("created user '%s' with rights '%s'", user, rights);
3034 eventlog("user_add", user, (char *)0);
3039 /** @brief Delete a user
3040 * @param user User to delete
3041 * @return 0 on success, non-0 if the user didn't exist anyway
3043 int trackdb_deluser(const char *user) {
3046 WITH_TRANSACTION(trackdb_delkey(trackdb_usersdb, user, tid));
3048 error(0, "cannot delete user '%s' because they do not exist", user);
3051 info("deleted user '%s'", user);
3052 eventlog("user_delete", user, (char *)0);
3056 /** @brief Get user information
3057 * @param user User to query
3058 * @return Linked list of user information or NULL if user does not exist
3060 * Every user has at least a @c rights entry so NULL can be used to mean no
3063 struct kvp *trackdb_getuserinfo(const char *user) {
3067 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3074 /** @brief Edit user information
3075 * @param user User to edit
3076 * @param key Key to change
3077 * @param value Value to set, or NULL to remove
3078 * @param tid Transaction ID
3079 * @return 0, DB_LOCK_DEADLOCK or DB_NOTFOUND
3081 static int trackdb_edituserinfo_tid(const char *user, const char *key,
3082 const char *value, DB_TXN *tid) {
3086 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3088 if(!kvp_set(&k, key, value))
3089 return 0; /* no change */
3090 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3093 /** @brief Edit user information
3094 * @param user User to edit
3095 * @param key Key to change
3096 * @param value Value to set, or NULL to remove
3097 * @return 0 on success, non-0 on error
3099 int trackdb_edituserinfo(const char *user,
3100 const char *key, const char *value) {
3103 if(!strcmp(key, "rights")) {
3105 error(0, "cannot remove 'rights' key from user '%s'", user);
3108 if(parse_rights(value, 0, 1)) {
3109 error(0, "invalid rights string");
3112 } else if(!strcmp(key, "email")) {
3114 if(!email_valid(value)) {
3115 error(0, "invalid email address '%s' for user '%s'", value, user);
3119 value = 0; /* no email -> remove key */
3120 } else if(!strcmp(key, "created")) {
3121 error(0, "cannot change creation date for user '%s'", user);
3123 } else if(strcmp(key, "password")
3124 && !strcmp(key, "confirmation")) {
3125 error(0, "unknown user info key '%s' for user '%s'", key, user);
3128 WITH_TRANSACTION(trackdb_edituserinfo_tid(user, key, value, tid));
3130 error(0, "unknown user '%s'", user);
3133 eventlog("user_edit", user, key, (char *)0);
3138 /** @brief List all users
3139 * @return NULL-terminated list of users
3141 char **trackdb_listusers(void) {
3146 WITH_TRANSACTION(trackdb_listkeys(trackdb_usersdb, v, tid));
3150 /** @brief Confirm a user registration
3151 * @param user Username
3152 * @param confirmation Confirmation string
3153 * @param rightsp Where to put user rights
3154 * @param tid Transaction ID
3155 * @return 0 on success, non-0 on error
3157 static int trackdb_confirm_tid(const char *user, const char *confirmation,
3158 rights_type *rightsp,
3160 const char *stored_confirmation;
3165 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3167 if(!(stored_confirmation = kvp_get(k, "confirmation"))) {
3168 error(0, "already confirmed user '%s'", user);
3169 /* DB claims -30,800 to -30,999 so -1 should be a safe bet */
3172 if(!(rights = kvp_get(k, "rights"))) {
3173 error(0, "no rights for unconfirmed user '%s'", user);
3176 if(parse_rights(rights, rightsp, 1))
3178 if(strcmp(confirmation, stored_confirmation)) {
3179 error(0, "wrong confirmation string for user '%s'", user);
3183 kvp_set(&k, "confirmation", 0);
3184 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3187 /** @brief Confirm a user registration
3188 * @param user Username
3189 * @param confirmation Confirmation string
3190 * @param rightsp Where to put user rights
3191 * @return 0 on success, non-0 on error
3193 int trackdb_confirm(const char *user, const char *confirmation,
3194 rights_type *rightsp) {
3197 WITH_TRANSACTION(trackdb_confirm_tid(user, confirmation, rightsp, tid));
3200 info("registration confirmed for user '%s'", user);
3201 eventlog("user_confirm", user, (char *)0);
3204 error(0, "confirmation for nonexistent user '%s'", user);
3206 default: /* already reported */
3216 indent-tabs-mode:nil