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 /** @brief Set a preference
1778 * @param track Track to modify
1779 * @param name Preference name
1780 * @param value New value, or NULL to erase any existing value
1781 * @return 0 on success or non-zero if not allowed to set preference
1783 int trackdb_set(const char *track,
1785 const char *value) {
1786 struct kvp *t, *p, *a;
1789 char *oldalias, *newalias, **oldtags = 0, **newtags;
1792 /* If the value matches the default then unset instead, to keep the database
1793 * tidy. Older versions did not have this feature so your database may yet
1794 * have some default values stored in it. */
1796 def = trackdb__default(track, name);
1797 if(def && !strcmp(value, def))
1802 tid = trackdb_begin_transaction();
1803 if((err = gettrackdata(track, &t, &p, 0,
1804 0, tid)) == DB_LOCK_DEADLOCK)
1806 if(err == DB_NOTFOUND) break;
1807 if(name[0] == '_') {
1808 if(kvp_set(&t, name, value))
1809 if(trackdb_putdata(trackdb_tracksdb, track, t, tid, 0))
1812 /* get the old alias name */
1813 if(compute_alias(&oldalias, track, p, tid)) goto fail;
1814 /* get the old tags */
1815 if(!strcmp(name, "tags"))
1816 oldtags = parsetags(kvp_get(p, "tags"));
1818 if(kvp_set(&p, name, value))
1819 if(trackdb_putdata(trackdb_prefsdb, track, p, tid, 0))
1821 /* compute the new alias name */
1822 if((err = compute_alias(&newalias, track, p, tid))) goto fail;
1823 /* check whether alias has changed */
1824 if(!(oldalias == newalias
1825 || (oldalias && newalias && !strcmp(oldalias, newalias)))) {
1826 /* adjust alias records to fit change */
1828 && trackdb_delkey(trackdb_tracksdb, oldalias, tid) == DB_LOCK_DEADLOCK)
1832 kvp_set(&a, "_alias_for", track);
1833 if(trackdb_putdata(trackdb_tracksdb, newalias, a, tid, 0)) goto fail;
1836 /* check whether tags have changed */
1837 if(!strcmp(name, "tags")) {
1838 newtags = parsetags(value);
1839 while(*oldtags || *newtags) {
1840 if(*oldtags && *newtags) {
1841 cmp = strcmp(*oldtags, *newtags);
1843 /* keeping this tag */
1847 /* old tag fits into a gap in the new list, so delete old */
1850 /* new tag fits into a gap in the old list, so insert new */
1852 } else if(*oldtags) {
1853 /* we've run out of new tags, so remaining old ones are to be
1856 if(trackdb_delkeydata(trackdb_tagsdb,
1857 *oldtags, track, tid) == DB_LOCK_DEADLOCK)
1861 /* we've run out of old tags, so remainig new ones are to be
1864 if(register_tag(track, *newtags, tid)) goto fail;
1873 trackdb_abort_transaction(tid);
1875 trackdb_commit_transaction(tid);
1876 return err == 0 ? 0 : -1;
1879 /** @brief Get the value of a preference
1880 * @param track Track name
1881 * @param name Preference name
1882 * @return Preference value or NULL if it's not set
1884 const char *trackdb_get(const char *track,
1886 return kvp_get(trackdb_get_all(track), name);
1889 /** @brief Get all preferences for a track
1890 * @param track Track name
1891 * @return Linked list of preferences
1893 struct kvp *trackdb_get_all(const char *track) {
1894 struct kvp *t, *p, **pp;
1898 tid = trackdb_begin_transaction();
1899 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1903 trackdb_abort_transaction(tid);
1905 trackdb_commit_transaction(tid);
1906 for(pp = &p; *pp; pp = &(*pp)->next)
1912 /** @brief Resolve an alias
1913 * @param Track name (might be an alias)
1914 * @return Real track name (definitely not an alias) or NULL if no such track
1916 const char *trackdb_resolve(const char *track) {
1921 tid = trackdb_begin_transaction();
1922 if(gettrackdata(track, 0, 0, &actual, 0, tid) == DB_LOCK_DEADLOCK)
1926 trackdb_abort_transaction(tid);
1928 trackdb_commit_transaction(tid);
1932 /** @brief Detect an alias
1933 * @param track Track name
1934 * @return Nonzero if @p track exists and is an alias
1936 int trackdb_isalias(const char *track) {
1937 const char *actual = trackdb_resolve(track);
1939 return strcmp(actual, track);
1942 /** @brief Detect whether a track exists
1943 * @param track Track name (can be an alias)
1944 * @return Nonzero if @p track exists (whether or not it's an alias)
1946 int trackdb_exists(const char *track) {
1951 tid = trackdb_begin_transaction();
1952 /* unusually, here we want the return value */
1953 if((err = gettrackdata(track, 0, 0, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1957 trackdb_abort_transaction(tid);
1959 trackdb_commit_transaction(tid);
1963 /** @brief Return list of all known tags
1964 * @return NULL-terminated tag list
1966 char **trackdb_alltags(void) {
1971 WITH_TRANSACTION(trackdb_listkeys(trackdb_tagsdb, v, tid));
1975 /** @brief List all the keys in @p db
1976 * @param db Database
1977 * @param v Vector to store keys in
1978 * @param tid Transaction ID
1979 * @return 0 or DB_LOCK_DEADLOCK
1981 int trackdb_listkeys(DB *db, struct vector *v, DB_TXN *tid) {
1984 DBC *const c = trackdb_opencursor(db, tid);
1987 memset(&k, 0, sizeof k);
1988 while(!(e = c->c_get(c, &k, prepare_data(&d), DB_NEXT_NODUP)))
1989 vector_append(v, xstrndup(k.data, k.size));
1993 case DB_LOCK_DEADLOCK:
1996 fatal(0, "c->c_get: %s", db_strerror(e));
1998 if((e = trackdb_closecursor(c)))
2000 vector_terminate(v);
2004 /* return 1 iff sorted tag lists A and B have at least one member in common */
2005 int tag_intersection(char **a, char **b) {
2008 /* Same sort of logic as trackdb_set() above */
2010 if(!(cmp = strcmp(*a, *b))) return 1;
2011 else if(cmp < 0) ++a;
2017 static void choose_finished(ev_source *ev, unsigned which) {
2018 choose_complete |= which;
2019 if(choose_complete != (CHOOSE_RUNNING|CHOOSE_READING))
2022 if(choose_status == 0 && choose_output.nvec > 0) {
2023 dynstr_terminate(&choose_output);
2024 choose_callback(ev, xstrdup(choose_output.vec));
2026 choose_callback(ev, 0);
2029 /** @brief Called when @c disorder-choose terminates */
2030 static int choose_exited(ev_source *ev,
2031 pid_t attribute((unused)) pid,
2033 const struct rusage attribute((unused)) *rusage,
2034 void attribute((unused)) *u) {
2036 error(0, "disorder-choose %s", wstat(status));
2037 choose_status = status;
2038 choose_finished(ev, CHOOSE_RUNNING);
2042 /** @brief Called with data from @c disorder-choose pipe */
2043 static int choose_readable(ev_source *ev,
2048 void attribute((unused)) *u) {
2049 dynstr_append_bytes(&choose_output, ptr, bytes);
2050 ev_reader_consume(reader, bytes);
2052 choose_finished(ev, CHOOSE_READING);
2056 static int choose_read_error(ev_source *ev,
2058 void attribute((unused)) *u) {
2059 error(errno_value, "error reading disorder-choose pipe");
2060 choose_finished(ev, CHOOSE_READING);
2064 /** @brief Request a random track
2065 * @param ev Event source
2066 * @param callback Called with random track or NULL
2067 * @return 0 if a request was initiated, else -1
2069 * Initiates a random track choice. @p callback will later be called back with
2070 * the choice (or NULL on error). If a choice is already underway then -1 is
2071 * returned and there will be no additional callback.
2073 * The caller shouldn't assume that the track returned actually exists (it
2074 * might be removed between the choice and the callback, or between being added
2075 * to the queue and being played).
2077 int trackdb_request_random(ev_source *ev,
2078 random_callback *callback) {
2081 if(choose_pid != -1)
2082 return -1; /* don't run concurrent chooses */
2085 choose_pid = subprogram(ev, p[1], "disorder-choose", (char *)0);
2088 choose_callback = callback;
2089 choose_output.nvec = 0;
2090 choose_complete = 0;
2091 if(!ev_reader_new(ev, p[0], choose_readable, choose_read_error, 0,
2092 "disorder-choose reader")) /* owns p[0] */
2093 fatal(0, "ev_reader_new for disorder-choose reader failed");
2094 ev_child(ev, choose_pid, 0, choose_exited, 0); /* owns the subprocess */
2098 /* get a track name given the prefs. Set *used_db to 1 if we got the answer
2099 * from the prefs. */
2100 static const char *getpart(const char *track,
2101 const char *context,
2103 const struct kvp *p,
2108 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2109 if((result = kvp_get(p, pref)))
2112 result = trackname_part(track, context, part);
2113 assert(result != 0);
2117 /* get a track name part, like trackname_part(), but taking the database into
2119 const char *trackdb_getpart(const char *track,
2120 const char *context,
2128 /* construct the full pref */
2129 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2131 tid = trackdb_begin_transaction();
2132 if((err = gettrackdata(track, 0, &p, &actual, 0, tid)) == DB_LOCK_DEADLOCK)
2136 trackdb_abort_transaction(tid);
2138 trackdb_commit_transaction(tid);
2139 return getpart(actual, context, part, p, &used_db);
2142 /* get the raw path name for @track@ (might be an alias) */
2143 const char *trackdb_rawpath(const char *track) {
2149 tid = trackdb_begin_transaction();
2150 if(gettrackdata(track, &t, 0, 0, 0, tid) == DB_LOCK_DEADLOCK)
2154 trackdb_abort_transaction(tid);
2156 trackdb_commit_transaction(tid);
2157 if(!(path = kvp_get(t, "_path"))) path = track;
2161 /* trackdb_list **************************************************************/
2163 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
2164 * readable at some point */
2166 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
2167 * If RE is a null pointer then it matches everything. */
2168 static int track_matches(size_t dl, const char *track, size_t tl,
2176 switch(rc = pcre_exec(re, 0, track, tl, 0, 0, ovec, 3)) {
2177 case PCRE_ERROR_NOMATCH: return 0;
2180 error(0, "pcre_exec returned %d, subject '%s'", rc, track);
2187 static int do_list(struct vector *v, const char *dir,
2188 enum trackdb_listable what, const pcre *re, DB_TXN *tid) {
2194 size_t l, last_dir_len = 0;
2195 char *last_dir = 0, *track;
2199 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2202 /* find the first key >= dir */
2203 err = cursor->c_get(cursor, &k, &d, DB_SET_RANGE);
2204 /* keep going while we're dealing with <dir/anything> */
2207 && ((char *)k.data)[dl] == '/'
2208 && !memcmp(k.data, dir, dl)) {
2209 ptr = memchr((char *)k.data + dl + 1, '/', k.size - (dl + 1));
2211 /* we have <dir/component/anything>, so <dir/component> is a directory */
2212 l = ptr - (char *)k.data;
2213 if(what & trackdb_directories)
2215 && l == last_dir_len
2216 && !memcmp(last_dir, k.data, l))) {
2217 last_dir = xstrndup(k.data, last_dir_len = l);
2218 if(track_matches(dl, k.data, l, re))
2219 vector_append(v, last_dir);
2222 /* found a plain file */
2223 if((what & trackdb_files)) {
2224 track = xstrndup(k.data, k.size);
2225 if((err = trackdb_getdata(trackdb_prefsdb,
2226 track, &p, tid)) == DB_LOCK_DEADLOCK)
2228 /* There's an awkward question here...
2230 * If a track shares a directory with its alias then we could
2231 * do one of three things:
2232 * - report both. Looks ridiculuous in most UIs.
2233 * - report just the alias. Remarkably inconvenient to write
2235 * - report just the real name. Ugly if the UI doesn't prettify
2236 * names via the name parts.
2239 /* If this file is an alias for a track in the same directory then we
2241 struct kvp *t = kvp_urldecode(d.data, d.size);
2242 const char *alias_target = kvp_get(t, "_alias_for");
2244 && !strcmp(d_dirname(alias_target),
2246 if(track_matches(dl, k.data, k.size, re))
2247 vector_append(v, track);
2249 /* if this file has an alias in the same directory then we skip it */
2251 if((err = compute_alias(&alias, track, p, tid)))
2253 if(!(alias && !strcmp(d_dirname(alias), d_dirname(track))))
2254 if(track_matches(dl, k.data, k.size, re))
2255 vector_append(v, track);
2259 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2267 case DB_LOCK_DEADLOCK:
2268 error(0, "error querying database: %s", db_strerror(err));
2271 fatal(0, "error querying database: %s", db_strerror(err));
2274 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2278 /* return the directories or files below @dir@ */
2279 char **trackdb_list(const char *dir, int *np, enum trackdb_listable what,
2287 tid = trackdb_begin_transaction();
2290 if(do_list(&v, dir, what, re, tid))
2293 for(n = 0; n < config->collection.n; ++n)
2294 if(do_list(&v, config->collection.s[n].root, what, re, tid))
2299 trackdb_abort_transaction(tid);
2301 trackdb_commit_transaction(tid);
2302 vector_terminate(&v);
2308 /* If S is tag:something, return something. Else return 0. */
2309 static const char *checktag(const char *s) {
2310 if(!strncmp(s, "tag:", 4))
2316 /* return a list of tracks containing all of the words given. If you
2317 * ask for only stopwords you get no tracks. */
2318 char **trackdb_search(char **wordlist, int nwordlist, int *ntracks) {
2319 const char **w, *best = 0, *tag;
2320 char **twords, **tags;
2322 int i, j, n, err, what;
2332 *ntracks = 0; /* for early returns */
2333 /* normalize all the words */
2334 w = xmalloc(nwordlist * sizeof (char *));
2335 istag = xmalloc_noptr(nwordlist);
2336 for(n = 0; n < nwordlist; ++n) {
2340 w[n] = utf8_casefold_compat(wordlist[n], strlen(wordlist[n]), 0);
2341 if(checktag(w[n])) {
2342 ++ntags; /* count up tags */
2343 /* Normalize the tag */
2344 w[n] = normalize_tag(w[n] + 4, strlen(w[n] + 4));
2347 /* Normalize the search term by removing combining characters */
2348 if(!(w32 = utf8_to_utf32(w[n], strlen(w[n]), &nw32)))
2350 nw32 = remove_combining_chars(w32, nw32);
2351 if(!(w[n] = utf32_to_utf8(w32, nw32, 0)))
2356 /* find the longest non-stopword */
2357 for(n = 0; n < nwordlist; ++n)
2358 if(!istag[n] && !stopword(w[n]))
2359 if(!best || strlen(w[n]) > strlen(best))
2361 /* TODO: we should at least in principal be able to identify the word or tag
2362 * with the least matches in log time, and choose that as our primary search
2364 if(ntags && !best) {
2365 /* Only tags are listed. We limit to the first and narrow down with the
2367 best = istag[0] ? w[0] : 0;
2368 db = trackdb_tagsdb;
2371 /* We can limit to some word. */
2372 db = trackdb_searchdb;
2375 /* Only stopwords */
2381 tid = trackdb_begin_transaction();
2382 /* find all the tracks that have that word */
2387 cursor = trackdb_opencursor(db, tid);
2388 while(!(err = cursor->c_get(cursor, &k, &d, what))) {
2389 vector_append(&v, xstrndup(d.data, d.size));
2396 case DB_LOCK_DEADLOCK:
2397 error(0, "error querying %s database: %s", dbname, db_strerror(err));
2400 fatal(0, "error querying %s database: %s", dbname, db_strerror(err));
2402 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2404 /* do a naive search over that (hopefuly fairly small) list of tracks */
2406 for(n = 0; n < v.nvec; ++n) {
2407 if((err = gettrackdata(v.vec[n], 0, &p, 0, 0, tid) == DB_LOCK_DEADLOCK))
2410 error(0, "track %s unexpected error: %s", v.vec[n], db_strerror(err));
2413 twords = track_to_words(v.vec[n], p);
2414 tags = parsetags(kvp_get(p, "tags"));
2415 for(i = 0; i < nwordlist; ++i) {
2418 /* Track must have this tag */
2419 for(j = 0; tags[j]; ++j)
2420 if(!strcmp(tag, tags[j])) break; /* tag found */
2421 if(!tags[j]) break; /* tag not found */
2423 /* Track must contain this word */
2424 for(j = 0; twords[j]; ++j)
2425 if(!strcmp(w[i], twords[j])) break; /* word found */
2426 if(!twords[j]) break; /* word not found */
2429 if(i >= nwordlist) /* all words found */
2430 vector_append(&u, v.vec[n]);
2434 trackdb_closecursor(cursor);
2436 trackdb_abort_transaction(tid);
2437 info("retrying search");
2439 trackdb_commit_transaction(tid);
2440 vector_terminate(&u);
2446 /* trackdb_scan **************************************************************/
2448 int trackdb_scan(const char *root,
2449 int (*callback)(const char *track,
2458 const size_t root_len = root ? strlen(root) : 0;
2460 struct kvp *data, *prefs;
2463 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2465 err = cursor->c_get(cursor, make_key(&k, root), prepare_data(&d),
2468 memset(&k, 0, sizeof k);
2469 err = cursor->c_get(cursor, &k, prepare_data(&d),
2474 || (k.size > root_len
2475 && !strncmp(k.data, root, root_len)
2476 && ((char *)k.data)[root_len] == '/')) {
2477 data = kvp_urldecode(d.data, d.size);
2478 if(kvp_get(data, "_path")) {
2479 track = xstrndup(k.data, k.size);
2480 /* TODO: trackdb_prefsdb is currently a DB_HASH. This means we have to
2481 * do a lookup for every single track. In fact this is quite quick:
2482 * with around 10,000 tracks a complete scan is around 0.3s on my
2483 * 2.2GHz Athlon. However, if it were a DB_BTREE, we could do the same
2484 * linear walk as we already do over trackdb_tracksdb, and probably get
2485 * even higher performance. That would require upgrade logic to
2486 * translate old databases though.
2488 switch(err = trackdb_prefsdb->get(trackdb_prefsdb, tid, &k,
2489 prepare_data(&pd), 0)) {
2491 prefs = kvp_urldecode(pd.data, pd.size);
2496 case DB_LOCK_DEADLOCK:
2497 error(0, "getting prefs: %s", db_strerror(err));
2498 trackdb_closecursor(cursor);
2501 fatal(0, "getting prefs: %s", db_strerror(err));
2503 /* Advance to the next track before the callback so that the callback
2504 * may safely delete the track */
2505 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2506 if((cberr = callback(track, data, prefs, u, tid))) {
2511 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2515 trackdb_closecursor(cursor);
2522 case DB_LOCK_DEADLOCK:
2523 error(0, "c->c_get: %s", db_strerror(err));
2526 fatal(0, "c->c_get: %s", db_strerror(err));
2530 /* trackdb_rescan ************************************************************/
2532 /** @brief Node in the list of rescan-complete callbacks */
2533 struct rescanned_node {
2534 struct rescanned_node *next;
2535 void (*rescanned)(void *ru);
2539 /** @brief List of rescan-complete callbacks */
2540 static struct rescanned_node *rescanned_list;
2542 /** @brief Add a rescan completion callback */
2543 void trackdb_add_rescanned(void (*rescanned)(void *ru),
2546 struct rescanned_node *n = xmalloc(sizeof *n);
2547 n->next = rescanned_list;
2548 n->rescanned = rescanned;
2554 /* called when the rescanner terminates */
2555 static int reap_rescan(ev_source attribute((unused)) *ev,
2558 const struct rusage attribute((unused)) *rusage,
2559 void attribute((unused)) *u) {
2560 if(pid == rescan_pid) rescan_pid = -1;
2562 error(0, RESCAN": %s", wstat(status));
2564 D((RESCAN" terminated: %s", wstat(status)));
2565 /* Our cache of file lookups is out of date now */
2566 cache_clean(&cache_files_type);
2567 eventlog("rescanned", (char *)0);
2568 /* Call rescanned callbacks */
2569 while(rescanned_list) {
2570 void (*rescanned)(void *u_) = rescanned_list->rescanned;
2571 void *ru = rescanned_list->ru;
2573 rescanned_list = rescanned_list->next;
2579 /** @brief Initiate a rescan
2580 * @param ev Event loop or 0 to block
2581 * @param recheck 1 to recheck lengths, 0 to suppress check
2582 * @param rescanned Called on completion (if not NULL)
2583 * @param ru Passed to @p rescanned
2585 void trackdb_rescan(ev_source *ev, int recheck,
2586 void (*rescanned)(void *ru),
2590 if(rescan_pid != -1) {
2591 trackdb_add_rescanned(rescanned, ru);
2592 error(0, "rescan already underway");
2595 rescan_pid = subprogram(ev, -1, RESCAN,
2596 recheck ? "--check" : "--no-check",
2598 trackdb_add_rescanned(rescanned, ru);
2600 ev_child(ev, rescan_pid, 0, reap_rescan, 0);
2601 D(("started rescanner"));
2603 /* This is the first rescan, we block until it is complete */
2604 while(waitpid(rescan_pid, &w, 0) < 0 && errno == EINTR)
2606 reap_rescan(0, rescan_pid, w, 0, 0);
2610 int trackdb_rescan_cancel(void) {
2611 if(rescan_pid == -1) return 0;
2612 if(kill(rescan_pid, SIGTERM) < 0)
2613 fatal(errno, "error killing rescanner");
2618 /** @brief Return true if a rescan is underway */
2619 int trackdb_rescan_underway(void) {
2620 return rescan_pid != -1;
2623 /* global prefs **************************************************************/
2625 void trackdb_set_global(const char *name,
2633 tid = trackdb_begin_transaction();
2634 if(!(err = trackdb_set_global_tid(name, value, tid)))
2636 trackdb_abort_transaction(tid);
2638 trackdb_commit_transaction(tid);
2639 /* log important state changes */
2640 if(!strcmp(name, "playing")) {
2641 state = !value || !strcmp(value, "yes");
2642 info("playing %s by %s",
2643 state ? "enabled" : "disabled",
2645 eventlog("state", state ? "enable_play" : "disable_play", (char *)0);
2647 if(!strcmp(name, "random-play")) {
2648 state = !value || !strcmp(value, "yes");
2649 info("random play %s by %s",
2650 state ? "enabled" : "disabled",
2652 eventlog("state", state ? "enable_random" : "disable_random", (char *)0);
2656 int trackdb_set_global_tid(const char *name,
2662 memset(&k, 0, sizeof k);
2663 memset(&d, 0, sizeof d);
2664 k.data = (void *)name;
2665 k.size = strlen(name);
2667 d.data = (void *)value;
2668 d.size = strlen(value);
2671 err = trackdb_globaldb->put(trackdb_globaldb, tid, &k, &d, 0);
2673 err = trackdb_globaldb->del(trackdb_globaldb, tid, &k, 0);
2674 if(err == DB_LOCK_DEADLOCK) return err;
2676 fatal(0, "error updating database: %s", db_strerror(err));
2680 const char *trackdb_get_global(const char *name) {
2686 tid = trackdb_begin_transaction();
2687 if(!(err = trackdb_get_global_tid(name, tid, &r)))
2689 trackdb_abort_transaction(tid);
2691 trackdb_commit_transaction(tid);
2695 int trackdb_get_global_tid(const char *name,
2701 memset(&k, 0, sizeof k);
2702 k.data = (void *)name;
2703 k.size = strlen(name);
2704 switch(err = trackdb_globaldb->get(trackdb_globaldb, tid, &k,
2705 prepare_data(&d), 0)) {
2707 *rp = xstrndup(d.data, d.size);
2712 case DB_LOCK_DEADLOCK:
2715 fatal(0, "error reading database: %s", db_strerror(err));
2719 /** @brief Retrieve the most recently added tracks
2720 * @param ntracksp Where to put count, or 0
2721 * @param maxtracks Maximum number of tracks to retrieve
2722 * @return null-terminated array of track names
2724 * The most recently added track is first in the array.
2726 char **trackdb_new(int *ntracksp,
2732 tid = trackdb_begin_transaction();
2733 tracks = trackdb_new_tid(ntracksp, maxtracks, tid);
2736 trackdb_abort_transaction(tid);
2738 trackdb_commit_transaction(tid);
2742 /** @brief Retrieve the most recently added tracks
2743 * @param ntracksp Where to put count, or 0
2744 * @param maxtracks Maximum number of tracks to retrieve, or 0 for all
2745 * @param tid Transaction ID
2746 * @return null-terminated array of track names, or NULL on deadlock
2748 * The most recently added track is first in the array.
2750 static char **trackdb_new_tid(int *ntracksp,
2756 struct vector tracks[1];
2757 hash *h = hash_new(1);
2759 vector_init(tracks);
2760 c = trackdb_opencursor(trackdb_noticeddb, tid);
2761 while((maxtracks <= 0 || tracks->nvec < maxtracks)
2762 && !(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_PREV))) {
2763 char *const track = xstrndup(d.data, d.size);
2764 /* Don't add any track more than once */
2765 if(hash_add(h, track, "", HASH_INSERT))
2767 /* See if the track still exists */
2768 err = trackdb_getdata(trackdb_tracksdb, track, NULL/*kp*/, tid);
2769 if(err == DB_NOTFOUND)
2770 continue; /* It doesn't, skip it */
2771 if(err == DB_LOCK_DEADLOCK)
2773 vector_append(tracks, track);
2776 case 0: /* hit maxtracks */
2777 case DB_NOTFOUND: /* ran out of tracks */
2779 case DB_LOCK_DEADLOCK:
2780 trackdb_closecursor(c);
2783 fatal(0, "error reading noticed.db: %s", db_strerror(err));
2785 if((err = trackdb_closecursor(c)))
2786 return 0; /* deadlock */
2787 vector_terminate(tracks);
2789 *ntracksp = tracks->nvec;
2793 /** @brief Expire noticed.db
2794 * @param earliest Earliest timestamp to keep
2796 void trackdb_expire_noticed(time_t earliest) {
2800 tid = trackdb_begin_transaction();
2801 if(!trackdb_expire_noticed_tid(earliest, tid))
2803 trackdb_abort_transaction(tid);
2805 trackdb_commit_transaction(tid);
2808 /** @brief Expire noticed.db
2809 * @param earliest Earliest timestamp to keep
2810 * @param tid Transaction ID
2811 * @return 0 or DB_LOCK_DEADLOCK
2813 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid) {
2821 c = trackdb_opencursor(trackdb_noticeddb, tid);
2822 while(!(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_NEXT))) {
2824 when = (time_t)(((uint64_t)ntohl(kk[0]) << 32) + ntohl(kk[1]));
2825 if(when >= earliest)
2827 if((err = c->c_del(c, 0))) {
2828 if(err != DB_LOCK_DEADLOCK)
2829 fatal(0, "error deleting expired noticed.db entry: %s",
2835 if(err == DB_NOTFOUND)
2837 if(err && err != DB_LOCK_DEADLOCK)
2838 fatal(0, "error expiring noticed.db: %s", db_strerror(err));
2840 if((err = trackdb_closecursor(c))) {
2841 if(err != DB_LOCK_DEADLOCK)
2842 fatal(0, "error closing cursor: %s", db_strerror(err));
2846 info("expired %d tracks from noticed.db", count);
2850 /* tidying up ****************************************************************/
2852 void trackdb_gc(void) {
2856 if((err = trackdb_env->txn_checkpoint(trackdb_env,
2857 config->checkpoint_kbyte,
2858 config->checkpoint_min,
2860 fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err));
2861 if((err = trackdb_env->log_archive(trackdb_env, &logfiles, DB_ARCH_REMOVE)))
2862 fatal(0, "trackdb_env->log_archive: %s", db_strerror(err));
2863 /* This makes catastrophic recovery impossible. However, the user can still
2864 * preserve the important data by using disorder-dump to snapshot their
2865 * prefs, and later to restore it. This is likely to have much small
2866 * long-term storage requirements than record the db logfiles. */
2869 /* user database *************************************************************/
2871 /** @brief Return true if @p user is trusted */
2872 static int trusted(const char *user) {
2875 for(n = 0; (n < config->trust.n
2876 && strcmp(config->trust.s[n], user)); ++n)
2878 return n < config->trust.n;
2881 /** @brief Return non-zero for a valid username
2883 * Currently we only allow the letters and digits in ASCII. We could be more
2884 * liberal than this but it is a nice simple test. It is critical that
2885 * semicolons are never allowed.
2887 * NB also used by playlist_parse_name() to validate playlist names!
2889 int valid_username(const char *user) {
2893 const uint8_t c = *user++;
2894 /* For now we are very strict */
2895 if((c >= 'a' && c <= 'z')
2896 || (c >= 'A' && c <= 'Z')
2897 || (c >= '0' && c <= '9'))
2905 /** @brief Add a user */
2906 static int create_user(const char *user,
2907 const char *password,
2910 const char *confirmation,
2916 /* sanity check user */
2917 if(!valid_username(user)) {
2918 error(0, "invalid username '%s'", user);
2921 if(parse_rights(rights, 0, 1)) {
2922 error(0, "invalid rights string");
2925 /* data for this user */
2927 kvp_set(&k, "password", password);
2928 kvp_set(&k, "rights", rights);
2930 kvp_set(&k, "email", email);
2932 kvp_set(&k, "confirmation", confirmation);
2933 snprintf(s, sizeof s, "%jd", (intmax_t)xtime(0));
2934 kvp_set(&k, "created", s);
2935 return trackdb_putdata(trackdb_usersdb, user, k, tid, flags);
2938 /** @brief Add one pre-existing user */
2939 static int one_old_user(const char *user, const char *password,
2943 /* www-data doesn't get added */
2944 if(!strcmp(user, "www-data")) {
2945 info("not adding www-data to user database");
2949 if(!strcmp(user, "root"))
2951 else if(trusted(user)) {
2954 parse_rights(config->default_rights, &r, 1);
2955 r &= ~(rights_type)(RIGHT_SCRATCH__MASK|RIGHT_MOVE__MASK|RIGHT_REMOVE__MASK);
2956 r |= (RIGHT_ADMIN|RIGHT_RESCAN
2957 |RIGHT_SCRATCH_ANY|RIGHT_MOVE_ANY|RIGHT_REMOVE_ANY);
2958 rights = rights_string(r);
2960 rights = config->default_rights;
2961 return create_user(user, password, rights, 0/*email*/, 0/*confirmation*/,
2962 tid, DB_NOOVERWRITE);
2965 static int trackdb_old_users_tid(DB_TXN *tid) {
2968 for(n = 0; n < config->allow.n; ++n) {
2969 switch(one_old_user(config->allow.s[n].s[0], config->allow.s[n].s[1],
2972 info("created user %s from 'allow' directive", config->allow.s[n].s[0]);
2975 error(0, "user %s already exists, delete 'allow' directive",
2976 config->allow.s[n].s[0]);
2977 /* This won't ever become fatal - eventually 'allow' will be
2980 case DB_LOCK_DEADLOCK:
2981 return DB_LOCK_DEADLOCK;
2987 /** @brief Read old 'allow' directives and copy them to the users database */
2988 void trackdb_old_users(void) {
2992 WITH_TRANSACTION(trackdb_old_users_tid(tid));
2995 /** @brief Create a root user in the user database if there is none */
2996 void trackdb_create_root(void) {
3001 /* Choose a new root password */
3002 gcry_randomize(pwbin, sizeof pwbin, GCRY_STRONG_RANDOM);
3003 pw = mime_to_base64(pwbin, sizeof pwbin);
3004 /* Create the root user if it does not exist */
3005 WITH_TRANSACTION(create_user("root", pw, "all",
3006 0/*email*/, 0/*confirmation*/,
3007 tid, DB_NOOVERWRITE));
3009 info("created root user");
3012 /** @brief Find a user's password from the database
3013 * @param user Username
3014 * @return Password or NULL
3016 * Only works if running as a user that can read the database!
3018 * If the user exists but has no password, "" is returned.
3020 const char *trackdb_get_password(const char *user) {
3023 const char *password;
3025 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3028 password = kvp_get(k, "password");
3029 return password ? password : "";
3032 /** @brief Add a new user
3033 * @param user Username
3034 * @param password Password or NULL
3035 * @param rights Initial rights
3036 * @param email Email address or NULL
3037 * @param confirmation Confirmation string or NULL
3038 * @return 0 on success, non-0 on error
3040 int trackdb_adduser(const char *user,
3041 const char *password,
3044 const char *confirmation) {
3047 WITH_TRANSACTION(create_user(user, password, rights, email, confirmation,
3048 tid, DB_NOOVERWRITE));
3050 error(0, "cannot create user '%s' because they already exist", user);
3054 info("created user '%s' with rights '%s' and email address '%s'",
3055 user, rights, email);
3057 info("created user '%s' with rights '%s'", user, rights);
3058 eventlog("user_add", user, (char *)0);
3063 /** @brief Delete a user
3064 * @param user User to delete
3065 * @return 0 on success, non-0 if the user didn't exist anyway
3067 int trackdb_deluser(const char *user) {
3070 WITH_TRANSACTION(trackdb_delkey(trackdb_usersdb, user, tid));
3072 error(0, "cannot delete user '%s' because they do not exist", user);
3075 info("deleted user '%s'", user);
3076 eventlog("user_delete", user, (char *)0);
3080 /** @brief Get user information
3081 * @param user User to query
3082 * @return Linked list of user information or NULL if user does not exist
3084 * Every user has at least a @c rights entry so NULL can be used to mean no
3087 struct kvp *trackdb_getuserinfo(const char *user) {
3091 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3098 /** @brief Edit user information
3099 * @param user User to edit
3100 * @param key Key to change
3101 * @param value Value to set, or NULL to remove
3102 * @param tid Transaction ID
3103 * @return 0, DB_LOCK_DEADLOCK or DB_NOTFOUND
3105 static int trackdb_edituserinfo_tid(const char *user, const char *key,
3106 const char *value, DB_TXN *tid) {
3110 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3112 if(!kvp_set(&k, key, value))
3113 return 0; /* no change */
3114 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3117 /** @brief Edit user information
3118 * @param user User to edit
3119 * @param key Key to change
3120 * @param value Value to set, or NULL to remove
3121 * @return 0 on success, non-0 on error
3123 int trackdb_edituserinfo(const char *user,
3124 const char *key, const char *value) {
3127 if(!strcmp(key, "rights")) {
3129 error(0, "cannot remove 'rights' key from user '%s'", user);
3132 if(parse_rights(value, 0, 1)) {
3133 error(0, "invalid rights string");
3136 } else if(!strcmp(key, "email")) {
3138 if(!email_valid(value)) {
3139 error(0, "invalid email address '%s' for user '%s'", value, user);
3143 value = 0; /* no email -> remove key */
3144 } else if(!strcmp(key, "created")) {
3145 error(0, "cannot change creation date for user '%s'", user);
3147 } else if(strcmp(key, "password")
3148 && !strcmp(key, "confirmation")) {
3149 error(0, "unknown user info key '%s' for user '%s'", key, user);
3152 WITH_TRANSACTION(trackdb_edituserinfo_tid(user, key, value, tid));
3154 error(0, "unknown user '%s'", user);
3157 eventlog("user_edit", user, key, (char *)0);
3162 /** @brief List all users
3163 * @return NULL-terminated list of users
3165 char **trackdb_listusers(void) {
3170 WITH_TRANSACTION(trackdb_listkeys(trackdb_usersdb, v, tid));
3174 /** @brief Confirm a user registration
3175 * @param user Username
3176 * @param confirmation Confirmation string
3177 * @param rightsp Where to put user rights
3178 * @param tid Transaction ID
3179 * @return 0 on success, non-0 on error
3181 static int trackdb_confirm_tid(const char *user, const char *confirmation,
3182 rights_type *rightsp,
3184 const char *stored_confirmation;
3189 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3191 if(!(stored_confirmation = kvp_get(k, "confirmation"))) {
3192 error(0, "already confirmed user '%s'", user);
3193 /* DB claims -30,800 to -30,999 so -1 should be a safe bet */
3196 if(!(rights = kvp_get(k, "rights"))) {
3197 error(0, "no rights for unconfirmed user '%s'", user);
3200 if(parse_rights(rights, rightsp, 1))
3202 if(strcmp(confirmation, stored_confirmation)) {
3203 error(0, "wrong confirmation string for user '%s'", user);
3207 kvp_set(&k, "confirmation", 0);
3208 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3211 /** @brief Confirm a user registration
3212 * @param user Username
3213 * @param confirmation Confirmation string
3214 * @param rightsp Where to put user rights
3215 * @return 0 on success, non-0 on error
3217 int trackdb_confirm(const char *user, const char *confirmation,
3218 rights_type *rightsp) {
3221 WITH_TRANSACTION(trackdb_confirm_tid(user, confirmation, rightsp, tid));
3224 info("registration confirmed for user '%s'", user);
3225 eventlog("user_confirm", user, (char *)0);
3228 error(0, "confirmation for nonexistent user '%s'", user);
3230 default: /* already reported */
3240 indent-tabs-mode:nil