1 /*
2  * libdpkg - Debian packaging suite library routines
3  * dbdir.c - on-disk database directory functions
4  *
5  * Copyright © 2011 Guillem Jover <guillem@debian.org>
6  *
7  * This is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 #include <compat.h>
23 
24 #include <sys/types.h>
25 
26 #include <stdlib.h>
27 
28 #include <dpkg/dpkg.h>
29 #include <dpkg/dpkg-db.h>
30 
31 static const char *db_dir = ADMINDIR;
32 
33 /**
34  * Set current on-disk database directory.
35  *
36  * The directory is initially set to ADMINDIR, this function can be used to
37  * set the directory to a new value, or to set it to a default value if dir
38  * is NULL. For the latter the order is, value from environment variable
39  * DPKG_ADMINDIR, and then the built-in default ADMINDIR,
40  *
41  * @param dir The new database directory, or NULL to set to default.
42  *
43  * @return The new database directory.
44  */
45 const char *
dpkg_db_set_dir(const char * dir)46 dpkg_db_set_dir(const char *dir)
47 {
48 	if (dir == NULL) {
49 		const char *env;
50 
51 		env = getenv("DPKG_ADMINDIR");
52 		if (env)
53 			db_dir = env;
54 		else
55 			db_dir = ADMINDIR;
56 	} else {
57 		db_dir = dir;
58 	}
59 
60 	return db_dir;
61 }
62 
63 /**
64  * Get current on-disk database directory.
65  *
66  * @return The current database directory.
67  */
68 const char *
dpkg_db_get_dir(void)69 dpkg_db_get_dir(void)
70 {
71 	return db_dir;
72 }
73 
74 /**
75  * Get a pathname to the current on-disk database directory.
76  *
77  * This function returns an allocated string, which should be freed with
78  * free(2).
79  *
80  * @param pathpart The pathpart to append to the new pathname.
81  *
82  * @return The newly allocated pathname.
83  */
84 char *
dpkg_db_get_path(const char * pathpart)85 dpkg_db_get_path(const char *pathpart)
86 {
87 	return str_fmt("%s/%s", db_dir, pathpart);
88 }
89