StandardDirectory.cxx 8.19 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

20 21 22 23
#ifdef _WIN32
#undef NOUSER // COM needs the "MSG" typedef, and shlobj.h includes COM headers
#endif

24 25
#include "StandardDirectory.hxx"
#include "FileSystem.hxx"
26
#include "XDG.hxx"
27
#include "util/StringView.hxx"
28
#include "config.h"
29 30 31

#include <array>

32
#ifdef _WIN32
33 34 35 36 37 38 39 40
#include <windows.h>
#include <shlobj.h>
#else
#include <stdlib.h>
#include <pwd.h>
#endif

#ifdef USE_XDG
41
#include "util/StringStrip.hxx"
42
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
43
#include "fs/io/TextFile.hxx"
44 45 46 47
#include <string.h>
#include <utility>
#endif

48 49 50
#ifdef ANDROID
#include "java/Global.hxx"
#include "android/Environment.hxx"
51 52
#include "android/Context.hxx"
#include "Main.hxx"
53 54
#endif

55 56 57 58 59 60
#ifdef USE_XDG
#include "Version.h" // for PACKAGE_NAME
#define APP_FILENAME PATH_LITERAL(PACKAGE_NAME)
static constexpr Path app_filename = Path::FromFS(APP_FILENAME);
#endif

61
#if !defined(_WIN32) && !defined(ANDROID)
62 63 64 65 66 67 68
class PasswdEntry
{
#if defined(HAVE_GETPWNAM_R) || defined(HAVE_GETPWUID_R)
	std::array<char, 16 * 1024> buf;
	passwd pw;
#endif

69
	passwd *result{nullptr};
70
public:
71
	PasswdEntry() = default;
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

	bool ReadByName(const char *name) {
#ifdef HAVE_GETPWNAM_R
		getpwnam_r(name, &pw, buf.data(), buf.size(), &result);
#else
		result = getpwnam(name);
#endif
		return result != nullptr;
	}

	const passwd *operator->() {
		assert(result != nullptr);
		return result;
	}
};
#endif

89
#ifndef ANDROID
90
static inline bool
91
IsValidPathString(PathTraitsFS::const_pointer path)
92 93 94 95
{
	return path != nullptr && *path != '\0';
}

96
static inline bool
97
IsValidDir(PathTraitsFS::const_pointer dir)
98 99 100 101 102
{
	return PathTraitsFS::IsAbsolute(dir) &&
	       DirectoryExists(Path::FromFS(dir));
}

103
static inline AllocatedPath
104
SafePathFromFS(PathTraitsFS::const_pointer dir)
105 106 107
{
	if (IsValidPathString(dir) && IsValidDir(dir))
		return AllocatedPath::FromFS(dir);
108
	return nullptr;
109
}
110
#endif
111

112
#ifdef _WIN32
113 114
static AllocatedPath GetStandardDir(int folder_id)
{
115
	std::array<PathTraitsFS::value_type, MAX_PATH> dir;
116 117 118
	auto ret = SHGetFolderPath(nullptr, folder_id | CSIDL_FLAG_DONT_VERIFY,
				   nullptr, SHGFP_TYPE_CURRENT, dir.data());
	if (FAILED(ret))
119
		return nullptr;
120 121 122 123 124 125 126 127
	return SafePathFromFS(dir.data());
}
#endif

#ifdef USE_XDG

static const char home_prefix[] = "$HOME/";

128 129
static bool
ParseConfigLine(char *line, const char *dir_name, AllocatedPath &result_dir)
130 131
{
	// strip leading white space
132
	line = StripLeft(line);
133 134 135 136 137 138 139 140 141 142 143

	// check for end-of-line or comment
	if (*line == '\0' || *line == '#')
		return false;

	// check if current setting is for requested dir
	if (!StringStartsWith(line, dir_name))
		return false;
	line += strlen(dir_name);

	// strip equals sign and spaces around it
144
	line = StripLeft(line);
145 146 147
	if (*line != '=')
		return false;
	++line;
148
	line = StripLeft(line);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

	// check if path is quoted
	bool quoted = false;
	if (*line == '"') {
		++line;
		quoted = true;
	}

	// check if path is relative to $HOME
	bool home_relative = false;
	if (StringStartsWith(line, home_prefix)) {
		line += strlen(home_prefix);
		home_relative = true;
	}


165
	char *line_end;
166 167
	// find end of the string
	if (quoted) {
Rosen Penev's avatar
Rosen Penev committed
168
		line_end = std::strrchr(line, '"');
169 170 171
		if (line_end == nullptr)
			return true;
	} else {
172
		line_end = StripRight(line, line + strlen(line));
173 174 175 176 177 178
	}

	// check for empty result
	if (line == line_end)
		return true;

179 180 181
	*line_end = 0;

	// build the result path
182
	const auto path_fs = Path::FromFS(line);
183

184
	AllocatedPath result = nullptr;
185 186 187 188
	if (home_relative) {
		auto home = GetHomeDir();
		if (home.IsNull())
			return true;
189
		result = home / path_fs;
190
	} else {
191
		result = AllocatedPath(path_fs);
192 193 194 195 196 197 198 199 200
	}

	if (IsValidDir(result.c_str())) {
		result_dir = std::move(result);
		return true;
	}
	return true;
}

201 202
static AllocatedPath
GetUserDir(const char *name) noexcept
203
try {
204
	AllocatedPath result = nullptr;
205 206 207
	auto config_dir = GetUserConfigDir();
	if (config_dir.IsNull())
		return result;
208

209
	TextFile input(config_dir / Path::FromFS("user-dirs.dirs"));
210
	char *line;
211 212 213 214
	while ((line = input.ReadLine()) != nullptr)
		if (ParseConfigLine(line, name, result))
			return result;
	return result;
215
} catch (const std::exception &e) {
216
	return nullptr;
217 218 219 220
}

