StandardDirectory.cxx 7.92 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 41
#include <windows.h>
#include <shlobj.h>
#else
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#endif

#ifdef USE_XDG
42
#include "util/StringStrip.hxx"
43
#include "util/StringCompare.hxx"
44
#include "io/TextFile.hxx"
45 46 47 48
#include <string.h>
#include <utility>
#endif

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

56
#if !defined(_WIN32) && !defined(ANDROID)
57 58 59 60 61 62 63
class PasswdEntry
{
#if defined(HAVE_GETPWNAM_R) || defined(HAVE_GETPWUID_R)
	std::array<char, 16 * 1024> buf;
	passwd pw;
#endif

64
	passwd *result{nullptr};
65
public:
66
	PasswdEntry() = default;
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

	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;
	}

	bool ReadByUid(uid_t uid) {
#ifdef HAVE_GETPWUID_R
		getpwuid_r(uid, &pw, buf.data(), buf.size(), &result);
#else
		result = getpwuid(uid);
#endif
		return result != nullptr;
	}

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

93
#ifndef ANDROID
94
static inline bool
95
IsValidPathString(PathTraitsFS::const_pointer path)
96 97 98 99
{
	return path != nullptr && *path != '\0';
}

100
static inline bool
101
IsValidDir(PathTraitsFS::const_pointer dir)
102 103 104 105 106
{
	return PathTraitsFS::IsAbsolute(dir) &&
	       DirectoryExists(Path::FromFS(dir));
}

107
static inline AllocatedPath
108
SafePathFromFS(PathTraitsFS::const_pointer dir)
109 110 111
{
	if (IsValidPathString(dir) && IsValidDir(dir))
		return AllocatedPath::FromFS(dir);
112
	return nullptr;
113
}
114
#endif
115

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

#ifdef USE_XDG

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

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

	// 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
148
	line = StripLeft(line);
149 150 151
	if (*line != '=')
		return false;
	++line;
152
	line = StripLeft(line);
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

	// 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;
	}


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

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

183 184 185
	*line_end = 0;

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

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

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

205 206
static AllocatedPath
GetUserDir(const char *name) noexcept
207
try {
208
	AllocatedPath result = nullptr;
209 210 211
	auto config_dir = GetUserConfigDir();
	if (config_dir.IsNull())
		return result;
212

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

#endif

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

	// Check for $HOME/.config
237
	if (const auto home = GetHomeDir(); !home.IsNull()) {
238
		auto fallback = home / Path::FromFS(".config");
239 240 241 242
		if (IsValidDir(fallback.c_str()))
			return fallback;
	}

243
	return nullptr;
244
#else
245
	return nullptr;
246 247 248
#endif
}

249 250
AllocatedPath
GetUserMusicDir() noexcept
251
{
252
#if defined(_WIN32)
253 254 255
	return GetStandardDir(CSIDL_MYMUSIC);	
#elif defined(USE_XDG)
	return GetUserDir("XDG_MUSIC_DIR");
256
#elif defined(ANDROID)
257
	return Environment::getExternalStoragePublicDirectory("Music");
258
#else
259
	return nullptr;
260
#endif
261 262
}

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

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

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

286 287 288 289 290 291 292 293 294 295
AllocatedPath
GetUserRuntimeDir() noexcept
{
#ifdef USE_XDG
	return SafePathFromFS(getenv("XDG_RUNTIME_DIR"));
#else
	return nullptr;
#endif
}

296 297 298
AllocatedPath
GetAppRuntimeDir() noexcept
{
299 300 301 302 303 304 305 306
#ifdef __linux__
	/* 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

307 308 309 310 311 312 313 314 315 316 317
#ifdef USE_XDG
	if (const auto user_dir = GetUserRuntimeDir(); !user_dir.IsNull()) {
		auto dir = user_dir / Path::FromFS("mpd");
		mkdir(dir.c_str(), 0700);
		return dir;
	}
#endif

	return nullptr;
}

318
#ifdef _WIN32
319

320 321
AllocatedPath
GetSystemConfigDir() noexcept
322 323 324 325
{
	return GetStandardDir(CSIDL_COMMON_APPDATA);
}

326 327
AllocatedPath
GetAppBaseDir() noexcept
328
{
329
	std::array<PathTraitsFS::value_type, MAX_PATH> app;
330 331 332 333
	auto ret = GetModuleFileName(nullptr, app.data(), app.size());

	// Check for error
	if (ret == 0)
334
		return nullptr;
335 336 337

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

340
	auto app_path = AllocatedPath::FromFS(PathTraitsFS::string_view(app.data(), ret));
341 342 343 344 345
	return app_path.GetDirectoryName().GetDirectoryName();
}

#else

346 347
AllocatedPath
GetHomeDir() noexcept
348
{
349
#ifndef ANDROID
350 351
	if (const auto home = getenv("HOME");
	    IsValidPathString(home) && IsValidDir(home))
352
		return AllocatedPath::FromFS(home);
353 354

	if (PasswdEntry pw; pw.ReadByUid(getuid()))
355
		return SafePathFromFS(pw->pw_dir);
356
#endif
357
	return nullptr;
358 359
}

360 361
AllocatedPath
GetHomeDir(const char *user_name) noexcept
362
{
363 364 365
#ifdef ANDROID
	(void)user_name;
#else
366
	assert(user_name != nullptr);
367 368

	if (PasswdEntry pw; pw.ReadByName(user_name))
369
		return SafePathFromFS(pw->pw_dir);
370
#endif
371
	return nullptr;
372 373 374
}

#endif