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 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 /** @brief Detect intersecting tag lists
2006 * @param a First list of tags (NULL-terminated)
2007 * @param b Second list of tags (NULL-terminated)
2008 * @return 1 if @p a and @p b have at least one member in common
2010 * @p a and @p must be sorted.
2012 int tag_intersection(char **a
, char **b
) {
2015 /* Same sort of logic as trackdb_set() above */
2017 if(!(cmp
= strcmp(*a
, *b
))) return 1;
2018 else if(cmp
< 0) ++a
;
2024 /** @brief Called when disorder-choose might have completed
2025 * @param ev Event loop
2026 * @param which @ref CHOOSE_RUNNING or @ref CHOOSE_READING
2028 * Once called with both @p which values, @ref choose_callback is called
2029 * (usually chosen_random_track()).
2031 static void choose_finished(ev_source
*ev
, unsigned which
) {
2032 choose_complete
|= which
;
2033 if(choose_complete
!= (CHOOSE_RUNNING
|CHOOSE_READING
))
2036 if(choose_status
== 0 && choose_output
.nvec
> 0) {
2037 dynstr_terminate(&choose_output
);
2038 choose_callback(ev
, xstrdup(choose_output
.vec
));
2040 choose_callback(ev
, 0);
2043 /** @brief Called when @c disorder-choose terminates
2044 * @param ev Event loop
2045 * @param pid Process ID
2046 * @param status Exit status
2047 * @param rusage Resource usage
2048 * @param u User data
2051 static int choose_exited(ev_source
*ev
,
2052 pid_t
attribute((unused
)) pid
,
2054 const struct rusage
attribute((unused
)) *rusage
,
2055 void attribute((unused
)) *u
) {
2057 error(0, "disorder-choose %s", wstat(status
));
2058 choose_status
= status
;
2059 choose_finished(ev
, CHOOSE_RUNNING
);
2063 /** @brief Called with data from @c disorder-choose pipe
2064 * @param ev Event loop
2065 * @param reader Reader state
2066 * @param ptr Data read
2067 * @param bytes Number of bytes read
2068 * @param eof Set at end of file
2069 * @param u User data
2072 static int choose_readable(ev_source
*ev
,
2077 void attribute((unused
)) *u
) {
2078 dynstr_append_bytes(&choose_output
, ptr
, bytes
);
2079 ev_reader_consume(reader
, bytes
);
2081 choose_finished(ev
, CHOOSE_READING
);
2085 /** @brief Called when @c disorder-choose pipe errors
2086 * @param ev Event loop
2087 * @param errno_value Error code
2088 * @param u User data
2091 static int choose_read_error(ev_source
*ev
,
2093 void attribute((unused
)) *u
) {
2094 error(errno_value
, "error reading disorder-choose pipe");
2095 choose_finished(ev
, CHOOSE_READING
);
2099 /** @brief Request a random track
2100 * @param ev Event source
2101 * @param callback Called with random track or NULL
2102 * @return 0 if a request was initiated, else -1
2104 * Initiates a random track choice. @p callback will later be called back with
2105 * the choice (or NULL on error). If a choice is already underway then -1 is
2106 * returned and there will be no additional callback.
2108 * The caller shouldn't assume that the track returned actually exists (it
2109 * might be removed between the choice and the callback, or between being added
2110 * to the queue and being played).
2112 int trackdb_request_random(ev_source
*ev
,
2113 random_callback
*callback
) {
2116 if(choose_pid
!= -1)
2117 return -1; /* don't run concurrent chooses */
2120 choose_pid
= subprogram(ev
, p
[1], "disorder-choose", (char *)0);
2123 choose_callback
= callback
;
2124 choose_output
.nvec
= 0;
2125 choose_complete
= 0;
2126 if(!ev_reader_new(ev
, p
[0], choose_readable
, choose_read_error
, 0,
2127 "disorder-choose reader")) /* owns p[0] */
2128 fatal(0, "ev_reader_new for disorder-choose reader failed");
2129 ev_child(ev
, choose_pid
, 0, choose_exited
, 0); /* owns the subprocess */
2133 /** @brief Get a track name part, using prefs
2134 * @param track Track name
2135 * @param context Context ("display" etc)
2136 * @param part Part ("album" etc)
2137 * @param p Preference
2138 * @param used_db Set if a preference is used
2139 * @return Name part (never NULL)
2141 * Used by compute_alias() and trackdb_getpart().
2143 static const char *getpart(const char *track
,
2144 const char *context
,
2146 const struct kvp
*p
,
2151 byte_xasprintf(&pref
, "trackname_%s_%s", context
, part
);
2152 if((result
= kvp_get(p
, pref
)))
2155 result
= trackname_part(track
, context
, part
);
2156 assert(result
!= 0);
2160 /** @brief Get a track name part
2161 * @param track Track name
2162 * @param context Context ("display" etc)
2163 * @param part Part ("album" etc)
2164 * @return Name part (never NULL)
2166 * This is interface used by c_part().
2168 const char *trackdb_getpart(const char *track
,
2169 const char *context
,
2177 /* construct the full pref */
2178 byte_xasprintf(&pref
, "trackname_%s_%s", context
, part
);
2180 tid
= trackdb_begin_transaction();
2181 if((err
= gettrackdata(track
, 0, &p
, &actual
, 0, tid
)) == DB_LOCK_DEADLOCK
)
2185 trackdb_abort_transaction(tid
);
2187 trackdb_commit_transaction(tid
);
2188 return getpart(actual
, context
, part
, p
, &used_db
);
2191 /** @brief Get the raw (filesystem) path for @p track
2192 * @param track track Track name (can be an alias)
2193 * @return Raw path (never NULL)
2195 * The raw path is the actual bytes that came out of readdir() etc.
2197 const char *trackdb_rawpath(const char *track
) {
2203 tid
= trackdb_begin_transaction();
2204 if(gettrackdata(track
, &t
, 0, 0, 0, tid
) == DB_LOCK_DEADLOCK
)
2208 trackdb_abort_transaction(tid
);
2210 trackdb_commit_transaction(tid
);
2211 if(!(path
= kvp_get(t
, "_path"))) path
= track
;
2215 /* trackdb_list **************************************************************/
2217 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
2218 * readable at some point */
2220 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
2221 * If RE is a null pointer then it matches everything. */
2222 /** @brief Match a track against a rgeexp
2223 * @param dl Length of directory part of track
2224 * @param track Track name
2225 * @param tl Length of track name
2226 * @param re Regular expression or NULL
2227 * @return Nonzero on match
2229 * @p tl is the total length of @p track, @p dl is the length of the directory
2230 * part (the index of the final "/"). The subject of the regexp match is the
2231 * basename, i.e. the part after @p dl.
2233 * If @p re is NULL then always matches.
2235 static int track_matches(size_t dl
, const char *track
, size_t tl
,
2243 switch(rc
= pcre_exec(re
, 0, track
, tl
, 0, 0, ovec
, 3)) {
2244 case PCRE_ERROR_NOMATCH
: return 0;
2247 error(0, "pcre_exec returned %d, subject '%s'", rc
, track
);
2254 /** @brief Generate a list of tracks and/or directories in @p dir
2255 * @param v Where to put results
2256 * @param dir Directory to list
2257 * @param what Bitmap of objects to return
2258 * @param re Regexp to filter matches (or NULL to accept all)
2259 * @param tid Owning transaction
2260 * @return 0 or DB_LOCK_DEADLOCK
2262 static int do_list(struct vector
*v
, const char *dir
,
2263 enum trackdb_listable what
, const pcre
*re
, DB_TXN
*tid
) {
2269 size_t l
, last_dir_len
= 0;
2270 char *last_dir
= 0, *track
;
2274 cursor
= trackdb_opencursor(trackdb_tracksdb
, tid
);
2277 /* find the first key >= dir */
2278 err
= cursor
->c_get(cursor
, &k
, &d
, DB_SET_RANGE
);
2279 /* keep going while we're dealing with <dir/anything> */
2282 && ((char *)k
.data
)[dl
] == '/'
2283 && !memcmp(k
.data
, dir
, dl
)) {
2284 ptr
= memchr((char *)k
.data
+ dl
+ 1, '/', k
.size
- (dl
+ 1));
2286 /* we have <dir/component/anything>, so <dir/component> is a directory */
2287 l
= ptr
- (char *)k
.data
;
2288 if(what
& trackdb_directories
)
2290 && l
== last_dir_len
2291 && !memcmp(last_dir
, k
.data
, l
))) {
2292 last_dir
= xstrndup(k
.data
, last_dir_len
= l
);
2293 if(track_matches(dl
, k
.data
, l
, re
))
2294 vector_append(v
, last_dir
);
2297 /* found a plain file */
2298 if((what
& trackdb_files
)) {
2299 track
= xstrndup(k
.data
, k
.size
);
2300 if((err
= trackdb_getdata(trackdb_prefsdb
,
2301 track
, &p
, tid
)) == DB_LOCK_DEADLOCK
)
2303 /* There's an awkward question here...
2305 * If a track shares a directory with its alias then we could
2306 * do one of three things:
2307 * - report both. Looks ridiculuous in most UIs.
2308 * - report just the alias. Remarkably inconvenient to write
2310 * - report just the real name. Ugly if the UI doesn't prettify
2311 * names via the name parts.
2314 /* If this file is an alias for a track in the same directory then we
2316 struct kvp
*t
= kvp_urldecode(d
.data
, d
.size
);
2317 const char *alias_target
= kvp_get(t
, "_alias_for");
2319 && !strcmp(d_dirname(alias_target
),
2321 if(track_matches(dl
, k
.data
, k
.size
, re
))
2322 vector_append(v
, track
);
2324 /* if this file has an alias in the same directory then we skip it */
2326 if((err
= compute_alias(&alias
, track
, p
, tid
)))
2328 if(!(alias
&& !strcmp(d_dirname(alias
), d_dirname(track
))))
2329 if(track_matches(dl
, k
.data
, k
.size
, re
))
2330 vector_append(v
, track
);
2334 err
= cursor
->c_get(cursor
, &k
, &d
, DB_NEXT
);
2342 case DB_LOCK_DEADLOCK
:
2343 error(0, "error querying database: %s", db_strerror(err
));
2346 fatal(0, "error querying database: %s", db_strerror(err
));
2349 if(trackdb_closecursor(cursor
)) err
= DB_LOCK_DEADLOCK
;
2353 /** @brief Get the directories or files below @p dir
2354 * @param dir Directory to list
2355 * @param np Where to put number of results (or NULL)
2356 * @param what Bitmap of objects to return
2357 * @param re Regexp to filter matches (or NULL to accept all)
2358 * @return List of tracks
2360 char **trackdb_list(const char *dir
, int *np
, enum trackdb_listable what
,
2368 tid
= trackdb_begin_transaction();
2371 if(do_list(&v
, dir
, what
, re
, tid
))
2374 for(n
= 0; n
< config
->collection
.n
; ++n
)
2375 if(do_list(&v
, config
->collection
.s
[n
].root
, what
, re
, tid
))
2380 trackdb_abort_transaction(tid
);
2382 trackdb_commit_transaction(tid
);
2383 vector_terminate(&v
);
2389 /** @brief Detect a tag element in a search string
2390 * @param s Element of search string
2391 * @return Pointer to tag name (in @p s) if this is a tag: search, else NULL
2393 * Tag searches take the form "tag:TAG".
2395 static const char *checktag(const char *s
) {
2396 if(!strncmp(s
, "tag:", 4))
2402 /* return a list of tracks containing all of the words given. If you
2403 * ask for only stopwords you get no tracks. */
2404 char **trackdb_search(char **wordlist
, int nwordlist
, int *ntracks
) {
2405 const char **w
, *best
= 0, *tag
;
2406 char **twords
, **tags
;
2408 int i
, j
, n
, err
, what
;
2418 *ntracks
= 0; /* for early returns */
2419 /* normalize all the words */
2420 w
= xmalloc(nwordlist
* sizeof (char *));
2421 istag
= xmalloc_noptr(nwordlist
);
2422 for(n
= 0; n
< nwordlist
; ++n
) {
2426 w
[n
] = utf8_casefold_compat(wordlist
[n
], strlen(wordlist
[n
]), 0);
2427 if(checktag(w
[n
])) {
2428 ++ntags
; /* count up tags */
2429 /* Normalize the tag */
2430 w
[n
] = normalize_tag(w
[n
] + 4, strlen(w
[n
] + 4));
2433 /* Normalize the search term by removing combining characters */
2434 if(!(w32
= utf8_to_utf32(w
[n
], strlen(w
[n
]), &nw32
)))
2436 nw32
= remove_combining_chars(w32
, nw32
);
2437 if(!(w
[n
] = utf32_to_utf8(w32
, nw32
, 0)))
2442 /* find the longest non-stopword */
2443 for(n
= 0; n
< nwordlist
; ++n
)
2444 if(!istag
[n
] && !stopword(w
[n
]))
2445 if(!best
|| strlen(w
[n
]) > strlen(best
))
2447 /* TODO: we should at least in principal be able to identify the word or tag
2448 * with the least matches in log time, and choose that as our primary search
2450 if(ntags
&& !best
) {
2451 /* Only tags are listed. We limit to the first and narrow down with the
2453 best
= istag
[0] ? w
[0] : 0;
2454 db
= trackdb_tagsdb
;
2457 /* We can limit to some word. */
2458 db
= trackdb_searchdb
;
2461 /* Only stopwords */
2467 tid
= trackdb_begin_transaction();
2468 /* find all the tracks that have that word */
2473 cursor
= trackdb_opencursor(db
, tid
);
2474 while(!(err
= cursor
->c_get(cursor
, &k
, &d
, what
))) {
2475 vector_append(&v
, xstrndup(d
.data
, d
.size
));
2482 case DB_LOCK_DEADLOCK
:
2483 error(0, "error querying %s database: %s", dbname
, db_strerror(err
));
2486 fatal(0, "error querying %s database: %s", dbname
, db_strerror(err
));
2488 if(trackdb_closecursor(cursor
)) err
= DB_LOCK_DEADLOCK
;
2490 /* do a naive search over that (hopefuly fairly small) list of tracks */
2492 for(n
= 0; n
< v
.nvec
; ++n
) {
2493 if((err
= gettrackdata(v
.vec
[n
], 0, &p
, 0, 0, tid
) == DB_LOCK_DEADLOCK
))
2496 error(0, "track %s unexpected error: %s", v
.vec
[n
], db_strerror(err
));
2499 twords
= track_to_words(v
.vec
[n
], p
);
2500 tags
= parsetags(kvp_get(p
, "tags"));
2501 for(i
= 0; i
< nwordlist
; ++i
) {
2504 /* Track must have this tag */
2505 for(j
= 0; tags
[j
]; ++j
)
2506 if(!strcmp(tag
, tags
[j
])) break; /* tag found */
2507 if(!tags
[j
]) break; /* tag not found */
2509 /* Track must contain this word */
2510 for(j
= 0; twords
[j
]; ++j
)
2511 if(!strcmp(w
[i
], twords
[j
])) break; /* word found */
2512 if(!twords
[j
]) break; /* word not found */
2515 if(i
>= nwordlist
) /* all words found */
2516 vector_append(&u
, v
.vec
[n
]);
2520 trackdb_closecursor(cursor
);
2522 trackdb_abort_transaction(tid
);
2523 info("retrying search");
2525 trackdb_commit_transaction(tid
);
2526 vector_terminate(&u
);
2532 /* trackdb_scan **************************************************************/
2534 /** @brief Visit every track
2535 * @param root Root to scan or NULL for all
2536 * @param callback Callback for each track
2537 * @param u Passed to @p callback
2538 * @param tid Owning transaction
2539 * @return 0, DB_LOCK_DEADLOCK or EINTR
2541 * Visits every track and calls @p callback. @p callback will get the track
2542 * data and preferences and should return 0 to continue scanning or EINTR to
2545 int trackdb_scan(const char *root
,
2546 int (*callback
)(const char *track
,
2555 const size_t root_len
= root ?
strlen(root
) : 0;
2557 struct kvp
*data
, *prefs
;
2560 cursor
= trackdb_opencursor(trackdb_tracksdb
, tid
);
2562 err
= cursor
->c_get(cursor
, make_key(&k
, root
), prepare_data(&d
),
2565 memset(&k
, 0, sizeof k
);
2566 err
= cursor
->c_get(cursor
, &k
, prepare_data(&d
),
2571 || (k
.size
> root_len
2572 && !strncmp(k
.data
, root
, root_len
)
2573 && ((char *)k
.data
)[root_len
] == '/')) {
2574 data
= kvp_urldecode(d
.data
, d
.size
);
2575 if(kvp_get(data
, "_path")) {
2576 track
= xstrndup(k
.data
, k
.size
);
2577 /* TODO: trackdb_prefsdb is currently a DB_HASH. This means we have to
2578 * do a lookup for every single track. In fact this is quite quick:
2579 * with around 10,000 tracks a complete scan is around 0.3s on my
2580 * 2.2GHz Athlon. However, if it were a DB_BTREE, we could do the same
2581 * linear walk as we already do over trackdb_tracksdb, and probably get
2582 * even higher performance. That would require upgrade logic to
2583 * translate old databases though.
2585 switch(err
= trackdb_prefsdb
->get(trackdb_prefsdb
, tid
, &k
,
2586 prepare_data(&pd
), 0)) {
2588 prefs
= kvp_urldecode(pd
.data
, pd
.size
);
2593 case DB_LOCK_DEADLOCK
:
2594 error(0, "getting prefs: %s", db_strerror(err
));
2595 trackdb_closecursor(cursor
);
2598 fatal(0, "getting prefs: %s", db_strerror(err
));
2600 /* Advance to the next track before the callback so that the callback
2601 * may safely delete the track */
2602 err
= cursor
->c_get(cursor
, &k
, &d
, DB_NEXT
);
2603 if((cberr
= callback(track
, data
, prefs
, u
, tid
))) {
2608 err
= cursor
->c_get(cursor
, &k
, &d
, DB_NEXT
);
2612 trackdb_closecursor(cursor
);
2619 case DB_LOCK_DEADLOCK
:
2620 error(0, "c->c_get: %s", db_strerror(err
));
2623 fatal(0, "c->c_get: %s", db_strerror(err
));
2627 /* trackdb_rescan ************************************************************/
2629 /** @brief Node in the list of rescan-complete callbacks */
2630 struct rescanned_node
{
2631 struct rescanned_node
*next
;
2632 void (*rescanned
)(void *ru
);
2636 /** @brief List of rescan-complete callbacks */
2637 static struct rescanned_node
*rescanned_list
;
2639 /** @brief Add a rescan completion callback */
2640 void trackdb_add_rescanned(void (*rescanned
)(void *ru
),
2643 struct rescanned_node
*n
= xmalloc(sizeof *n
);
2644 n
->next
= rescanned_list
;
2645 n
->rescanned
= rescanned
;
2651 /* called when the rescanner terminates */
2652 static int reap_rescan(ev_source
attribute((unused
)) *ev
,
2655 const struct rusage
attribute((unused
)) *rusage
,
2656 void attribute((unused
)) *u
) {
2657 if(pid
== rescan_pid
) rescan_pid
= -1;
2659 error(0, RESCAN
": %s", wstat(status
));
2661 D((RESCAN
" terminated: %s", wstat(status
)));
2662 /* Our cache of file lookups is out of date now */
2663 cache_clean(&cache_files_type
);
2664 eventlog("rescanned", (char *)0);
2665 /* Call rescanned callbacks */
2666 while(rescanned_list
) {
2667 void (*rescanned
)(void *u_
) = rescanned_list
->rescanned
;
2668 void *ru
= rescanned_list
->ru
;
2670 rescanned_list
= rescanned_list
->next
;
2676 /** @brief Initiate a rescan
2677 * @param ev Event loop or 0 to block
2678 * @param recheck 1 to recheck lengths, 0 to suppress check
2679 * @param rescanned Called on completion (if not NULL)
2680 * @param ru Passed to @p rescanned
2682 void trackdb_rescan(ev_source
*ev
, int recheck
,
2683 void (*rescanned
)(void *ru
),
2687 if(rescan_pid
!= -1) {
2688 trackdb_add_rescanned(rescanned
, ru
);
2689 error(0, "rescan already underway");
2692 rescan_pid
= subprogram(ev
, -1, RESCAN
,
2693 recheck ?
"--check" : "--no-check",
2695 trackdb_add_rescanned(rescanned
, ru
);
2697 ev_child(ev
, rescan_pid
, 0, reap_rescan
, 0);
2698 D(("started rescanner"));
2700 /* This is the first rescan, we block until it is complete */
2701 while(waitpid(rescan_pid
, &w
, 0) < 0 && errno
== EINTR
)
2703 reap_rescan(0, rescan_pid
, w
, 0, 0);
2707 /** @brief Cancel a rescan
2708 * @return Nonzero if a rescan was cancelled
2710 int trackdb_rescan_cancel(void) {
2711 if(rescan_pid
== -1) return 0;
2712 if(kill(rescan_pid
, SIGTERM
) < 0)
2713 fatal(errno
, "error killing rescanner");
2718 /** @brief Return true if a rescan is underway */
2719 int trackdb_rescan_underway(void) {
2720 return rescan_pid
!= -1;
2723 /* global prefs **************************************************************/
2725 /** @brief Set a global preference
2726 * @param name Global preference name
2727 * @param value New value
2728 * @param who Who is setting it
2730 void trackdb_set_global(const char *name
,
2738 tid
= trackdb_begin_transaction();
2739 if(!(err
= trackdb_set_global_tid(name
, value
, tid
)))
2741 trackdb_abort_transaction(tid
);
2743 trackdb_commit_transaction(tid
);
2744 /* log important state changes */
2745 if(!strcmp(name
, "playing")) {
2746 state
= !value
|| !strcmp(value
, "yes");
2747 info("playing %s by %s",
2748 state ?
"enabled" : "disabled",
2750 eventlog("state", state ?
"enable_play" : "disable_play", (char *)0);
2752 if(!strcmp(name
, "random-play")) {
2753 state
= !value
|| !strcmp(value
, "yes");
2754 info("random play %s by %s",
2755 state ?
"enabled" : "disabled",
2757 eventlog("state", state ?
"enable_random" : "disable_random", (char *)0);
2761 /** @brief Set a global preference
2762 * @param name Global preference name
2763 * @param value New value
2764 * @param tid Owning transaction
2766 int trackdb_set_global_tid(const char *name
,
2772 memset(&k
, 0, sizeof k
);
2773 memset(&d
, 0, sizeof d
);
2774 k
.data
= (void *)name
;
2775 k
.size
= strlen(name
);
2777 d
.data
= (void *)value
;
2778 d
.size
= strlen(value
);
2781 err
= trackdb_globaldb
->put(trackdb_globaldb
, tid
, &k
, &d
, 0);
2783 err
= trackdb_globaldb
->del(trackdb_globaldb
, tid
, &k
, 0);
2784 if(err
== DB_LOCK_DEADLOCK
) return err
;
2786 fatal(0, "error updating database: %s", db_strerror(err
));
2790 /** @brief Get a global preference
2791 * @param name Global preference name
2792 * @return Value of global preference, or NULL if it's not set
2794 const char *trackdb_get_global(const char *name
) {
2800 tid
= trackdb_begin_transaction();
2801 if(!(err
= trackdb_get_global_tid(name
, tid
, &r
)))
2803 trackdb_abort_transaction(tid
);
2805 trackdb_commit_transaction(tid
);
2809 /** @brief Get a global preference
2810 * @param name Global preference name
2811 * @param tid Owning transaction
2812 * @param rp Where to store value (will get NULL if preference not set)
2813 * @return 0 or DB_LOCK_DEADLOCK
2815 int trackdb_get_global_tid(const char *name
,
2821 memset(&k
, 0, sizeof k
);
2822 k
.data
= (void *)name
;
2823 k
.size
= strlen(name
);
2824 switch(err
= trackdb_globaldb
->get(trackdb_globaldb
, tid
, &k
,
2825 prepare_data(&d
), 0)) {
2827 *rp
= xstrndup(d
.data
, d
.size
);
2832 case DB_LOCK_DEADLOCK
:
2835 fatal(0, "error reading database: %s", db_strerror(err
));
2839 /** @brief Retrieve the most recently added tracks
2840 * @param ntracksp Where to put count, or 0
2841 * @param maxtracks Maximum number of tracks to retrieve
2842 * @return null-terminated array of track names
2844 * The most recently added track is first in the array.
2846 char **trackdb_new(int *ntracksp
,
2852 tid
= trackdb_begin_transaction();
2853 tracks
= trackdb_new_tid(ntracksp
, maxtracks
, tid
);
2856 trackdb_abort_transaction(tid
);
2858 trackdb_commit_transaction(tid
);
2862 /** @brief Retrieve the most recently added tracks
2863 * @param ntracksp Where to put count, or 0
2864 * @param maxtracks Maximum number of tracks to retrieve, or 0 for all
2865 * @param tid Transaction ID
2866 * @return null-terminated array of track names, or NULL on deadlock
2868 * The most recently added track is first in the array.
2870 static char **trackdb_new_tid(int *ntracksp
,
2876 struct vector tracks
[1];
2877 hash
*h
= hash_new(1);
2879 vector_init(tracks
);
2880 c
= trackdb_opencursor(trackdb_noticeddb
, tid
);
2881 while((maxtracks
<= 0 || tracks
->nvec
< maxtracks
)
2882 && !(err
= c
->c_get(c
, prepare_data(&k
), prepare_data(&d
), DB_PREV
))) {
2883 char *const track
= xstrndup(d
.data
, d
.size
);
2884 /* Don't add any track more than once */
2885 if(hash_add(h
, track
, "", HASH_INSERT
))
2887 /* See if the track still exists */
2888 err
= trackdb_getdata(trackdb_tracksdb
, track
, NULL
/*kp*/, tid
);
2889 if(err
== DB_NOTFOUND
)
2890 continue; /* It doesn't, skip it */
2891 if(err
== DB_LOCK_DEADLOCK
)
2893 vector_append(tracks
, track
);
2896 case 0: /* hit maxtracks */
2897 case DB_NOTFOUND
: /* ran out of tracks */
2899 case DB_LOCK_DEADLOCK
:
2900 trackdb_closecursor(c
);
2903 fatal(0, "error reading noticed.db: %s", db_strerror(err
));
2905 if((err
= trackdb_closecursor(c
)))
2906 return 0; /* deadlock */
2907 vector_terminate(tracks
);
2909 *ntracksp
= tracks
->nvec
;
2913 /** @brief Expire noticed.db
2914 * @param earliest Earliest timestamp to keep
2916 void trackdb_expire_noticed(time_t earliest
) {
2920 tid
= trackdb_begin_transaction();
2921 if(!trackdb_expire_noticed_tid(earliest
, tid
))
2923 trackdb_abort_transaction(tid
);
2925 trackdb_commit_transaction(tid
);
2928 /** @brief Expire noticed.db
2929 * @param earliest Earliest timestamp to keep
2930 * @param tid Transaction ID
2931 * @return 0 or DB_LOCK_DEADLOCK
2933 static int trackdb_expire_noticed_tid(time_t earliest
, DB_TXN
*tid
) {
2941 c
= trackdb_opencursor(trackdb_noticeddb
, tid
);
2942 while(!(err
= c
->c_get(c
, prepare_data(&k
), prepare_data(&d
), DB_NEXT
))) {
2944 when
= (time_t)(((uint64_t)ntohl(kk
[0]) << 32) + ntohl(kk
[1]));
2945 if(when
>= earliest
)
2947 if((err
= c
->c_del(c
, 0))) {
2948 if(err
!= DB_LOCK_DEADLOCK
)
2949 fatal(0, "error deleting expired noticed.db entry: %s",
2955 if(err
== DB_NOTFOUND
)
2957 if(err
&& err
!= DB_LOCK_DEADLOCK
)
2958 fatal(0, "error expiring noticed.db: %s", db_strerror(err
));
2960 if((err
= trackdb_closecursor(c
))) {
2961 if(err
!= DB_LOCK_DEADLOCK
)
2962 fatal(0, "error closing cursor: %s", db_strerror(err
));
2966 info("expired %d tracks from noticed.db", count
);
2970 /* tidying up ****************************************************************/
2972 /** @brief Do database garbage collection
2974 * Called form periodic_database_gc().
2976 void trackdb_gc(void) {
2980 if((err
= trackdb_env
->txn_checkpoint(trackdb_env
,
2981 config
->checkpoint_kbyte
,
2982 config
->checkpoint_min
,
2984 fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err
));
2985 if((err
= trackdb_env
->log_archive(trackdb_env
, &logfiles
, DB_ARCH_REMOVE
)))
2986 fatal(0, "trackdb_env->log_archive: %s", db_strerror(err
));
2987 /* This makes catastrophic recovery impossible. However, the user can still
2988 * preserve the important data by using disorder-dump to snapshot their
2989 * prefs, and later to restore it. This is likely to have much small
2990 * long-term storage requirements than record the db logfiles. */
2993 /* user database *************************************************************/
2995 /** @brief Return true if @p user is trusted
2996 * @param user User to look up
2997 * @return Nonzero if they are in the 'trusted' list
2999 * Now used only in upgrade from old versions.
3001 static int trusted(const char *user
) {
3004 for(n
= 0; (n
< config
->trust
.n
3005 && strcmp(config
->trust
.s
[n
], user
)); ++n
)
3007 return n
< config
->trust
.n
;
3010 /** @brief Return non-zero for a valid username
3011 * @param user Candidate username
3012 * @return Nonzero if it's valid
3014 * Currently we only allow the letters and digits in ASCII. We could be more
3015 * liberal than this but it is a nice simple test. It is critical that
3016 * semicolons are never allowed.
3018 * NB also used by playlist_parse_name() to validate playlist names!
3020 int valid_username(const char *user
) {
3024 const uint8_t c
= *user
++;
3025 /* For now we are very strict */
3026 if((c
>= 'a' && c
<= 'z')
3027 || (c
>= 'A' && c
<= 'Z')
3028 || (c
>= '0' && c
<= '9'))
3036 /** @brief Add a user
3037 * @param user Username
3038 * @param password Initial password or NULL
3039 * @param rights Initial rights
3040 * @param email Email address or NULL
3041 * @param confirmation Confirmation string to require
3042 * @param tid Owning transaction
3043 * @param flags DB flags e.g. DB_NOOVERWRITE
3044 * @return 0, DB_KEYEXIST or DB_LOCK_DEADLOCK
3046 static int create_user(const char *user
,
3047 const char *password
,
3050 const char *confirmation
,
3056 /* sanity check user */
3057 if(!valid_username(user
)) {
3058 error(0, "invalid username '%s'", user
);
3061 if(parse_rights(rights
, 0, 1)) {
3062 error(0, "invalid rights string");
3065 /* data for this user */
3067 kvp_set(&k
, "password", password
);
3068 kvp_set(&k
, "rights", rights
);
3070 kvp_set(&k
, "email", email
);
3072 kvp_set(&k
, "confirmation", confirmation
);
3073 snprintf(s
, sizeof s
, "%jd", (intmax_t)xtime(0));
3074 kvp_set(&k
, "created", s
);
3075 return trackdb_putdata(trackdb_usersdb
, user
, k
, tid
, flags
);
3078 /** @brief Add one pre-existing user
3079 * @param user Username
3080 * @param password password
3081 * @param tid Owning transaction
3082 * @return 0, DB_KEYEXIST or DB_LOCK_DEADLOCK
3084 * Used only in upgrade from old versions.
3086 static int one_old_user(const char *user
, const char *password
,
3090 /* www-data doesn't get added */
3091 if(!strcmp(user
, "www-data")) {
3092 info("not adding www-data to user database");
3096 if(!strcmp(user
, "root"))
3098 else if(trusted(user
)) {
3101 parse_rights(config
->default_rights
, &r
, 1);
3102 r
&= ~(rights_type
)(RIGHT_SCRATCH__MASK
|RIGHT_MOVE__MASK
|RIGHT_REMOVE__MASK
);
3103 r
|= (RIGHT_ADMIN
|RIGHT_RESCAN
3104 |RIGHT_SCRATCH_ANY
|RIGHT_MOVE_ANY
|RIGHT_REMOVE_ANY
);
3105 rights
= rights_string(r
);
3107 rights
= config
->default_rights
;
3108 return create_user(user
, password
, rights
, 0/*email*/, 0/*confirmation*/,
3109 tid
, DB_NOOVERWRITE
);
3112 /** @brief Upgrade old users
3113 * @param tid Owning transaction
3114 * @return 0 or DB_LOCK_DEADLOCK
3116 static int trackdb_old_users_tid(DB_TXN
*tid
) {
3119 for(n
= 0; n
< config
->allow
.n
; ++n
) {
3120 switch(one_old_user(config
->allow
.s
[n
].s
[0], config
->allow
.s
[n
].s
[1],
3123 info("created user %s from 'allow' directive", config
->allow
.s
[n
].s
[0]);
3126 error(0, "user %s already exists, delete 'allow' directive",
3127 config
->allow
.s
[n
].s
[0]);
3128 /* This won't ever become fatal - eventually 'allow' will be
3131 case DB_LOCK_DEADLOCK
:
3132 return DB_LOCK_DEADLOCK
;
3138 /** @brief Read old 'allow' directives and copy them to the users database */
3139 void trackdb_old_users(void) {
3143 WITH_TRANSACTION(trackdb_old_users_tid(tid
));
3146 /** @brief Create a root user in the user database if there is none */
3147 void trackdb_create_root(void) {
3152 /* Choose a new root password */
3153 gcry_randomize(pwbin
, sizeof pwbin
, GCRY_STRONG_RANDOM
);
3154 pw
= mime_to_base64(pwbin
, sizeof pwbin
);
3155 /* Create the root user if it does not exist */
3156 WITH_TRANSACTION(create_user("root", pw
, "all",
3157 0/*email*/, 0/*confirmation*/,
3158 tid
, DB_NOOVERWRITE
));
3160 info("created root user");
3163 /** @brief Find a user's password from the database
3164 * @param user Username
3165 * @return Password or NULL
3167 * Only works if running as a user that can read the database!
3169 * If the user exists but has no password, "" is returned.
3171 const char *trackdb_get_password(const char *user
) {
3174 const char *password
;
3176 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb
, user
, &k
, tid
));
3179 password
= kvp_get(k
, "password");
3180 return password ? password
: "";
3183 /** @brief Add a new user
3184 * @param user Username
3185 * @param password Password or NULL
3186 * @param rights Initial rights
3187 * @param email Email address or NULL
3188 * @param confirmation Confirmation string or NULL
3189 * @return 0 on success, non-0 on error
3191 int trackdb_adduser(const char *user
,
3192 const char *password
,
3195 const char *confirmation
) {
3198 WITH_TRANSACTION(create_user(user
, password
, rights
, email
, confirmation
,
3199 tid
, DB_NOOVERWRITE
));
3201 error(0, "cannot create user '%s' because they already exist", user
);
3205 info("created user '%s' with rights '%s' and email address '%s'",
3206 user
, rights
, email
);
3208 info("created user '%s' with rights '%s'", user
, rights
);
3209 eventlog("user_add", user
, (char *)0);
3214 /** @brief Delete a user
3215 * @param user User to delete
3216 * @return 0 on success, non-0 if the user didn't exist anyway
3218 int trackdb_deluser(const char *user
) {
3221 WITH_TRANSACTION(trackdb_delkey(trackdb_usersdb
, user
, tid
));
3223 error(0, "cannot delete user '%s' because they do not exist", user
);
3226 info("deleted user '%s'", user
);
3227 eventlog("user_delete", user
, (char *)0);
3231 /** @brief Get user information
3232 * @param user User to query
3233 * @return Linked list of user information or NULL if user does not exist
3235 * Every user has at least a @c rights entry so NULL can be used to mean no
3238 struct kvp
*trackdb_getuserinfo(const char *user
) {
3242 WITH_TRANSACTION(trackdb_getdata(trackdb_usersdb
, user
, &k
, tid
));
3249 /** @brief Edit user information
3250 * @param user User to edit
3251 * @param key Key to change
3252 * @param value Value to set, or NULL to remove
3253 * @param tid Transaction ID
3254 * @return 0, DB_LOCK_DEADLOCK or DB_NOTFOUND
3256 static int trackdb_edituserinfo_tid(const char *user
, const char *key
,
3257 const char *value
, DB_TXN
*tid
) {
3261 if((e
= trackdb_getdata(trackdb_usersdb
, user
, &k
, tid
)))
3263 if(!kvp_set(&k
, key
, value
))
3264 return 0; /* no change */
3265 return trackdb_putdata(trackdb_usersdb
, user
, k
, tid
, 0);
3268 /** @brief Edit user information
3269 * @param user User to edit
3270 * @param key Key to change
3271 * @param value Value to set, or NULL to remove
3272 * @return 0 on success, non-0 on error
3274 int trackdb_edituserinfo(const char *user
,
3275 const char *key
, const char *value
) {
3278 if(!strcmp(key
, "rights")) {
3280 error(0, "cannot remove 'rights' key from user '%s'", user
);
3283 if(parse_rights(value
, 0, 1)) {
3284 error(0, "invalid rights string");
3287 } else if(!strcmp(key
, "email")) {
3289 if(!email_valid(value
)) {
3290 error(0, "invalid email address '%s' for user '%s'", value
, user
);
3294 value
= 0; /* no email -> remove key */
3295 } else if(!strcmp(key
, "created")) {
3296 error(0, "cannot change creation date for user '%s'", user
);
3298 } else if(strcmp(key
, "password")
3299 && !strcmp(key
, "confirmation")) {
3300 error(0, "unknown user info key '%s' for user '%s'", key
, user
);
3303 WITH_TRANSACTION(trackdb_edituserinfo_tid(user
, key
, value
, tid
));
3305 error(0, "unknown user '%s'", user
);
3308 eventlog("user_edit", user
, key
, (char *)0);
3313 /** @brief List all users
3314 * @return NULL-terminated list of users
3316 char **trackdb_listusers(void) {
3321 WITH_TRANSACTION(trackdb_listkeys(trackdb_usersdb
, v
, tid
));
3325 /** @brief Confirm a user registration
3326 * @param user Username
3327 * @param confirmation Confirmation string
3328 * @param rightsp Where to put user rights
3329 * @param tid Transaction ID
3330 * @return 0 on success, non-0 on error
3332 static int trackdb_confirm_tid(const char *user
, const char *confirmation
,
3333 rights_type
*rightsp
,
3335 const char *stored_confirmation
;
3340 if((e
= trackdb_getdata(trackdb_usersdb
, user
, &k
, tid
)))
3342 if(!(stored_confirmation
= kvp_get(k
, "confirmation"))) {
3343 error(0, "already confirmed user '%s'", user
);
3344 /* DB claims -30,800 to -30,999 so -1 should be a safe bet */
3347 if(!(rights
= kvp_get(k
, "rights"))) {
3348 error(0, "no rights for unconfirmed user '%s'", user
);
3351 if(parse_rights(rights
, rightsp
, 1))
3353 if(strcmp(confirmation
, stored_confirmation
)) {
3354 error(0, "wrong confirmation string for user '%s'", user
);
3358 kvp_set(&k
, "confirmation", 0);
3359 return trackdb_putdata(trackdb_usersdb
, user
, k
, tid
, 0);
3362 /** @brief Confirm a user registration
3363 * @param user Username
3364 * @param confirmation Confirmation string
3365 * @param rightsp Where to put user rights
3366 * @return 0 on success, non-0 on error
3368 int trackdb_confirm(const char *user
, const char *confirmation
,
3369 rights_type
*rightsp
) {
3372 WITH_TRANSACTION(trackdb_confirm_tid(user
, confirmation
, rightsp
, tid
));
3375 info("registration confirmed for user '%s'", user
);
3376 eventlog("user_confirm", user
, (char *)0);
3379 error(0, "confirmation for nonexistent user '%s'", user
);
3381 default: /* already reported */
3391 indent-tabs-mode:nil