#endif

221 222
AllocatedPath
GetUserConfigDir() noexcept
223
{
224
#if defined(_WIN32)
225 226 227
	return GetStandardDir(CSIDL_LOCAL_APPDATA);
#elif defined(USE_XDG)
	// Check for $XDG_CONFIG_HOME
228 229
	if (const auto config_home = getenv("XDG_CONFIG_HOME");
	    IsValidPathString(config_home) && IsValidDir(config_home))
230 231 232
		return AllocatedPath::FromFS(config_home);

	// Check for $HOME/.config
233
	if (const auto home = GetHomeDir(); !home.IsNull()) {
234
		auto fallback = home / Path::FromFS(".config");
235 236 237 238
		if (IsValidDir(fallback.c_str()))
			return fallback;
	}

239
	return nullptr;
240
#else
241
	return nullptr;
242 243 244
#endif
}

245 246
AllocatedPath
GetUserMusicDir() noexcept
247
{
248
#if defined(_WIN32)
249 250 251
	return GetStandardDir(CSIDL_MYMUSIC);	
#elif defined(USE_XDG)
	return GetUserDir("XDG_MUSIC_DIR");
252
#elif defined(ANDROID)
253 254
	return Environment::getExternalStoragePublicDirectory(Java::GetEnv(),
							      "Music");
255
#else
256
	return nullptr;
257
#endif
258 259
}

260 261
AllocatedPath
GetUserCacheDir() noexcept
262 263
{
#ifdef USE_XDG
264
	// Check for $XDG_CACHE_HOME
265 266
	if (const auto cache_home = getenv("XDG_CACHE_HOME");
	    IsValidPathString(cache_home) && IsValidDir(cache_home))
267 268 269
		return AllocatedPath::FromFS(cache_home);

	// Check for $HOME/.cache
270 271 272
	if (const auto home = GetHomeDir(); !home.IsNull())
		if (auto fallback = home / Path::FromFS(".cache");
		    IsValidDir(fallback.c_str()))
273 274
			return fallback;

275
	return nullptr;
276 277 278
#elif defined(ANDROID)
	return context->GetCacheDir(Java::GetEnv());
#else
279
	return nullptr;
280
#endif
281 282
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
AllocatedPath
GetAppCacheDir() noexcept
{
#ifdef USE_XDG
	if (const auto user_dir = GetUserCacheDir(); !user_dir.IsNull()) {
		auto dir = user_dir / app_filename;
		CreateDirectoryNoThrow(dir);
		return dir;
	}

	return nullptr;
#elif defined(ANDROID)
	return context->GetCacheDir(Java::GetEnv());
#else
	return nullptr;
#endif
}

301 302 303 304 305 306 307 308 309 310
AllocatedPath
GetUserRuntimeDir() noexcept
{
#ifdef USE_XDG
	return SafePathFromFS(getenv("XDG_RUNTIME_DIR"));
#else
	return nullptr;
#endif
}

311 312 313
AllocatedPath
GetAppRuntimeDir() noexcept
{
314
#if defined(__linux__) && !defined(ANDROID)
315 316 317 318 319 320 321
	/* systemd specific; see systemd.exec(5) */
	if (const char *runtime_directory = getenv("RUNTIME_DIRECTORY"))
		if (auto dir = StringView{runtime_directory}.Split(':').first;
		    !dir.empty())
			return AllocatedPath::FromFS(dir);
#endif

322 323
#ifdef USE_XDG
	if (const auto user_dir = GetUserRuntimeDir(); !user_dir.IsNull()) {
324
		auto dir = user_dir / app_filename;
325
		CreateDirectoryNoThrow(dir);
326 327 328 329 330 331 332
		return dir;
	}
#endif

	return nullptr;
}

333
#ifdef _WIN32
334

335 336
AllocatedPath
GetSystemConfigDir() noexcept
337 338 339 340
{
	return GetStandardDir(CSIDL_COMMON_APPDATA);
}

341 342
AllocatedPath
GetAppBaseDir() noexcept
343
{
344
	std::array<PathTraitsFS::value_type, MAX_PATH> app;
345 346 347 348
	auto ret = GetModuleFileName(nullptr, app.data(), app.size());

	// Check for error
	if (ret == 0)
349
		return nullptr;
350 351 352

	// Check for truncation
	if (ret == app.size() && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
353
		return nullptr;
354

355
	auto app_path = AllocatedPath::FromFS(PathTraitsFS::string_view(app.data(), ret));
356 357 358 359 360
	return app_path.GetDirectoryName().GetDirectoryName();
}

#else

361 362
AllocatedPath
GetHomeDir() noexcept
363
{
364
#ifndef ANDROID
365 366
	if (const auto home = getenv("HOME");
	    IsValidPathString(home) && IsValidDir(home))
367
		return AllocatedPath::FromFS(home);
368
#endif
369

370
	return nullptr;
371 372
}

373 374
AllocatedPath
GetHomeDir(const char *user_name) noexcept
375
{
376 377 378
#ifdef ANDROID
	(void)user_name;
#else
379
	assert(user_name != nullptr);
380 381

	if (PasswdEntry pw; pw.ReadByName(user_name))
382
		return SafePathFromFS(pw->pw_dir);
383
#endif
384
	return nullptr;
385 386 387
}

#endif