StandardDirectory.cxx 7.25 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 * 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.
 */

#include "config.h"

// Use X Desktop guidelines where applicable
23
#if !defined(__APPLE__) && !defined(WIN32) && !defined(ANDROID)
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#define USE_XDG
#endif

#include "StandardDirectory.hxx"
#include "FileSystem.hxx"

#include <array>

#ifdef WIN32
#include <windows.h>
#include <shlobj.h>
#else
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#endif

#ifdef USE_XDG
43
#include "util/Error.hxx"
44
#include "util/StringUtil.hxx"
45
#include "io/TextFile.hxx"
46 47 48 49
#include <string.h>
#include <utility>
#endif

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

57 58 59 60 61 62 63 64 65 66 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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
#ifndef WIN32
class PasswdEntry
{
#if defined(HAVE_GETPWNAM_R) || defined(HAVE_GETPWUID_R)
	std::array<char, 16 * 1024> buf;
	passwd pw;
#endif

	passwd *result;
public:
	PasswdEntry() : result(nullptr) { }

	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

static inline bool IsValidPathString(PathTraitsFS::const_pointer path)
{
	return path != nullptr && *path != '\0';
}

static inline bool IsValidDir(PathTraitsFS::const_pointer dir)
{
	return PathTraitsFS::IsAbsolute(dir) &&
	       DirectoryExists(Path::FromFS(dir));
}

static inline AllocatedPath SafePathFromFS(PathTraitsFS::const_pointer dir)
{
	if (IsValidPathString(dir) && IsValidDir(dir))
		return AllocatedPath::FromFS(dir);
	return AllocatedPath::Null();
}

#ifdef WIN32
static AllocatedPath GetStandardDir(int folder_id)
{
115
	std::array<PathTraitsFS::value_type, MAX_PATH> dir;
116 117 118 119 120 121 122 123 124 125 126 127
	auto ret = SHGetFolderPath(nullptr, folder_id | CSIDL_FLAG_DONT_VERIFY,
				   nullptr, SHGFP_TYPE_CURRENT, dir.data());
	if (FAILED(ret))
		return AllocatedPath::Null();
	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 168 169 170 171
	// find end of the string
	if (quoted) {
		line_end = strrchr(line, '"');
		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 182
	*line_end = 0;

	// build the result path
	const char *path = line;
183 184 185 186 187 188

	auto result = AllocatedPath::Null();
	if (home_relative) {
		auto home = GetHomeDir();
		if (home.IsNull())
			return true;
189
		result = AllocatedPath::Build(home, path);
190
	} else {
191
		result = AllocatedPath::FromFS(path);
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
	}

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

static AllocatedPath GetUserDir(const char *name)
{
	auto result = AllocatedPath::Null();
	auto config_dir = GetUserConfigDir();
	if (config_dir.IsNull())
		return result;
	auto dirs_file = AllocatedPath::Build(config_dir, "user-dirs.dirs");
208
	TextFile input(dirs_file, IgnoreError());
209 210
	if (input.HasFailed())
		return result;
211
	char *line;
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	while ((line = input.ReadLine()) != nullptr)
		if (ParseConfigLine(line, name, result))
			return result;
	return result;
}

#endif

AllocatedPath GetUserConfigDir()
{
#if defined(WIN32)
	return GetStandardDir(CSIDL_LOCAL_APPDATA);
#elif defined(USE_XDG)
	// Check for $XDG_CONFIG_HOME
	auto config_home = getenv("XDG_CONFIG_HOME");
	if (IsValidPathString(config_home) && IsValidDir(config_home))
		return AllocatedPath::FromFS(config_home);

	// Check for $HOME/.config
	auto home = GetHomeDir();
	if (!home.IsNull()) {
		AllocatedPath fallback = AllocatedPath::Build(home, ".config");
		if (IsValidDir(fallback.c_str()))
			return fallback;
	}

	return AllocatedPath::Null();
#else
	return AllocatedPath::Null();
#endif
}

AllocatedPath GetUserMusicDir()
{
#if defined(WIN32)
	return GetStandardDir(CSIDL_MYMUSIC);	
#elif defined(USE_XDG)
	return GetUserDir("XDG_MUSIC_DIR");
250
#elif defined(ANDROID)
251
	return Environment::getExternalStoragePublicDirectory("Music");
252 253 254
#else
	return AllocatedPath::Null();
#endif
255 256
}

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

	// Check for $HOME/.cache
	auto home = GetHomeDir();
	if (!home.IsNull()) {
		AllocatedPath fallback = AllocatedPath::Build(home, ".cache");
		if (IsValidDir(fallback.c_str()))
			return fallback;
	}

	return AllocatedPath::Null();
274 275 276 277 278
#elif defined(ANDROID)
	return context->GetCacheDir(Java::GetEnv());
#else
	return AllocatedPath::Null();
#endif
279 280 281 282 283 284 285 286 287 288 289
}

#ifdef WIN32

AllocatedPath GetSystemConfigDir()
{
	return GetStandardDir(CSIDL_COMMON_APPDATA);
}

AllocatedPath GetAppBaseDir()
{
290
	std::array<PathTraitsFS::value_type, MAX_PATH> app;
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	auto ret = GetModuleFileName(nullptr, app.data(), app.size());

	// Check for error
	if (ret == 0)
		return AllocatedPath::Null();

	// Check for truncation
	if (ret == app.size() && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
		return AllocatedPath::Null();

	auto app_path = AllocatedPath::FromFS(app.data());
	return app_path.GetDirectoryName().GetDirectoryName();
}

#else

AllocatedPath GetHomeDir()
{
	auto home = getenv("HOME");
	if (IsValidPathString(home) && IsValidDir(home))
		return AllocatedPath::FromFS(home);
	PasswdEntry pw;
	if (pw.ReadByUid(getuid()))
		return SafePathFromFS(pw->pw_dir);
	return AllocatedPath::Null();
}

AllocatedPath GetHomeDir(const char *user_name)
{
	assert(user_name != nullptr);
	PasswdEntry pw;
	if (pw.ReadByName(user_name))
		return SafePathFromFS(pw->pw_dir);
	return AllocatedPath::Null();
}

#endif