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"
64 #define RESCAN "disorder-rescan"
65 #define DEADLOCK "disorder-deadlock"
67 static const char *getpart(const char *track,
72 static char **trackdb_new_tid(int *ntracksp,
75 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid);
76 static char *normalize_tag(const char *s, size_t ns);
78 const struct cache_type cache_files_type = { 86400 };
79 unsigned long cache_files_hits, cache_files_misses;
81 /** @brief Set by trackdb_open() */
82 int trackdb_existing_database;
84 /* setup and teardown ********************************************************/
86 /** @brief Database home directory
88 * All database files live below here. It had better never change.
90 static const char *home;
92 /** @brief Database environment */
95 /** @brief The tracks database
96 * - Keys are UTF-8(NFC(unicode(path name)))
97 * - Values are encoded key-value pairs
98 * - Data is reconstructable data about tracks that currently exist
100 DB *trackdb_tracksdb;
102 /** @brief The preferences database
104 * - Keys are UTF-8(NFC(unicode(path name)))
105 * - Values are encoded key-value pairs
106 * - Data is user data about tracks (that might not exist any more)
107 * and cannot be reconstructed
111 /** @brief The search database
113 * - Keys are UTF-8(NFKC(casefold(search term)))
114 * - Values are UTF-8(NFC(unicode(path name)))
115 * - There can be more than one value per key
116 * - Presence of key,value means that path matches the search terms
117 * - Only tracks fond in @ref trackdb_tracksdb are represented here
118 * - This database can be reconstructed, it contains no user data
120 DB *trackdb_searchdb;
122 /** @brief The tags database
124 * - Keys are UTF-8(NFKC(casefold(tag)))
125 * - Values are UTF-8(NFC(unicode(path name)))
126 * - There can be more than one value per key
127 * - Presence of key,value means that path matches the tag
128 * - This is always in sync with the tags preference
129 * - This database can be reconstructed, it contains no user data
131 DB *trackdb_tagsdb; /* the tags database */
133 /** @brief The global preferences database
134 * - Keys are UTF-8(NFC(preference))
135 * - Values are global preference values
136 * - Data is user data and cannot be reconstructed
138 DB *trackdb_globaldb; /* global preferences */
140 /** @brief The noticed database
141 * - Keys are 64-bit big-endian timestamps
142 * - Values are UTF-8(NFC(unicode(path name)))
143 * - There can be more than one value per key
144 * - Presence of key,value means that path was added at the given time
145 * - Data cannot be reconstructed (but isn't THAT important)
147 DB *trackdb_noticeddb; /* when track noticed */
149 /** @brief The schedule database
151 * - Keys are ID strings, generated at random
152 * - Values are encoded key-value pairs
153 * - There can be more than one value per key
154 * - Data cannot be reconstructed
156 * See @ref server/schedule.c for further information.
158 DB *trackdb_scheduledb;
160 /** @brief The user database
161 * - Keys are usernames
162 * - Values are encoded key-value pairs
163 * - Data is user data and cannot be reconstructed
167 /** @brief The playlists database
168 * - Keys are playlist names
169 * - Values are encoded key-value pairs
170 * - Data is user data and cannot be reconstructed
172 DB *trackdb_playlistsdb;
174 /** @brief Deadlock manager PID */
175 static pid_t db_deadlock_pid = -1;
177 /** @brief Rescanner PID */
178 static pid_t rescan_pid = -1;
180 /** @brief Set when the database environment exists */
181 static int initialized;
183 /** @brief Set when databases are open */
186 /** @brief Current stats subprocess PIDs */
187 static hash *stats_pids;
189 /** @brief PID of current random track chooser (disorder-choose) */
190 static pid_t choose_pid = -1;
192 /** @brief Our end of pipe from disorder-choose */
193 static int choose_fd;
195 /** @brief Callback to supply random track to */
196 static random_callback *choose_callback;
198 /** @brief Accumulator for output from disorder-choose */
199 static struct dynstr choose_output;
201 /** @brief Current completion status of disorder-choose
202 * A bitmap of @ref CHOOSE_READING and @ref CHOOSE_RUNNING.
204 static unsigned choose_complete;
206 /* @brief Exit status from disorder-choose */
207 static int choose_status;
209 /** @brief disorder-choose process is running */
210 #define CHOOSE_RUNNING 1
212 /** @brief disorder-choose pipe is still open */
213 #define CHOOSE_READING 2
215 /** @brief Comparison function for filename-based keys */
216 static int compare(DB attribute((unused)) *db_,
217 const DBT *a, const DBT *b) {
218 return compare_path_raw(a->data, a->size, b->data, b->size);
221 /** @brief Test whether the track database can be read
222 * @return 1 if it can, 0 if it cannot
224 int trackdb_readable(void) {
227 byte_xasprintf(&usersdb, "%s/users.db", config->home);
228 return access(usersdb, R_OK) == 0;
231 /** @brief Open database environment
232 * @param flags Flags word
234 * Flags should be one of:
235 * - @ref TRACKDB_NO_RECOVER
236 * - @ref TRACKDB_NORMAL_RECOVER
237 * - @ref TRACKDB_FATAL_RECOVER
238 * - @ref TRACKDB_MAY_CREATE
240 void trackdb_init(int flags) {
242 const int recover = flags & TRACKDB_RECOVER_MASK;
243 static int recover_type[] = { 0, DB_RECOVER, DB_RECOVER_FATAL };
246 assert(initialized == 0);
249 if(strcmp(home, config->home))
250 disorder_fatal(0, "cannot change db home without server restart");
254 if(flags & TRACKDB_MAY_CREATE) {
260 /* Remove world/group permissions on any regular files already in the
261 * database directory. Actually we don't care about all of them but it's
262 * easier to just do the lot. This can be revisited if it's a serious
263 * practical inconvenience for anyone.
265 * The socket, not being a regular file, is excepted.
267 if(!(dp = opendir(config->home)))
268 disorder_fatal(errno, "error reading %s", config->home);
269 while((de = readdir(dp))) {
270 byte_xasprintf(&p, "%s/%s", config->home, de->d_name);
271 if(lstat(p, &st) == 0
272 && S_ISREG(st.st_mode)
273 && (st.st_mode & 077)) {
274 if(chmod(p, st.st_mode & 07700) < 0)
275 disorder_fatal(errno, "cannot chmod %s", p);
282 /* create environment */
283 if((err = db_env_create(&trackdb_env, 0)))
284 disorder_fatal(0, "db_env_create: %s", db_strerror(err));
285 if((err = trackdb_env->set_alloc(trackdb_env,
286 xmalloc_noptr, xrealloc_noptr, xfree)))
287 disorder_fatal(0, "trackdb_env->set_alloc: %s", db_strerror(err));
288 if((err = trackdb_env->set_lk_max_locks(trackdb_env, 10000)))
289 disorder_fatal(0, "trackdb_env->set_lk_max_locks: %s", db_strerror(err));
290 if((err = trackdb_env->set_lk_max_objects(trackdb_env, 10000)))
291 disorder_fatal(0, "trackdb_env->set_lk_max_objects: %s", db_strerror(err));
292 if((err = trackdb_env->open(trackdb_env, config->home,
298 |recover_type[recover],
300 disorder_fatal(0, "trackdb_env->open %s: %s",
301 config->home, db_strerror(err));
302 trackdb_env->set_errpfx(trackdb_env, "DB");
303 trackdb_env->set_errfile(trackdb_env, stderr);
304 trackdb_env->set_verbose(trackdb_env, DB_VERB_DEADLOCK, 1);
305 trackdb_env->set_verbose(trackdb_env, DB_VERB_RECOVERY, 1);
306 trackdb_env->set_verbose(trackdb_env, DB_VERB_REPLICATION, 1);
307 D(("initialized database environment"));
310 /** @brief Called when deadlock manager terminates */
311 static int reap_db_deadlock(ev_source attribute((unused)) *ev,
312 pid_t attribute((unused)) pid,
314 const struct rusage attribute((unused)) *rusage,
315 void attribute((unused)) *u) {
316 db_deadlock_pid = -1;
318 disorder_fatal(0, "deadlock manager unexpectedly terminated: %s",
321 D(("deadlock manager terminated: %s", wstat(status)));
325 /** @brief Start a subprogram
326 * @param ev Event loop
327 * @param outputfd File descriptor to redirect @c stdout to, or -1
328 * @param prog Program name
329 * @param ... Arguments
332 * Starts a subprocess. Adds the following arguments:
333 * - @c --config to ensure the right config file is used
334 * - @c --debug or @c --no-debug to match debug settings
335 * - @c --syslog or @c --no-syslog to match log settings
337 static pid_t subprogram(ev_source *ev, int outputfd, const char *prog,
341 const char *args[1024], **argp, *a;
345 *argp++ = "--config";
346 *argp++ = configfile;
347 *argp++ = debugging ? "--debug" : "--no-debug";
348 *argp++ = log_default == &log_syslog ? "--syslog" : "--no-syslog";
350 while((a = va_arg(ap, const char *)))
354 /* If we're in the background then trap subprocess stdout/stderr */
355 if(!(pid = xfork())) {
358 ev_signal_atfork(ev);
359 signal(SIGPIPE, SIG_DFL);
364 /* ensure we don't leak privilege anywhere */
365 if(setuid(geteuid()) < 0)
366 disorder_fatal(errno, "error calling setuid");
367 /* If we were negatively niced, undo it. We don't bother checking for
368 * error, it's not that important. */
369 setpriority(PRIO_PROCESS, 0, 0);
370 execvp(prog, (char **)args);
371 disorder_fatal(errno, "error invoking %s", prog);
376 /** @brief Start deadlock manager
377 * @param ev Event loop
379 * Called from the main server (only).
381 void trackdb_master(ev_source *ev) {
382 assert(db_deadlock_pid == -1);
383 db_deadlock_pid = subprogram(ev, -1, DEADLOCK, (char *)0);
384 ev_child(ev, db_deadlock_pid, 0, reap_db_deadlock, 0);
385 D(("started deadlock manager"));
388 /** @brief Kill a subprocess and wait for it to terminate
389 * @param ev Event loop or NULL
390 * @param pid Process ID or -1
391 * @param what Description of subprocess
393 * Used during trackdb_deinit(). This function blocks so don't use it for
394 * normal teardown as that will hang the server.
396 static void terminate_and_wait(ev_source *ev,
403 if(kill(pid, SIGTERM) < 0)
404 disorder_fatal(errno, "error killing %s", what);
405 /* wait for the rescanner to finish */
406 while(waitpid(pid, &err, 0) == -1 && errno == EINTR)
409 ev_child_cancel(ev, pid);
412 /** @brief Close database environment
413 * @param ev Event loop
415 void trackdb_deinit(ev_source *ev) {
419 assert(initialized == 1);
422 /* close the environment */
423 if((err = trackdb_env->close(trackdb_env, 0)))
424 disorder_fatal(0, "trackdb_env->close: %s", db_strerror(err));
426 terminate_and_wait(ev, rescan_pid, "disorder-rescan");
428 terminate_and_wait(ev, choose_pid, "disorder-choose");
432 char **ks = hash_keys(stats_pids);
435 pid_t pid = atoi(*ks++);
436 terminate_and_wait(ev, pid, "disorder-stats");
441 terminate_and_wait(ev, db_deadlock_pid, "disorder-deadlock");
442 db_deadlock_pid = -1;
443 D(("deinitialized database environment"));
446 /** @brief Open a specific database
447 * @param path Relative path to database
448 * @param dbflags Database flags: DB_DUP, DB_DUPSORT, etc
449 * @param dbtype Database type: DB_HASH, DB_BTREE, etc
450 * @param openflags Open flags: DB_RDONLY, DB_CREATE, etc
451 * @param mode Permission mask: usually 0666
452 * @return Database handle
454 static DB *open_db(const char *path,
462 D(("open %s", path));
463 path = config_get_file(path);
464 if((err = db_create(&db, trackdb_env, 0)))
465 disorder_fatal(0, "db_create %s: %s", path, db_strerror(err));
467 if((err = db->set_flags(db, dbflags)))
468 disorder_fatal(0, "db->set_flags %s: %s", path, db_strerror(err));
469 if(dbtype == DB_BTREE)
470 if((err = db->set_bt_compare(db, compare)))
471 disorder_fatal(0, "db->set_bt_compare %s: %s", path, db_strerror(err));
472 if((err = db->open(db, 0, path, 0, dbtype,
473 openflags | DB_AUTO_COMMIT, mode))) {
474 if((openflags & DB_CREATE) || errno != ENOENT) {
475 if((err2 = db->close(db, 0)))
476 disorder_error(0, "db->close: %s", db_strerror(err2));
478 trackdb_env->close(trackdb_env,0);
480 disorder_fatal(0, "db->open %s: %s", path, db_strerror(err));
488 /** @brief Open track databases
489 * @param flags Flags flags word
491 * @p flags should have one of:
492 * - @p TRACKDB_NO_UPGRADE, if no upgrade should be attempted
493 * - @p TRACKDB_CAN_UPGRADE, if an upgrade may be attempted
494 * - @p TRACKDB_OPEN_FOR_UPGRADE, if this is disorder-dbupgrade
496 * - @p TRACKDB_READ_ONLY, read only access
498 void trackdb_open(int flags) {
501 uint32_t dbflags = flags & TRACKDB_READ_ONLY ? DB_RDONLY : DB_CREATE;
506 /* check the database version first */
507 trackdb_globaldb = open_db("global.db", 0, DB_HASH, DB_RDONLY, 0666);
508 if(trackdb_globaldb) {
509 /* This is an existing database */
513 s = trackdb_get_global("_dbversion");
514 /* Close the database again, we'll open it property below */
515 if((err = trackdb_globaldb->close(trackdb_globaldb, 0)))
516 disorder_fatal(0, "error closing global.db: %s", db_strerror(err));
517 trackdb_globaldb = 0;
518 /* Convert version string to an integer */
519 oldversion = s ? atol(s) : 1;
520 if(oldversion > config->dbversion) {
521 /* Database is from the future; we never allow this. */
522 disorder_fatal(0, "this version of DisOrder is too old for database version %ld",
525 if(oldversion < config->dbversion) {
526 /* Database version is out of date */
527 switch(flags & TRACKDB_UPGRADE_MASK) {
528 case TRACKDB_NO_UPGRADE:
529 /* This database needs upgrading but this is not permitted */
530 disorder_fatal(0, "database needs upgrading from %ld to %ld",
531 oldversion, config->dbversion);
532 case TRACKDB_CAN_UPGRADE:
533 /* This database needs upgrading */
534 disorder_info("invoking disorder-dbupgrade to upgrade from %ld to %ld",
535 oldversion, config->dbversion);
536 pid = subprogram(0, -1, "disorder-dbupgrade", (char *)0);
537 while(waitpid(pid, &err, 0) == -1 && errno == EINTR)
540 disorder_fatal(0, "disorder-dbupgrade %s", wstat(err));
541 disorder_info("disorder-dbupgrade succeeded");
543 case TRACKDB_OPEN_FOR_UPGRADE:
549 if(oldversion == config->dbversion && (flags & TRACKDB_OPEN_FOR_UPGRADE)) {
550 /* This doesn't make any sense */
551 disorder_fatal(0, "database is already at current version");
553 trackdb_existing_database = 1;
555 if(flags & TRACKDB_OPEN_FOR_UPGRADE) {
556 /* Cannot upgrade a new database */
557 disorder_fatal(0, "cannot upgrade a database that does not exist");
559 /* This is a brand new database */
560 trackdb_existing_database = 0;
562 /* open the databases */
563 if(!(trackdb_usersdb = open_db("users.db",
564 0, DB_HASH, dbflags, 0600)))
565 disorder_fatal(0, "cannot open users.db");
566 trackdb_tracksdb = open_db("tracks.db",
567 DB_RECNUM, DB_BTREE, dbflags, 0666);
568 trackdb_searchdb = open_db("search.db",
569 DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
570 trackdb_tagsdb = open_db("tags.db",
571 DB_DUP|DB_DUPSORT, DB_HASH, dbflags, 0666);
572 trackdb_prefsdb = open_db("prefs.db", 0, DB_HASH, dbflags, 0666);
573 trackdb_globaldb = open_db("global.db", 0, DB_HASH, dbflags, 0666);
574 trackdb_noticeddb = open_db("noticed.db",
575 DB_DUPSORT, DB_BTREE, dbflags, 0666);
576 trackdb_scheduledb = open_db("schedule.db", 0, DB_HASH, dbflags, 0666);
577 trackdb_playlistsdb = open_db("playlists.db", 0, DB_HASH, dbflags, 0666);
578 if(!trackdb_existing_database && !(flags & TRACKDB_READ_ONLY)) {
579 /* Stash the database version */
582 assert(!(flags & TRACKDB_OPEN_FOR_UPGRADE));
583 snprintf(buf, sizeof buf, "%ld", config->dbversion);
584 trackdb_set_global("_dbversion", buf, 0);
586 D(("opened databases"));
589 /** @brief Close track databases */
590 void trackdb_close(void) {
596 #define CLOSE(N, V) do { \
597 if(V && (err = V->close(V, 0))) \
598 disorder_fatal(0, "error closing %s: %s", N, db_strerror(err)); \
601 CLOSE("tracks.db", trackdb_tracksdb);
602 CLOSE("search.db", trackdb_searchdb);
603 CLOSE("tags.db", trackdb_tagsdb);
604 CLOSE("prefs.db", trackdb_prefsdb);
605 CLOSE("global.db", trackdb_globaldb);
606 CLOSE("noticed.db", trackdb_noticeddb);
607 CLOSE("schedule.db", trackdb_scheduledb);
608 CLOSE("users.db", trackdb_usersdb);
609 CLOSE("playlists.db", trackdb_playlistsdb);
610 D(("closed databases"));
613 /* generic db routines *******************************************************/
615 /** @brief Fetch and decode a database entry
617 * @param track Track name
618 * @param kp Where to put decoded list (or NULL if you don't care)
619 * @param tid Owning transaction
620 * @return 0, @c DB_NOTFOUND or @c DB_LOCK_DEADLOCK
622 int trackdb_getdata(DB *db,
629 switch(err = db->get(db, tid, make_key(&key, track),
630 prepare_data(&data), 0)) {
633 *kp = kvp_urldecode(data.data, data.size);
639 case DB_LOCK_DEADLOCK:
640 disorder_error(0, "error querying database: %s", db_strerror(err));
643 disorder_fatal(0, "error querying database: %s", db_strerror(err));
647 /** @brief Encode and store a database entry
649 * @param track Track name
650 * @param k List of key/value pairs to store
651 * @param tid Owning transaction
652 * @param flags DB flags e.g. DB_NOOVERWRITE
653 * @return 0, DB_KEYEXIST or DB_LOCK_DEADLOCK
655 int trackdb_putdata(DB *db,
663 switch(err = db->put(db, tid, make_key(&key, track),
664 encode_data(&data, k), flags)) {
668 case DB_LOCK_DEADLOCK:
669 disorder_error(0, "error updating database: %s", db_strerror(err));
672 disorder_fatal(0, "error updating database: %s", db_strerror(err));
676 /** @brief Delete a database entry
678 * @param track Key to delete
679 * @param tid Transaction ID
680 * @return 0, DB_NOTFOUND or DB_LOCK_DEADLOCK
682 int trackdb_delkey(DB *db,
688 switch(err = db->del(db, tid, make_key(&key, track), 0)) {
692 case DB_LOCK_DEADLOCK:
693 disorder_error(0, "error updating database: %s", db_strerror(err));
696 disorder_fatal(0, "error updating database: %s", db_strerror(err));
700 /** @brief Open a database cursor
702 * @param tid Owning transaction
705 DBC *trackdb_opencursor(DB *db, DB_TXN *tid) {
709 switch(err = db->cursor(db, tid, &c, 0)) {
711 default: disorder_fatal(0, "error creating cursor: %s", db_strerror(err));
716 /** @brief Close a database cursor
718 * @return 0 or DB_LOCK_DEADLOCK
720 int trackdb_closecursor(DBC *c) {
724 switch(err = c->c_close(c)) {
727 case DB_LOCK_DEADLOCK:
728 disorder_error(0, "error closing cursor: %s", db_strerror(err));
731 disorder_fatal(0, "error closing cursor: %s", db_strerror(err));
735 /** @brief Delete a key/data pair
739 * @param tid Owning transaction
740 * @return 0, DB_NOTFOUND or DB_LOCK_DEADLOCK
742 * Used by the search and tags databases, hence the odd parameter names.
743 * See also register_word().
745 int trackdb_delkeydata(DB *db,
753 c = trackdb_opencursor(db, tid);
754 switch(err = c->c_get(c, make_key(&key, word),
755 make_key(&data, track), DB_GET_BOTH)) {
757 switch(err = c->c_del(c, 0)) {
763 case DB_LOCK_DEADLOCK:
764 disorder_error(0, "error updating database: %s", db_strerror(err));
767 disorder_fatal(0, "c->c_del: %s", db_strerror(err));
772 case DB_LOCK_DEADLOCK:
773 disorder_error(0, "error updating database: %s", db_strerror(err));
776 disorder_fatal(0, "c->c_get: %s", db_strerror(err));
778 if(trackdb_closecursor(c)) err = DB_LOCK_DEADLOCK;
782 /** @brief Start a transaction
783 * @return Transaction
785 DB_TXN *trackdb_begin_transaction(void) {
789 if((err = trackdb_env->txn_begin(trackdb_env, 0, &tid, 0)))
790 disorder_fatal(0, "trackdb_env->txn_begin: %s", db_strerror(err));
794 /** @brief Abort transaction
795 * @param tid Transaction (or NULL)
797 * If @p tid is NULL then nothing happens.
799 void trackdb_abort_transaction(DB_TXN *tid) {
803 if((err = tid->abort(tid)))
804 disorder_fatal(0, "tid->abort: %s", db_strerror(err));
807 /** @brief Commit transaction
808 * @param tid Transaction (must not be NULL)
810 void trackdb_commit_transaction(DB_TXN *tid) {
813 if((err = tid->commit(tid, 0)))
814 disorder_fatal(0, "tid->commit: %s", db_strerror(err));
817 /* search/tags shared code ***************************************************/
819 /** @brief Comparison function used by dedupe()
820 * @param a Pointer to first key
821 * @param b Pointer to second key
826 static int wordcmp(const void *a, const void *b) {
827 return strcmp(*(const char **)a, *(const char **)b);
830 /** @brief Sort and de-duplicate @p vec
831 * @param vec Vector to sort
832 * @param nvec Length of @p vec
835 * The returned vector is NULL-terminated, and there must be room for this NULL
836 * even if there are no duplicates (i.e. it must have more than @p nvec
839 static char **dedupe(char **vec, int nvec) {
842 qsort(vec, nvec, sizeof (char *), wordcmp);
846 for(n = 1; n < nvec; ++n)
847 if(strcmp(vec[n], vec[m - 1]))
854 /** @brief Store a key/data pair
856 * @param what Description
859 * @param tid Owning transaction
860 * @return 0 or DB_DEADLOCK
862 * Used by the search and tags databases, hence the odd parameter names.
863 * See also trackdb_delkeydata().
865 static int register_word(DB *db, const char *what,
866 const char *track, const char *word,
871 switch(err = db->put(db, tid, make_key(&key, word),
872 make_key(&data, track), DB_NODUPDATA)) {
876 case DB_LOCK_DEADLOCK:
877 disorder_error(0, "error updating %s.db: %s", what, db_strerror(err));
880 disorder_fatal(0, "error updating %s.db: %s", what, db_strerror(err));
884 /* search primitives *********************************************************/
886 /** @brief Return true iff @p name is a trackname_display_ pref
887 * @param name Preference name
888 * @return Non-zero iff @p name is a trackname_display_ pref
890 static int is_display_pref(const char *name) {
891 static const char prefix[] = "trackname_display_";
892 return !strncmp(name, prefix, (sizeof prefix) - 1);
895 /** @brief Word_Break property tailor that treats underscores as spaces
896 * @param c Code point
897 * @return Tailored property or -1 to use standard value
899 * Passed to utf32_word_split() when splitting a track name into words.
900 * See word_split() and @ref unicode_property_tailor.
902 static int tailor_underscore_Word_Break_Other(uint32_t c) {
906 case 0x005F: /* LOW LINE (SPACING UNDERSCORE) */
907 return unicode_Word_Break_Other;
911 /** @brief Remove all combining characters in-place
912 * @param s Pointer to start of string
913 * @param ns Length of string
914 * @return New, possiblby reduced, length
916 static size_t remove_combining_chars(uint32_t *s, size_t ns) {
917 uint32_t *start = s, *t = s, *end = s + ns;
920 const uint32_t c = *s++;
921 if(!utf32_combining_class(c))
927 /** @brief Normalize and split a string using a given tailoring
928 * @param v Where to store words from string
929 * @param s Input string
930 * @param pt Word_Break property tailor, or NULL
932 * The output words will be:
934 * - have any combination characters stripped
935 * - not include any word break code points (as tailored)
937 * Used by track_to_words(), with @p pt set to @ref
938 * tailor_underscore_Word_Break_Other, and by normalize_tag() with no
941 static void word_split(struct vector *v,
943 unicode_property_tailor *pt) {
945 uint32_t *t32, **w32;
947 /* Convert to UTF-32 */
948 if(!(t32 = utf8_to_utf32(s, strlen(s), &nt32)))
950 /* Erase case distinctions */
951 if(!(t32 = utf32_casefold_compat(t32, nt32, &nt32)))
953 /* Drop combining characters */
954 nt32 = remove_combining_chars(t32, nt32);
955 /* Split into words, treating _ as a space */
956 w32 = utf32_word_split(t32, nt32, &nw, pt);
957 /* Convert words back to UTF-8 and append to result */
958 for(i = 0; i < nw; ++i)
959 vector_append(v, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
962 /** @brief Normalize a tag
964 * @param ns Length of tag
965 * @return Normalized string or NULL on error
967 * The return value will be:
969 * - have no leading or trailing space
970 * - have no combining characters
971 * - all spacing between words will be a single U+0020 SPACE
973 static char *normalize_tag(const char *s, size_t ns) {
974 uint32_t *s32, **w32;
975 size_t ns32, nw32, i;
978 if(!(s32 = utf8_to_utf32(s, ns, &ns32)))
980 if(!(s32 = utf32_casefold_compat(s32, ns32, &ns32))) /* ->NFKD */
982 ns32 = remove_combining_chars(s32, ns32);
983 /* Split into words, no Word_Break tailoring */
984 w32 = utf32_word_split(s32, ns32, &nw32, 0);
985 /* Compose back into a string */
987 for(i = 0; i < nw32; ++i) {
989 dynstr_append(d, ' ');
990 dynstr_append_string(d, utf32_to_utf8(w32[i], utf32_len(w32[i]), 0));
996 /** @brief Compute the words of a track name
997 * @param track Track name
998 * @param p Preferences (for display prefs)
999 * @return NULL-terminated, de-duplicated list or words
1001 static char **track_to_words(const char *track,
1002 const struct kvp *p) {
1004 const char *rootless = track_rootless(track);
1007 rootless = track; /* bodge */
1009 rootless = strip_extension(rootless);
1010 word_split(&v, strip_extension(rootless), tailor_underscore_Word_Break_Other);
1011 for(; p; p = p->next)
1012 if(is_display_pref(p->name))
1013 word_split(&v, p->value, 0);
1014 vector_terminate(&v);
1015 return dedupe(v.vec, v.nvec);
1018 /** @brief Test for a stopword
1020 * @return Non-zero if @p word is a stopword
1022 static int stopword(const char *word) {
1025 for(n = 0; n < config->stopword.n
1026 && strcmp(word, config->stopword.s[n]); ++n)
1028 return n < config->stopword.n;
1031 /** @brief Register a search term
1032 * @param track Track name
1033 * @param word A word that appears in the name of @p track
1034 * @param tid Owning transaction
1035 * @return 0 or DB_LOCK_DEADLOCK
1037 static int register_search_word(const char *track, const char *word,
1039 if(stopword(word)) return 0;
1040 return register_word(trackdb_searchdb, "search", track, word, tid);
1043 /* Tags **********************************************************************/
1045 /** @brief Test for tag characters
1046 * @param c Character
1047 * @return Non-zero if @p c is a tag character
1049 * The current rule is that commas and the control characters 0-31 are not
1050 * allowed but anything else is permitted. This is arguably a bit loose.
1052 static int tagchar(int c) {
1061 /** @brief Parse a tag list
1062 * @param s Tag list or NULL (equivalent to "")
1063 * @return Parsed tag list
1065 * The tags will be normalized (as per normalize_tag()) and de-duplicated.
1067 char **parsetags(const char *s) {
1073 /* skip initial separators */
1074 while(*s && (!tagchar(*s) || *s == ' '))
1077 /* find the extent of the tag */
1079 while(*s && tagchar(*s))
1081 /* strip trailing spaces */
1082 while(s > t && s[-1] == ' ')
1084 /* add tag to list */
1085 vector_append(&v, normalize_tag(t, (size_t)(s - t)));
1086 /* skip intermediate and trailing separators */
1087 while(*s && (!tagchar(*s) || *s == ' '))
1091 vector_terminate(&v);
1092 return dedupe(v.vec, v.nvec);
1095 /** @brief Register a tag
1096 * @param track Track name
1097 * @param tag Tag name
1098 * @param tid Owning transaction
1099 * @return 0 or DB_LOCK_DEADLOCK
1101 static int register_tag(const char *track, const char *tag, DB_TXN *tid) {
1102 return register_word(trackdb_tagsdb, "tags", track, tag, tid);
1105 /* aliases *******************************************************************/
1107 /** @brief Compute an alias
1108 * @param aliasp Where to put alias (gets NULL if none)
1109 * @param track Track to find alias for
1110 * @param p Prefs for @p track
1111 * @param tid Owning transaction
1112 * @return 0 or DB_LOCK_DEADLOCK
1114 * This function looks up the track name parts for @p track. By default these
1115 * amount to the original values from the track name but are overridden by
1118 * These values are then substituted into the pattern defined by the @b alias
1119 * command; see disorder_config(5) for the syntax.
1121 * The track is only considered to have an alias if all of the following are
1123 * - a preference was used for at least one name part
1124 * - the result differs from the original track name
1125 * - the result does not match any existing track or alias
1127 static int compute_alias(char **aliasp,
1129 const struct kvp *p,
1132 const char *s = config->alias, *t, *expansion, *part;
1133 int c, used_db = 0, slash_prefix, err;
1135 const char *const root = find_track_root(track);
1138 /* Bodge for tracks with no root */
1143 dynstr_append_string(&d, root);
1144 while((c = (unsigned char)*s++)) {
1146 dynstr_append(&d, c);
1149 if((slash_prefix = (*s == '/')))
1152 assert(t != 0); /* validated at startup */
1153 part = xstrndup(s, t - s);
1154 expansion = getpart(track, "display", part, p, &used_db);
1156 if(slash_prefix) dynstr_append(&d, '/');
1157 dynstr_append_string(&d, expansion);
1159 s = t + 1; /* skip {part} */
1161 /* only admit to the alias if we used the db... */
1166 dynstr_terminate(&d);
1167 /* ...and the answer differs from the original... */
1168 if(!strcmp(track, d.vec)) {
1172 /* ...and there isn't already a different track with that name (including as
1174 switch(err = trackdb_getdata(trackdb_tracksdb, d.vec, &at, tid)) {
1176 if((s = kvp_get(at, "_alias_for"))
1177 && !strcmp(s, track)) {
1189 /** @brief Assert that no alias is allowed for gettrackdata() */
1190 #define GTD_NOALIAS 0x0001
1192 /** @brief Get all track data
1193 * @param track Track to look up; aliases allowed unless @ref GTD_NOALIAS
1194 * @param tp Where to put track data (if not NULL)
1195 * @param pp Where to put preferences (if not NULL)
1196 * @param actualp Where to put real (i.e. non-alias) path (if not NULL)
1197 * @param flags Flag values, see below
1198 * @param tid Owning transaction
1199 * @return 0, DB_NOTFOUND (track doesn't exist) or DB_LOCK_DEADLOCK
1201 * Possible flags values are:
1202 * - @ref GTD_NOALIAS to assert that an alias is not allowed
1204 * The return values are always set (even if to NULL).
1206 static int gettrackdata(const char *track,
1209 const char **actualp,
1213 const char *actual = track;
1214 struct kvp *t = 0, *p = 0;
1216 if((err = trackdb_getdata(trackdb_tracksdb, track, &t, tid))) goto done;
1217 if((actual = kvp_get(t, "_alias_for"))) {
1218 if(flags & GTD_NOALIAS) {
1220 "alias passed to gettrackdata where real path required");
1223 if((err = trackdb_getdata(trackdb_tracksdb, actual, &t, tid))) goto done;
1226 assert(actual != 0);
1228 if((err = trackdb_getdata(trackdb_prefsdb, actual, &p, tid)) == DB_LOCK_DEADLOCK)
1233 if(actualp) *actualp = actual;
1239 /* trackdb_notice() **********************************************************/
1241 /** @brief Notice a possibly new track
1242 * @param track NFC UTF-8 track name
1243 * @param path Raw path name (i.e. the bytes that came out of readdir())
1244 * @return @c DB_NOTFOUND if new, 0 if already known
1246 * @c disorder-rescan is responsible for normalizing the track name.
1248 int trackdb_notice(const char *track,
1254 tid = trackdb_begin_transaction();
1255 err = trackdb_notice_tid(track, path, tid);
1256 if((err == DB_LOCK_DEADLOCK)) goto fail;
1259 trackdb_abort_transaction(tid);
1261 trackdb_commit_transaction(tid);
1265 /** @brief Notice a possibly new track
1266 * @param track NFC UTF-8 track name
1267 * @param path Raw path name (i.e. the bytes that came out of readdir())
1268 * @param tid Owning transaction
1269 * @return @c DB_NOTFOUND if new, 0 if already known, @c DB_LOCK_DEADLOCK also
1271 * @c disorder-rescan is responsible for normalizing the track name.
1273 int trackdb_notice_tid(const char *track,
1277 struct kvp *t, *a, *p;
1279 char *alias, **w, *noticed;
1282 /* notice whether the tracks.db entry changes */
1284 /* get any existing tracks entry */
1285 if((err = gettrackdata(track, &t, &p, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1287 ret = err; /* 0 or DB_NOTFOUND */
1288 /* this is a real track */
1289 t_changed += kvp_set(&t, "_alias_for", 0);
1290 t_changed += kvp_set(&t, "_path", path);
1292 if(ret == DB_NOTFOUND) {
1293 /* It's a new track; record the time */
1294 byte_xasprintf(¬iced, "%lld", (long long)now);
1295 t_changed += kvp_set(&t, "_noticed", noticed);
1297 /* if we have an alias record it in the database */
1298 if((err = compute_alias(&alias, track, p, tid))) return err;
1300 /* won't overwrite someone else's alias as compute_alias() checks */
1301 D(("%s: alias %s", track, alias));
1303 kvp_set(&a, "_alias_for", track);
1304 if((err = trackdb_putdata(trackdb_tracksdb, alias, a, tid, 0))) return err;
1306 /* update search.db */
1307 w = track_to_words(track, p);
1308 for(n = 0; w[n]; ++n)
1309 if((err = register_search_word(track, w[n], tid)))
1311 /* update tags.db */
1312 w = parsetags(kvp_get(p, "tags"));
1313 for(n = 0; w[n]; ++n)
1314 if((err = register_tag(track, w[n], tid)))
1316 /* only store the tracks.db entry if it has changed */
1317 if(t_changed && (err = trackdb_putdata(trackdb_tracksdb, track, t, tid, 0)))
1319 if(ret == DB_NOTFOUND) {
1320 uint32_t timestamp[2];
1323 timestamp[0] = htonl((uint64_t)now >> 32);
1324 timestamp[1] = htonl((uint32_t)now);
1325 memset(&key, 0, sizeof key);
1326 key.data = timestamp;
1327 key.size = sizeof timestamp;
1328 switch(err = trackdb_noticeddb->put(trackdb_noticeddb, tid, &key,
1329 make_key(&data, track), 0)) {
1331 case DB_LOCK_DEADLOCK: return err;
1333 disorder_fatal(0, "error updating noticed.db: %s", db_strerror(err));
1339 /* trackdb_obsolete() ********************************************************/
1341 /** @brief Obsolete a track
1342 * @param track Track name
1343 * @param tid Owning transaction
1344 * @return 0 or DB_LOCK_DEADLOCK
1346 * Discards a track from the database when it's known not to exist any more.
1347 * Returns 0 even if it wasn't recorded.
1349 int trackdb_obsolete(const char *track, DB_TXN *tid) {
1354 if((err = gettrackdata(track, 0, &p, 0,
1355 GTD_NOALIAS, tid)) == DB_LOCK_DEADLOCK)
1357 else if(err == DB_NOTFOUND) return 0;
1358 /* compute the alias, if any, and delete it */
1359 if((err = compute_alias(&alias, track, p, tid))) return err;
1361 /* if the alias points to some other track then compute_alias won't
1363 if((err = trackdb_delkey(trackdb_tracksdb, alias, tid))
1364 && err != DB_NOTFOUND)
1367 /* update search.db */
1368 w = track_to_words(track, p);
1369 for(n = 0; w[n]; ++n)
1370 if(trackdb_delkeydata(trackdb_searchdb,
1371 w[n], track, tid) == DB_LOCK_DEADLOCK)
1373 /* update tags.db */
1374 w = parsetags(kvp_get(p, "tags"));
1375 for(n = 0; w[n]; ++n)
1376 if(trackdb_delkeydata(trackdb_tagsdb,
1377 w[n], track, tid) == DB_LOCK_DEADLOCK)
1379 /* update tracks.db */
1380 if(trackdb_delkey(trackdb_tracksdb, track, tid) == DB_LOCK_DEADLOCK)
1382 /* We don't delete the prefs, so they survive temporary outages of the
1383 * (possibly virtual) track filesystem */
1387 /* trackdb_stats() ***********************************************************/
1389 #define H(name) { #name, offsetof(DB_HASH_STAT, name) }
1390 #define B(name) { #name, offsetof(DB_BTREE_STAT, name) }
1392 /** @brief Table of libdb stats to return */
1393 static const struct statinfo {
1396 } statinfo_hash[] = {
1412 }, statinfo_btree[] = {
1433 /** @brief Look up DB statistics
1434 * @param v Where to store stats
1435 * @param database Database
1436 * @param si Pointer to table of stats
1437 * @param nsi Size of @p si
1438 * @param tid Owning transaction
1439 * @return 0 or DB_LOCK_DEADLOCK
1441 static int get_stats(struct vector *v,
1443 const struct statinfo *si,
1452 switch(err = database->stat(database, tid, &sp, 0)) {
1455 case DB_LOCK_DEADLOCK:
1456 disorder_error(0, "error querying database: %s", db_strerror(err));
1459 disorder_fatal(0, "error querying database: %s", db_strerror(err));
1461 for(n = 0; n < nsi; ++n) {
1462 byte_xasprintf(&str, "%s=%"PRIuMAX, si[n].name,
1463 (uintmax_t)*(u_int32_t *)((char *)sp + si[n].offset));
1464 vector_append(v, str);
1470 /** @brief One entry in the search league */
1471 struct search_entry {
1476 /** @brief Add a word to the search league
1477 * @param se Pointer to search league
1478 * @param count Maximum size for search league
1479 * @param nse Current size of search league
1480 * @param word New word, or NULL
1481 * @param n How often @p word appears
1482 * @return New size of search league
1484 static int register_search_entry(struct search_entry *se,
1491 if(word && (nse < count || n > se[nse - 1].n)) {
1492 /* Find the starting point */
1497 /* Find the insertion point */
1498 while(i > 0 && n > se[i - 1].n)
1500 memmove(&se[i + 1], &se[i], (nse - i - 1) * sizeof *se);
1507 /** @brief Find the top @p count words in the search database
1508 * @param v Where to format the result
1509 * @param count Maximum number of words
1510 * @param tid Owning transaction
1511 * @return 0 or DB_LOCK_DEADLOCK
1513 static int search_league(struct vector *v, int count, DB_TXN *tid) {
1514 struct search_entry *se;
1517 int err, n = 0, nse = 0, i;
1522 cursor = trackdb_opencursor(trackdb_searchdb, tid);
1523 se = xmalloc(count * sizeof *se);
1524 /* Walk across the whole database counting up the number of times each
1526 while(!(err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
1528 if(word && wl == k.size && !strncmp(word, k.data, wl))
1529 ++n; /* same word again */
1531 nse = register_search_entry(se, count, nse, word, n);
1532 word = xstrndup(k.data, wl = k.size);
1540 case DB_LOCK_DEADLOCK:
1541 disorder_error(0, "error querying search database: %s", db_strerror(err));
1544 disorder_fatal(0, "error querying search database: %s", db_strerror(err));
1546 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1548 nse = register_search_entry(se, count, nse, word, n);
1549 byte_xasprintf(&str, "Top %d search words:", nse);
1550 vector_append(v, str);
1551 for(i = 0; i < nse; ++i) {
1552 byte_xasprintf(&str, "%4d: %5d %s", i + 1, se[i].n, se[i].word);
1553 vector_append(v, str);
1558 #define SI(what) statinfo_##what, \
1559 sizeof statinfo_##what / sizeof (struct statinfo)
1561 /** @brief Return a list of database stats
1562 * @param nstatsp Where to store number of lines (or NULL)
1563 * @return Database stats output
1565 * This is called by @c disorder-stats. Don't call it directly from elsewhere
1566 * as it can take unreasonably long.
1568 char **trackdb_stats(int *nstatsp) {
1574 tid = trackdb_begin_transaction();
1576 vector_append(&v, (char *)"Tracks database stats:");
1577 if(get_stats(&v, trackdb_tracksdb, SI(btree), tid)) goto fail;
1578 vector_append(&v, (char *)"");
1579 vector_append(&v, (char *)"Search database stats:");
1580 if(get_stats(&v, trackdb_searchdb, SI(hash), tid)) goto fail;
1581 vector_append(&v, (char *)"");
1582 vector_append(&v, (char *)"Prefs database stats:");
1583 if(get_stats(&v, trackdb_prefsdb, SI(hash), tid)) goto fail;
1584 vector_append(&v, (char *)"");
1585 if(search_league(&v, 10, tid)) goto fail;
1586 vector_terminate(&v);
1589 trackdb_abort_transaction(tid);
1591 trackdb_commit_transaction(tid);
1592 if(nstatsp) *nstatsp = v.nvec;
1596 /** @brief State structure tracking @c disorder-stats */
1597 struct stats_details {
1598 void (*done)(char *data, void *u);
1600 int exited; /* subprocess exited */
1601 int closed; /* pipe close */
1602 int wstat; /* wait status from subprocess */
1603 struct dynstr data[1]; /* data read from pipe */
1606 /** @brief Called when @c disorder-stats may have completed
1607 * @param d Pointer to state structure
1609 * Called from stats_finished() and stats_read(). Only proceeds when the
1610 * process has terminated and the output is complete.
1612 static void stats_complete(struct stats_details *d) {
1615 if(!(d->exited && d->closed))
1617 byte_xasprintf(&s, "\n"
1619 "track lookup cache hits: %lu\n"
1620 "track lookup cache misses: %lu\n",
1622 cache_files_misses);
1623 dynstr_append_string(d->data, s);
1624 dynstr_terminate(d->data);
1625 d->done(d->data->vec, d->u);
1628 /** @brief Called when @c disorder-stats exits
1629 * @param ev Event loop
1630 * @param pid Process ID
1631 * @param status Exit status
1632 * @param rusage Resource usage
1633 * @param u Pointer to state structure (@ref stats_details)
1636 static int stats_finished(ev_source attribute((unused)) *ev,
1639 const struct rusage attribute((unused)) *rusage,
1641 struct stats_details *const d = u;
1645 disorder_error(0, "disorder-stats %s", wstat(status));
1648 byte_xasprintf(&k, "%lu", (unsigned long)pid);
1649 hash_remove(stats_pids, k);
1653 /** @brief Called when pipe from @c disorder-stats is readable
1654 * @param ev Event loop
1655 * @param reader Reader state
1656 * @param ptr Pointer to bytes read
1657 * @param bytes Number of bytes available
1658 * @param eof Set at end of file
1659 * @param u Pointer to state structure (@ref stats_details)
1662 static int stats_read(ev_source attribute((unused)) *ev,
1668 struct stats_details *const d = u;
1670 dynstr_append_bytes(d->data, ptr, bytes);
1671 ev_reader_consume(reader, bytes);
1678 /** @brief Called when pipe from @c disorder-stats errors
1679 * @param ev Event loop
1680 * @param errno_value Error code
1681 * @param u Pointer to state structure (@ref stats_details)
1684 static int stats_error(ev_source attribute((unused)) *ev,
1687 struct stats_details *const d = u;
1689 disorder_error(errno_value, "error reading from pipe to disorder-stats");
1695 /** @brief Get database statistics via background process
1696 * @param ev Event loop
1697 * @param done Called on completion
1698 * @param u Passed to @p done
1700 * Within the main server use this instead of trackdb_stats(), which can take
1701 * unreasonably long.
1703 void trackdb_stats_subprocess(ev_source *ev,
1704 void (*done)(char *data, void *u),
1708 struct stats_details *d = xmalloc(sizeof *d);
1710 dynstr_init(d->data);
1714 pid = subprogram(ev, p[1], "disorder-stats", (char *)0);
1716 ev_child(ev, pid, 0, stats_finished, d);
1717 if(!ev_reader_new(ev, p[0], stats_read, stats_error, d,
1718 "disorder-stats reader"))
1719 disorder_fatal(0, "ev_reader_new for disorder-stats reader failed");
1720 /* Remember the PID */
1722 stats_pids = hash_new(1);
1724 byte_xasprintf(&k, "%lu", (unsigned long)pid);
1725 hash_add(stats_pids, k, "", HASH_INSERT);
1728 /** @brief Parse a track name part preference
1729 * @param name Preference name
1730 * @param partp Where to store part name
1731 * @param contextp Where to store context name
1732 * @return 0 on success, non-0 if parse fails
1734 static int trackdb__parse_namepref(const char *name,
1738 static const char prefix[] = "trackname_";
1740 if(strncmp(name, prefix, strlen(prefix)))
1741 return -1; /* not trackname_* at all */
1742 name += strlen(prefix);
1743 /* There had better be a _ between context and part */
1744 c = strchr(name, '_');
1747 /* Context is first in the pref name even though most APIs have the part
1748 * first. Confusing; sorry. */
1749 *contextp = xstrndup(name, c - name);
1751 /* There had better NOT be a second _ */
1754 *partp = xstrdup(c);
1758 /** @brief Compute the default value for a track preference
1759 * @param track Track name
1760 * @param name Preference name
1761 * @return Default value or 0 if none/not known
1763 static const char *trackdb__default(const char *track, const char *name) {
1764 char *context, *part;
1766 if(!trackdb__parse_namepref(name, &part, &context)) {
1767 /* We can work out the default for a trackname_ pref */
1768 return trackname_part(track, context, part);
1769 } else if(!strcmp(name, "weight")) {
1770 /* We know the default weight */
1772 } else if(!strcmp(name, "pick_at_random")) {
1773 /* By default everything is eligible for picking at random */
1775 } else if(!strcmp(name, "tags")) {
1776 /* By default everything no track has any tags */
1782 /** @brief Set a preference
1783 * @param track Track to modify
1784 * @param name Preference name
1785 * @param value New value, or NULL to erase any existing value
1786 * @return 0 on success or non-zero if not allowed to set preference
1788 int trackdb_set(const char *track,
1790 const char *value) {
1791 struct kvp *t, *p, *a;
1794 char *oldalias, *newalias, **oldtags = 0, **newtags;
1797 /* If the value matches the default then unset instead, to keep the database
1798 * tidy. Older versions did not have this feature so your database may yet
1799 * have some default values stored in it. */
1801 def = trackdb__default(track, name);
1802 if(def && !strcmp(value, def))
1807 tid = trackdb_begin_transaction();
1808 if((err = gettrackdata(track, &t, &p, 0,
1809 0, tid)) == DB_LOCK_DEADLOCK)
1811 if(err == DB_NOTFOUND) break;
1812 if(name[0] == '_') {
1813 if(kvp_set(&t, name, value))
1814 if(trackdb_putdata(trackdb_tracksdb, track, t, tid, 0))
1817 /* get the old alias name */
1818 if(compute_alias(&oldalias, track, p, tid)) goto fail;
1819 /* get the old tags */
1820 if(!strcmp(name, "tags"))
1821 oldtags = parsetags(kvp_get(p, "tags"));
1823 if(kvp_set(&p, name, value))
1824 if(trackdb_putdata(trackdb_prefsdb, track, p, tid, 0))
1826 /* compute the new alias name */
1827 if(compute_alias(&newalias, track, p, tid)) goto fail;
1828 /* check whether alias has changed */
1829 if(!(oldalias == newalias
1830 || (oldalias && newalias && !strcmp(oldalias, newalias)))) {
1831 /* adjust alias records to fit change */
1833 && trackdb_delkey(trackdb_tracksdb, oldalias, tid) == DB_LOCK_DEADLOCK)
1837 kvp_set(&a, "_alias_for", track);
1838 if(trackdb_putdata(trackdb_tracksdb, newalias, a, tid, 0)) goto fail;
1841 /* check whether tags have changed */
1842 if(!strcmp(name, "tags")) {
1843 newtags = parsetags(value);
1844 while(*oldtags || *newtags) {
1845 if(*oldtags && *newtags) {
1846 cmp = strcmp(*oldtags, *newtags);
1848 /* keeping this tag */
1852 /* old tag fits into a gap in the new list, so delete old */
1855 /* new tag fits into a gap in the old list, so insert new */
1857 } else if(*oldtags) {
1858 /* we've run out of new tags, so remaining old ones are to be
1861 if(trackdb_delkeydata(trackdb_tagsdb,
1862 *oldtags, track, tid) == DB_LOCK_DEADLOCK)
1866 /* we've run out of old tags, so remainig new ones are to be
1869 if(register_tag(track, *newtags, tid)) goto fail;
1878 trackdb_abort_transaction(tid);
1880 trackdb_commit_transaction(tid);
1881 return err == 0 ? 0 : -1;
1884 /** @brief Get the value of a preference
1885 * @param track Track name
1886 * @param name Preference name
1887 * @return Preference value or NULL if it's not set
1889 const char *trackdb_get(const char *track,
1891 return kvp_get(trackdb_get_all(track), name);
1894 /** @brief Get all preferences for a track
1895 * @param track Track name
1896 * @return Linked list of preferences
1898 struct kvp *trackdb_get_all(const char *track) {
1899 struct kvp *t, *p, **pp;
1903 tid = trackdb_begin_transaction();
1904 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1908 trackdb_abort_transaction(tid);
1910 trackdb_commit_transaction(tid);
1911 for(pp = &p; *pp; pp = &(*pp)->next)
1917 /** @brief Resolve an alias
1918 * @param track Track name (might be an alias)
1919 * @return Real track name (definitely not an alias) or NULL if no such track
1921 const char *trackdb_resolve(const char *track) {
1926 tid = trackdb_begin_transaction();
1927 if(gettrackdata(track, 0, 0, &actual, 0, tid) == DB_LOCK_DEADLOCK)
1931 trackdb_abort_transaction(tid);
1933 trackdb_commit_transaction(tid);
1937 /** @brief Detect an alias
1938 * @param track Track name
1939 * @return Nonzero if @p track exists and is an alias
1941 int trackdb_isalias(const char *track) {
1942 const char *actual = trackdb_resolve(track);
1944 return strcmp(actual, track);
1947 /** @brief Detect whether a track exists
1948 * @param track Track name (can be an alias)
1949 * @return Nonzero if @p track exists (whether or not it's an alias)
1951 int trackdb_exists(const char *track) {
1956 tid = trackdb_begin_transaction();
1957 /* unusually, here we want the return value */
1958 if((err = gettrackdata(track, 0, 0, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1962 trackdb_abort_transaction(tid);
1964 trackdb_commit_transaction(tid);
1968 /** @brief Return list of all known tags
1969 * @return NULL-terminated tag list
1971 char **trackdb_alltags(void) {
1976 WITH_TRANSACTION(trackdb_listkeys(trackdb_tagsdb, v, tid));
1980 /** @brief List all the keys in @p db
1981 * @param db Database
1982 * @param v Vector to store keys in
1983 * @param tid Transaction ID
1984 * @return 0 or DB_LOCK_DEADLOCK
1986 int trackdb_listkeys(DB *db, struct vector *v, DB_TXN *tid) {
1989 DBC *const c = trackdb_opencursor(db, tid);
1992 memset(&k, 0, sizeof k);
1993 while(!(e = c->c_get(c, &k, prepare_data(&d), DB_NEXT_NODUP)))
1994 vector_append(v, xstrndup(k.data, k.size));
1998 case DB_LOCK_DEADLOCK:
2001 disorder_fatal(0, "c->c_get: %s", db_strerror(e));
2003 if((e = trackdb_closecursor(c)))
2005 vector_terminate(v);
2009 /* return 1 iff sorted tag lists A and B have at least one member in common */
2010 /** @brief Detect intersecting tag lists
2011 * @param a First list of tags (NULL-terminated)
2012 * @param b Second list of tags (NULL-terminated)
2013 * @return 1 if @p a and @p b have at least one member in common
2015 * @p a and @p must be sorted.
2017 int tag_intersection(char **a, char **b) {
2020 /* Same sort of logic as trackdb_set() above */
2022 if(!(cmp = strcmp(*a, *b))) return 1;
2023 else if(cmp < 0) ++a;
2029 /** @brief Called when disorder-choose might have completed
2030 * @param ev Event loop
2031 * @param which @ref CHOOSE_RUNNING or @ref CHOOSE_READING
2033 * Once called with both @p which values, @ref choose_callback is called
2034 * (usually chosen_random_track()).
2036 static void choose_finished(ev_source *ev, unsigned which) {
2037 choose_complete |= which;
2038 if(choose_complete != (CHOOSE_RUNNING|CHOOSE_READING))
2041 if(choose_status == 0 && choose_output.nvec > 0) {
2042 dynstr_terminate(&choose_output);
2043 choose_callback(ev, xstrdup(choose_output.vec));
2045 choose_callback(ev, 0);
2048 /** @brief Called when @c disorder-choose terminates
2049 * @param ev Event loop
2050 * @param pid Process ID
2051 * @param status Exit status
2052 * @param rusage Resource usage
2053 * @param u User data
2056 static int choose_exited(ev_source *ev,
2057 pid_t attribute((unused)) pid,
2059 const struct rusage attribute((unused)) *rusage,
2060 void attribute((unused)) *u) {
2062 disorder_error(0, "disorder-choose %s", wstat(status));
2063 choose_status = status;
2064 choose_finished(ev, CHOOSE_RUNNING);
2068 /** @brief Called with data from @c disorder-choose pipe
2069 * @param ev Event loop
2070 * @param reader Reader state
2071 * @param ptr Data read
2072 * @param bytes Number of bytes read
2073 * @param eof Set at end of file
2074 * @param u User data
2077 static int choose_readable(ev_source *ev,
2082 void attribute((unused)) *u) {
2083 dynstr_append_bytes(&choose_output, ptr, bytes);
2084 ev_reader_consume(reader, bytes);
2086 choose_finished(ev, CHOOSE_READING);
2090 /** @brief Called when @c disorder-choose pipe errors
2091 * @param ev Event loop
2092 * @param errno_value Error code
2093 * @param u User data
2096 static int choose_read_error(ev_source *ev,
2098 void attribute((unused)) *u) {
2099 disorder_error(errno_value, "error reading disorder-choose pipe");
2100 choose_finished(ev, CHOOSE_READING);
2104 /** @brief Request a random track
2105 * @param ev Event source
2106 * @param callback Called with random track or NULL
2107 * @return 0 if a request was initiated, else -1
2109 * Initiates a random track choice. @p callback will later be called back with
2110 * the choice (or NULL on error). If a choice is already underway then -1 is
2111 * returned and there will be no additional callback.
2113 * The caller shouldn't assume that the track returned actually exists (it
2114 * might be removed between the choice and the callback, or between being added
2115 * to the queue and being played).
2117 int trackdb_request_random(ev_source *ev,
2118 random_callback *callback) {
2121 if(choose_pid != -1)
2122 return -1; /* don't run concurrent chooses */
2125 choose_pid = subprogram(ev, p[1], "disorder-choose", (char *)0);
2128 choose_callback = callback;
2129 choose_output.nvec = 0;
2130 choose_complete = 0;
2131 if(!ev_reader_new(ev, p[0], choose_readable, choose_read_error, 0,
2132 "disorder-choose reader")) /* owns p[0] */
2133 disorder_fatal(0, "ev_reader_new for disorder-choose reader failed");
2134 ev_child(ev, choose_pid, 0, choose_exited, 0); /* owns the subprocess */
2138 /** @brief Get a track name part, using prefs
2139 * @param track Track name
2140 * @param context Context ("display" etc)
2141 * @param part Part ("album" etc)
2142 * @param p Preference
2143 * @param used_db Set if a preference is used
2144 * @return Name part (never NULL)
2146 * Used by compute_alias() and trackdb_getpart().
2148 static const char *getpart(const char *track,
2149 const char *context,
2151 const struct kvp *p,
2156 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2157 if((result = kvp_get(p, pref)))
2160 result = trackname_part(track, context, part);
2161 assert(result != 0);
2165 /** @brief Get a track name part
2166 * @param track Track name
2167 * @param context Context ("display" etc)
2168 * @param part Part ("album" etc)
2169 * @return Name part (never NULL)
2171 * This is interface used by c_part().
2173 const char *trackdb_getpart(const char *track,
2174 const char *context,
2182 /* construct the full pref */
2183 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
2185 tid = trackdb_begin_transaction();
2186 if(gettrackdata(track, 0, &p, &actual, 0, tid) == DB_LOCK_DEADLOCK)
2190 trackdb_abort_transaction(tid);
2192 trackdb_commit_transaction(tid);
2193 return getpart(actual, context, part, p, &used_db);
2196 /** @brief Get the raw (filesystem) path for @p track
2197 * @param track track Track name (can be an alias)
2198 * @return Raw path (never NULL)
2200 * The raw path is the actual bytes that came out of readdir() etc.
2202 const char *trackdb_rawpath(const char *track) {
2208 tid = trackdb_begin_transaction();
2209 if(gettrackdata(track, &t, 0, 0, 0, tid) == DB_LOCK_DEADLOCK)
2213 trackdb_abort_transaction(tid);
2215 trackdb_commit_transaction(tid);
2216 if(!(path = kvp_get(t, "_path"))) path = track;
2220 /* trackdb_list **************************************************************/
2222 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
2223 * readable at some point */
2225 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
2226 * If RE is a null pointer then it matches everything. */
2227 /** @brief Match a track against a rgeexp
2228 * @param dl Length of directory part of track
2229 * @param track Track name
2230 * @param tl Length of track name
2231 * @param re Regular expression or NULL
2232 * @return Nonzero on match
2234 * @p tl is the total length of @p track, @p dl is the length of the directory
2235 * part (the index of the final "/"). The subject of the regexp match is the
2236 * basename, i.e. the part after @p dl.
2238 * If @p re is NULL then always matches.
2240 static int track_matches(size_t dl, const char *track, size_t tl,
2248 switch(rc = pcre_exec(re, 0, track, tl, 0, 0, ovec, 3)) {
2249 case PCRE_ERROR_NOMATCH: return 0;
2252 disorder_error(0, "pcre_exec returned %d, subject '%s'", rc, track);
2259 /** @brief Generate a list of tracks and/or directories in @p dir
2260 * @param v Where to put results
2261 * @param dir Directory to list
2262 * @param what Bitmap of objects to return
2263 * @param re Regexp to filter matches (or NULL to accept all)
2264 * @param tid Owning transaction
2265 * @return 0 or DB_LOCK_DEADLOCK
2267 static int do_list(struct vector *v, const char *dir,
2268 enum trackdb_listable what, const pcre *re, DB_TXN *tid) {
2274 size_t l, last_dir_len = 0;
2275 char *last_dir = 0, *track;
2279 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2282 /* find the first key >= dir */
2283 err = cursor->c_get(cursor, &k, &d, DB_SET_RANGE);
2284 /* keep going while we're dealing with <dir/anything> */
2287 && ((char *)k.data)[dl] == '/'
2288 && !memcmp(k.data, dir, dl)) {
2289 ptr = memchr((char *)k.data + dl + 1, '/', k.size - (dl + 1));
2291 /* we have <dir/component/anything>, so <dir/component> is a directory */
2292 l = ptr - (char *)k.data;
2293 if(what & trackdb_directories)
2295 && l == last_dir_len
2296 && !memcmp(last_dir, k.data, l))) {
2297 last_dir = xstrndup(k.data, last_dir_len = l);
2298 if(track_matches(dl, k.data, l, re))
2299 vector_append(v, last_dir);
2302 /* found a plain file */
2303 if((what & trackdb_files)) {
2304 track = xstrndup(k.data, k.size);
2305 if((err = trackdb_getdata(trackdb_prefsdb,
2306 track, &p, tid)) == DB_LOCK_DEADLOCK)
2308 /* There's an awkward question here...
2310 * If a track shares a directory with its alias then we could
2311 * do one of three things:
2312 * - report both. Looks ridiculuous in most UIs.
2313 * - report just the alias. Remarkably inconvenient to write
2315 * - report just the real name. Ugly if the UI doesn't prettify
2316 * names via the name parts.
2319 /* If this file is an alias for a track in the same directory then we
2321 struct kvp *t = kvp_urldecode(d.data, d.size);
2322 const char *alias_target = kvp_get(t, "_alias_for");
2324 && !strcmp(d_dirname(alias_target),
2326 if(track_matches(dl, k.data, k.size, re))
2327 vector_append(v, track);
2329 /* if this file has an alias in the same directory then we skip it */
2331 if((err = compute_alias(&alias, track, p, tid)))
2333 if(!(alias && !strcmp(d_dirname(alias), d_dirname(track))))
2334 if(track_matches(dl, k.data, k.size, re))
2335 vector_append(v, track);
2339 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2347 case DB_LOCK_DEADLOCK:
2348 disorder_error(0, "error querying database: %s", db_strerror(err));
2351 disorder_fatal(0, "error querying database: %s", db_strerror(err));
2354 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2358 /** @brief Get the directories or files below @p dir
2359 * @param dir Directory to list
2360 * @param np Where to put number of results (or NULL)
2361 * @param what Bitmap of objects to return
2362 * @param re Regexp to filter matches (or NULL to accept all)
2363 * @return List of tracks
2365 char **trackdb_list(const char *dir, int *np, enum trackdb_listable what,
2373 tid = trackdb_begin_transaction();
2376 if(do_list(&v, dir, what, re, tid))
2379 for(n = 0; n < config->collection.n; ++n)
2380 if(do_list(&v, config->collection.s[n].root, what, re, tid))
2385 trackdb_abort_transaction(tid);
2387 trackdb_commit_transaction(tid);
2388 vector_terminate(&v);
2394 /** @brief Detect a tag element in a search string
2395 * @param s Element of search string
2396 * @return Pointer to tag name (in @p s) if this is a tag: search, else NULL
2398 * Tag searches take the form "tag:TAG".
2400 static const char *checktag(const char *s) {
2401 if(!strncmp(s, "tag:", 4))
2407 /* return a list of tracks containing all of the words given. If you
2408 * ask for only stopwords you get no tracks. */
2409 char **trackdb_search(char **wordlist, int nwordlist, int *ntracks) {
2410 const char **w, *best = 0, *tag;
2411 char **twords, **tags;
2413 int i, j, n, err, what;
2423 *ntracks = 0; /* for early returns */
2424 /* normalize all the words */
2425 w = xmalloc(nwordlist * sizeof (char *));
2426 istag = xmalloc_noptr(nwordlist);
2427 for(n = 0; n < nwordlist; ++n) {
2431 w[n] = utf8_casefold_compat(wordlist[n], strlen(wordlist[n]), 0);
2432 if(checktag(w[n])) {
2433 ++ntags; /* count up tags */
2434 /* Normalize the tag */
2435 w[n] = normalize_tag(w[n] + 4, strlen(w[n] + 4));
2438 /* Normalize the search term by removing combining characters */
2439 if(!(w32 = utf8_to_utf32(w[n], strlen(w[n]), &nw32)))
2441 nw32 = remove_combining_chars(w32, nw32);
2442 if(!(w[n] = utf32_to_utf8(w32, nw32, 0)))
2447 /* find the longest non-stopword */
2448 for(n = 0; n < nwordlist; ++n)
2449 if(!istag[n] && !stopword(w[n]))
2450 if(!best || strlen(w[n]) > strlen(best))
2452 /* TODO: we should at least in principal be able to identify the word or tag
2453 * with the least matches in log time, and choose that as our primary search
2455 if(ntags && !best) {
2456 /* Only tags are listed. We limit to the first and narrow down with the
2458 best = istag[0] ? w[0] : 0;
2459 db = trackdb_tagsdb;
2462 /* We can limit to some word. */
2463 db = trackdb_searchdb;
2466 /* Only stopwords */
2472 tid = trackdb_begin_transaction();
2473 /* find all the tracks that have that word */
2478 cursor = trackdb_opencursor(db, tid);
2479 while(!(err = cursor->c_get(cursor, &k, &d, what))) {
2480 vector_append(&v, xstrndup(d.data, d.size));
2487 case DB_LOCK_DEADLOCK:
2488 disorder_error(0, "error querying %s database: %s",
2489 dbname, db_strerror(err));
2492 disorder_fatal(0, "error querying %s database: %s",
2493 dbname, db_strerror(err));
2495 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
2500 /* do a naive search over that (hopefuly fairly small) list of tracks */
2502 for(n = 0; n < v.nvec; ++n) {
2503 if((err = gettrackdata(v.vec[n], 0, &p, 0, 0, tid) == DB_LOCK_DEADLOCK))
2506 disorder_error(0, "track %s unexpected error: %s",
2507 v.vec[n], db_strerror(err));
2510 twords = track_to_words(v.vec[n], p);
2511 tags = parsetags(kvp_get(p, "tags"));
2512 for(i = 0; i < nwordlist; ++i) {
2515 /* Track must have this tag */
2516 for(j = 0; tags[j]; ++j)
2517 if(!strcmp(tag, tags[j])) break; /* tag found */
2518 if(!tags[j]) break; /* tag not found */
2520 /* Track must contain this word */
2521 for(j = 0; twords[j]; ++j)
2522 if(!strcmp(w[i], twords[j])) break; /* word found */
2523 if(!twords[j]) break; /* word not found */
2526 if(i >= nwordlist) /* all words found */
2527 vector_append(&u, v.vec[n]);
2531 trackdb_closecursor(cursor);
2533 trackdb_abort_transaction(tid);
2534 disorder_info("retrying search");
2536 trackdb_commit_transaction(tid);
2537 vector_terminate(&u);
2543 /* trackdb_scan **************************************************************/
2545 /** @brief Visit every track
2546 * @param root Root to scan or NULL for all
2547 * @param callback Callback for each track
2548 * @param u Passed to @p callback
2549 * @param tid Owning transaction
2550 * @return 0, DB_LOCK_DEADLOCK or EINTR
2552 * Visits every track and calls @p callback. @p callback will get the track
2553 * data and preferences and should return 0 to continue scanning or EINTR to
2556 int trackdb_scan(const char *root,
2557 int (*callback)(const char *track,
2566 const size_t root_len = root ? strlen(root) : 0;
2568 struct kvp *data, *prefs;
2571 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
2573 err = cursor->c_get(cursor, make_key(&k, root), prepare_data(&d),
2576 memset(&k, 0, sizeof k);
2577 err = cursor->c_get(cursor, &k, prepare_data(&d),
2582 || (k.size > root_len
2583 && !strncmp(k.data, root, root_len)
2584 && ((char *)k.data)[root_len] == '/')) {
2585 data = kvp_urldecode(d.data, d.size);
2586 if(kvp_get(data, "_path")) {
2587 track = xstrndup(k.data, k.size);
2588 /* TODO: trackdb_prefsdb is currently a DB_HASH. This means we have to
2589 * do a lookup for every single track. In fact this is quite quick:
2590 * with around 10,000 tracks a complete scan is around 0.3s on my
2591 * 2.2GHz Athlon. However, if it were a DB_BTREE, we could do the same
2592 * linear walk as we already do over trackdb_tracksdb, and probably get
2593 * even higher performance. That would require upgrade logic to
2594 * translate old databases though.
2596 switch(err = trackdb_prefsdb->get(trackdb_prefsdb, tid, &k,
2597 prepare_data(&pd), 0)) {
2599 prefs = kvp_urldecode(pd.data, pd.size);
2604 case DB_LOCK_DEADLOCK:
2605 disorder_error(0, "getting prefs: %s", db_strerror(err));
2606 trackdb_closecursor(cursor);
2609 disorder_fatal(0, "getting prefs: %s", db_strerror(err));
2611 /* Advance to the next track before the callback so that the callback
2612 * may safely delete the track */
2613 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2614 if((cberr = callback(track, data, prefs, u, tid))) {
2619 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
2623 trackdb_closecursor(cursor);
2630 case DB_LOCK_DEADLOCK:
2631 disorder_error(0, "c->c_get: %s", db_strerror(err));
2634 disorder_fatal(0, "c->c_get: %s", db_strerror(err));
2638 /* trackdb_rescan ************************************************************/
2640 /** @brief Node in the list of rescan-complete callbacks */
2641 struct rescanned_node {
2642 struct rescanned_node *next;
2643 void (*rescanned)(void *ru);
2647 /** @brief List of rescan-complete callbacks */
2648 static struct rescanned_node *rescanned_list;
2650 /** @brief Add a rescan completion callback */
2651 void trackdb_add_rescanned(void (*rescanned)(void *ru),
2654 struct rescanned_node *n = xmalloc(sizeof *n);
2655 n->next = rescanned_list;
2656 n->rescanned = rescanned;
2662 /* called when the rescanner terminates */
2663 static int reap_rescan(ev_source attribute((unused)) *ev,
2666 const struct rusage attribute((unused)) *rusage,
2667 void attribute((unused)) *u) {
2668 if(pid == rescan_pid) rescan_pid = -1;
2670 disorder_error(0, RESCAN": %s", wstat(status));
2672 D((RESCAN" terminated: %s", wstat(status)));
2673 /* Our cache of file lookups is out of date now */
2674 cache_clean(&cache_files_type);
2675 eventlog("rescanned", (char *)0);
2676 /* Call rescanned callbacks */
2677 while(rescanned_list) {
2678 void (*rescanned)(void *u_) = rescanned_list->rescanned;
2679 void *ru = rescanned_list->ru;
2681 rescanned_list = rescanned_list->next;
2687 /** @brief Initiate a rescan
2688 * @param ev Event loop or 0 to block
2689 * @param recheck 1 to recheck lengths, 0 to suppress check
2690 * @param rescanned Called on completion (if not NULL)
2691 * @param ru Passed to @p rescanned
2693 void trackdb_rescan(ev_source *ev, int recheck,
2694 void (*rescanned)(void *ru),
2698 if(rescan_pid != -1) {
2699 trackdb_add_rescanned(rescanned, ru);
2700 disorder_error(0, "rescan already underway");
2703 rescan_pid = subprogram(ev, -1, RESCAN,
2704 recheck ? "--check" : "--no-check",
2706 trackdb_add_rescanned(rescanned, ru);
2708 ev_child(ev, rescan_pid, 0, reap_rescan, 0);
2709 D(("started rescanner"));
2711 /* This is the first rescan, we block until it is complete */
2712 while(waitpid(rescan_pid, &w, 0) < 0 && errno == EINTR)
2714 reap_rescan(0, rescan_pid, w, 0, 0);
2718 /** @brief Cancel a rescan
2719 * @return Nonzero if a rescan was cancelled
2721 int trackdb_rescan_cancel(void) {
2722 if(rescan_pid == -1) return 0;
2723 if(kill(rescan_pid, SIGTERM) < 0)
2724 disorder_fatal(errno, "error killing rescanner");
2729 /** @brief Return true if a rescan is underway */
2730 int trackdb_rescan_underway(void) {
2731 return rescan_pid != -1;
2734 /* global prefs **************************************************************/
2736 /** @brief Set a global preference
2737 * @param name Global preference name
2738 * @param value New value
2739 * @param who Who is setting it
2740 * @return 0 on success, -1 on error
2742 int trackdb_set_global(const char *name,
2749 tid = trackdb_begin_transaction();
2750 err = trackdb_set_global_tid(name, value, tid);
2751 if(err != DB_LOCK_DEADLOCK)
2753 trackdb_abort_transaction(tid);
2755 trackdb_commit_transaction(tid);
2756 /* log important state changes */
2757 if(!strcmp(name, "playing")) {
2758 state = !value || !strcmp(value, "yes");
2759 disorder_info("playing %s by %s",
2760 state ? "enabled" : "disabled",
2762 eventlog("state", state ? "enable_play" : "disable_play", (char *)0);
2764 if(!strcmp(name, "random-play")) {
2765 state = !value || !strcmp(value, "yes");
2766 disorder_info("random play %s by %s",
2767 state ? "enabled" : "disabled",
2769 eventlog("state", state ? "enable_random" : "disable_random", (char *)0);
2771 eventlog("global_pref", name, value, (char *)0);
2772 return err == 0 ? 0 : -1;
2775 /** @brief Set a global preference
2776 * @param name Global preference name
2777 * @param value New value
2778 * @param tid Owning transaction
2780 int trackdb_set_global_tid(const char *name,
2786 memset(&k, 0, sizeof k);
2787 memset(&d, 0, sizeof d);
2788 k.data = (void *)name;
2789 k.size = strlen(name);
2791 d.data = (void *)value;
2792 d.size = strlen(value);
2795 err = trackdb_globaldb->put(trackdb_globaldb, tid, &k, &d, 0);
2797 err = trackdb_globaldb->del(trackdb_globaldb, tid, &k, 0);
2798 if(err == DB_LOCK_DEADLOCK || err == DB_NOTFOUND) return err;
2800 disorder_fatal(0, "error updating database: %s", db_strerror(err));
2804 /** @brief Get a global preference
2805 * @param name Global preference name
2806 * @return Value of global preference, or NULL if it's not set
2808 const char *trackdb_get_global(const char *name) {
2813 tid = trackdb_begin_transaction();
2814 if(!trackdb_get_global_tid(name, tid, &r))
2816 trackdb_abort_transaction(tid);
2818 trackdb_commit_transaction(tid);
2822 /** @brief Get a global preference
2823 * @param name Global preference name
2824 * @param tid Owning transaction
2825 * @param rp Where to store value (will get NULL if preference not set)
2826 * @return 0 or DB_LOCK_DEADLOCK
2828 int trackdb_get_global_tid(const char *name,
2834 memset(&k, 0, sizeof k);
2835 k.data = (void *)name;
2836 k.size = strlen(name);
2837 switch(err = trackdb_globaldb->get(trackdb_globaldb, tid, &k,
2838 prepare_data(&d), 0)) {
2840 *rp = xstrndup(d.data, d.size);
2845 case DB_LOCK_DEADLOCK:
2848 disorder_fatal(0, "error reading database: %s", db_strerror(err));
2852 /** @brief Retrieve the most recently added tracks
2853 * @param ntracksp Where to put count, or 0
2854 * @param maxtracks Maximum number of tracks to retrieve
2855 * @return null-terminated array of track names
2857 * The most recently added track is first in the array.
2859 char **trackdb_new(int *ntracksp,
2865 tid = trackdb_begin_transaction();
2866 tracks = trackdb_new_tid(ntracksp, maxtracks, tid);
2869 trackdb_abort_transaction(tid);
2871 trackdb_commit_transaction(tid);
2875 /** @brief Retrieve the most recently added tracks
2876 * @param ntracksp Where to put count, or 0
2877 * @param maxtracks Maximum number of tracks to retrieve, or 0 for all
2878 * @param tid Transaction ID
2879 * @return null-terminated array of track names, or NULL on deadlock
2881 * The most recently added track is first in the array.
2883 static char **trackdb_new_tid(int *ntracksp,
2889 struct vector tracks[1];
2890 hash *h = hash_new(1);
2892 vector_init(tracks);
2893 c = trackdb_opencursor(trackdb_noticeddb, tid);
2894 while((maxtracks <= 0 || tracks->nvec < maxtracks)
2895 && !(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_PREV))) {
2896 char *const track = xstrndup(d.data, d.size);
2897 /* Don't add any track more than once */
2898 if(hash_add(h, track, "", HASH_INSERT))
2900 /* See if the track still exists */
2901 err = trackdb_getdata(trackdb_tracksdb, track, NULL/*kp*/, tid);
2902 if(err == DB_NOTFOUND)
2903 continue; /* It doesn't, skip it */
2904 if(err == DB_LOCK_DEADLOCK)
2906 vector_append(tracks, track);
2909 case 0: /* hit maxtracks */
2910 case DB_NOTFOUND: /* ran out of tracks */
2912 case DB_LOCK_DEADLOCK:
2913 trackdb_closecursor(c);
2916 disorder_fatal(0, "error reading noticed.db: %s", db_strerror(err));
2918 if(trackdb_closecursor(c))
2919 return 0; /* deadlock */
2920 vector_terminate(tracks);
2922 *ntracksp = tracks->nvec;
2926 /** @brief Expire noticed.db
2927 * @param earliest Earliest timestamp to keep
2929 void trackdb_expire_noticed(time_t earliest) {
2933 tid = trackdb_begin_transaction();
2934 if(!trackdb_expire_noticed_tid(earliest, tid))
2936 trackdb_abort_transaction(tid);
2938 trackdb_commit_transaction(tid);
2941 /** @brief Expire noticed.db
2942 * @param earliest Earliest timestamp to keep
2943 * @param tid Transaction ID
2944 * @return 0 or DB_LOCK_DEADLOCK
2946 static int trackdb_expire_noticed_tid(time_t earliest, DB_TXN *tid) {
2954 c = trackdb_opencursor(trackdb_noticeddb, tid);
2955 while(!(err = c->c_get(c, prepare_data(&k), prepare_data(&d), DB_NEXT))) {
2957 when = (time_t)(((uint64_t)ntohl(kk[0]) << 32) + ntohl(kk[1]));
2958 if(when >= earliest)
2960 if((err = c->c_del(c, 0))) {
2961 if(err != DB_LOCK_DEADLOCK)
2962 disorder_fatal(0, "error deleting expired noticed.db entry: %s",
2968 if(err == DB_NOTFOUND)
2970 if(err && err != DB_LOCK_DEADLOCK)
2971 disorder_fatal(0, "error expiring noticed.db: %s", db_strerror(err));
2973 if((err = trackdb_closecursor(c))) {
2974 if(err != DB_LOCK_DEADLOCK)
2975 disorder_fatal(0, "error closing cursor: %s", db_strerror(err));
2979 disorder_info("expired %d tracks from noticed.db", count);
2983 /* tidying up ****************************************************************/
2985 /** @brief Do database garbage collection
2987 * Called form periodic_database_gc().
2989 void trackdb_gc(void) {
2993 if((err = trackdb_env->txn_checkpoint(trackdb_env,
2994 config->checkpoint_kbyte,
2995 config->checkpoint_min,
2997 disorder_fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err));
2998 if((err = trackdb_env->log_archive(trackdb_env, &logfiles, DB_ARCH_REMOVE)))
2999 disorder_fatal(0, "trackdb_env->log_archive: %s", db_strerror(err));
3000 /* This makes catastrophic recovery impossible. However, the user can still
3001 * preserve the important data by using disorder-dump to snapshot their
3002 * prefs, and later to restore it. This is likely to have much small
3003 * long-term storage requirements than record the db logfiles. */
3006 /* user database *************************************************************/
3008 /** @brief Add a user
3009 * @param user Username
3010 * @param password Initial password or NULL
3011 * @param rights Initial rights
3012 * @param email Email address or NULL
3013 * @param confirmation Confirmation string to require
3014 * @param tid Owning transaction
3015 * @param flags DB flags e.g. DB_NOOVERWRITE
3016 * @return 0, DB_KEYEXIST or DB_LOCK_DEADLOCK
3018 static int create_user(const char *user,
3019 const char *password,
3022 const char *confirmation,
3028 /* sanity check user */
3029 if(!valid_username(user)) {
3030 disorder_error(0, "invalid username '%s'", user);
3033 if(parse_rights(rights, 0, 1)) {
3034 disorder_error(0, "invalid rights string");
3037 /* data for this user */
3039 kvp_set(&k, "password", password);
3040 kvp_set(&k, "rights", rights);
3042 kvp_set(&k, "email", email);
3044 kvp_set(&k, "confirmation", confirmation);
3045 snprintf(s, sizeof s, "%jd", (intmax_t)xtime(0));
3046 kvp_set(&k, "created", s);
3047 return trackdb_putdata(trackdb_usersdb, user, k, tid, flags);
3050 /** @brief Create a root user in the user database if there is none */
3051 void trackdb_create_root(void) {
3056 /* Choose a new root password */
3057 gcry_randomize(pwbin, sizeof pwbin, GCRY_STRONG_RANDOM);
3058 pw = mime_to_base64(pwbin, sizeof pwbin);
3059 /* Create the root user if it does not exist */
3060 WITH_TRANSACTION(create_user("root", pw, "all",
3061 0/*email*/, 0/*confirmation*/,
3062 tid, DB_NOOVERWRITE));
3064 disorder_info("created root user");
3067 /** @brief Find a user's password from the database
3068 * @param user Username
3069 * @return Password or NULL
3071 * Only works if running as a user that can read the database!
3073 * If the user exists but has no password, "" is returned.
3075 const char *trackdb_get_password(const char *user) {
3078 const char *password;
3080 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3083 password = kvp_get(k, "password");
3084 return password ? password : "";
3087 /** @brief Add a new user
3088 * @param user Username
3089 * @param password Password or NULL
3090 * @param rights Initial rights
3091 * @param email Email address or NULL
3092 * @param confirmation Confirmation string or NULL
3093 * @return 0 on success, non-0 on error
3095 int trackdb_adduser(const char *user,
3096 const char *password,
3099 const char *confirmation) {
3102 WITH_TRANSACTION(create_user(user, password, rights, email, confirmation,
3103 tid, DB_NOOVERWRITE));
3105 disorder_error(0, "cannot create user '%s' because they already exist",
3110 disorder_info("created user '%s' with rights '%s' and email address '%s'",
3111 user, rights, email);
3113 disorder_info("created user '%s' with rights '%s'", user, rights);
3114 eventlog("user_add", user, (char *)0);
3119 /** @brief Delete a user
3120 * @param user User to delete
3121 * @return 0 on success, non-0 if the user didn't exist anyway
3123 int trackdb_deluser(const char *user) {
3126 WITH_TRANSACTION(trackdb_delkey(trackdb_usersdb, user, tid));
3128 disorder_error(0, "cannot delete user '%s' because they do not exist",
3132 disorder_info("deleted user '%s'", user);
3133 eventlog("user_delete", user, (char *)0);
3137 /** @brief Get user information
3138 * @param user User to query
3139 * @return Linked list of user information or NULL if user does not exist
3141 * Every user has at least a @c rights entry so NULL can be used to mean no
3144 struct kvp *trackdb_getuserinfo(const char *user) {
3148 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb, user, &k, tid));
3155 /** @brief Edit user information
3156 * @param user User to edit
3157 * @param key Key to change
3158 * @param value Value to set, or NULL to remove
3159 * @param tid Transaction ID
3160 * @return 0, DB_LOCK_DEADLOCK or DB_NOTFOUND
3162 static int trackdb_edituserinfo_tid(const char *user, const char *key,
3163 const char *value, DB_TXN *tid) {
3167 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3169 if(!kvp_set(&k, key, value))
3170 return 0; /* no change */
3171 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3174 /** @brief Edit user information
3175 * @param user User to edit
3176 * @param key Key to change
3177 * @param value Value to set, or NULL to remove
3178 * @return 0 on success, non-0 on error
3180 int trackdb_edituserinfo(const char *user,
3181 const char *key, const char *value) {
3184 if(!strcmp(key, "rights")) {
3186 disorder_error(0, "cannot remove 'rights' key from user '%s'", user);
3189 if(parse_rights(value, 0, 1)) {
3190 disorder_error(0, "invalid rights string");
3193 } else if(!strcmp(key, "email")) {
3195 if(!email_valid(value)) {
3196 disorder_error(0, "invalid email address '%s' for user '%s'",
3201 value = 0; /* no email -> remove key */
3202 } else if(!strcmp(key, "created")) {
3203 disorder_error(0, "cannot change creation date for user '%s'", user);
3205 } else if(strcmp(key, "password")
3206 && !strcmp(key, "confirmation")) {
3207 disorder_error(0, "unknown user info key '%s' for user '%s'", key, user);
3210 WITH_TRANSACTION(trackdb_edituserinfo_tid(user, key, value, tid));
3212 disorder_error(0, "unknown user '%s'", user);
3215 eventlog("user_edit", user, key, (char *)0);
3220 /** @brief List all users
3221 * @return NULL-terminated list of users
3223 char **trackdb_listusers(void) {
3228 WITH_TRANSACTION(trackdb_listkeys(trackdb_usersdb, v, tid));
3232 /** @brief Confirm a user registration
3233 * @param user Username
3234 * @param confirmation Confirmation string
3235 * @param rightsp Where to put user rights
3236 * @param tid Transaction ID
3237 * @return 0 on success, non-0 on error
3239 static int trackdb_confirm_tid(const char *user, const char *confirmation,
3240 rights_type *rightsp,
3242 const char *stored_confirmation;
3247 if((e = trackdb_getdata(trackdb_usersdb, user, &k, tid)))
3249 if(!(stored_confirmation = kvp_get(k, "confirmation"))) {
3250 disorder_error(0, "already confirmed user '%s'", user);
3251 /* DB claims -30,800 to -30,999 so -1 should be a safe bet */
3254 if(!(rights = kvp_get(k, "rights"))) {
3255 disorder_error(0, "no rights for unconfirmed user '%s'", user);
3258 if(parse_rights(rights, rightsp, 1))
3260 if(strcmp(confirmation, stored_confirmation)) {
3261 disorder_error(0, "wrong confirmation string for user '%s'", user);
3265 kvp_set(&k, "confirmation", 0);
3266 return trackdb_putdata(trackdb_usersdb, user, k, tid, 0);
3269 /** @brief Confirm a user registration
3270 * @param user Username
3271 * @param confirmation Confirmation string
3272 * @param rightsp Where to put user rights
3273 * @return 0 on success, non-0 on error
3275 int trackdb_confirm(const char *user, const char *confirmation,
3276 rights_type *rightsp) {
3279 WITH_TRANSACTION(trackdb_confirm_tid(user, confirmation, rightsp, tid));
3282 disorder_info("registration confirmed for user '%s'", user);
3283 eventlog("user_confirm", user, (char *)0);
3286 disorder_error(0, "confirmation for nonexistent user '%s'", user);
3288 default: /* already reported */
3298 indent-tabs-mode:nil