2 This file is part of PulseAudio.
4 Copyright 2020 Igor V. Kovalenko <igor.v.kovalenko@gmail.com>
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
27 #include <pulse/xmalloc.h>
28 #include <pulsecore/core-util.h>
29 #include <pulsecore/log.h>
32 #include "core-error.h"
34 pa_database* pa_database_open(const char *path, const char *fn, bool prependmid, bool for_write) {
36 const char *filename_suffix = pa_database_get_filename_suffix();
38 char *machine_id = NULL, *filename_prefix, *full_path;
40 DIR *database_dir = NULL;
45 pa_assert(filename_suffix && filename_suffix[0]);
47 if (prependmid && !(machine_id = pa_machine_id())) {
51 /* Database file name starts with ${machine_id}-${fn} */
53 filename_prefix = pa_sprintf_malloc("%s-%s", machine_id, fn);
55 filename_prefix = pa_xstrdup(fn);
57 /* Search for existing database directory entry name matching architecture suffix and filename suffix. */
58 database_dir = opendir(path);
63 de = readdir(database_dir);
66 pa_log_warn("Unable to search for existing database file, readdir() failed: %s", pa_cstrerror(errno));
67 /* can continue as if there is no matching database file candidate */
73 if (pa_startswith(de->d_name, filename_prefix)
74 && de->d_name[strlen(filename_prefix)] == '.'
75 && pa_endswith(de->d_name + strlen(filename_prefix) + 1, filename_suffix)) {
77 /* candidate filename found, replace filename_prefix with this one */
79 pa_log_debug("Found existing database file '%s/%s', using it", path, de->d_name);
80 pa_xfree(filename_prefix);
81 filename_prefix = pa_xstrndup(de->d_name, strlen(de->d_name) - strlen(filename_suffix));
86 closedir(database_dir);
88 pa_log_warn("Unable to search for existing database file, failed to open directory %s: %s", path, pa_cstrerror(errno));
91 full_path = pa_sprintf_malloc("%s" PA_PATH_SEP "%s%s", path, filename_prefix, filename_suffix);
93 f = pa_database_open_internal(full_path, for_write);
96 pa_log_info("Successfully opened '%s' database file '%s'.", fn, full_path);
98 pa_log("Failed to open '%s' database file '%s': %s", fn, full_path, pa_cstrerror(errno));
101 pa_xfree(filename_prefix);
103 /* deallocate machine_id if it was used to construct file name */
104 pa_xfree(machine_id);