Debian Codegraph @

source/misc/embedded_libs/PlatformFolders-4.2.0/sago/platform_folders.cpp

raw symbols SCIP
1 /*
2 Its is under the MIT license, to encourage reuse by cut-and-paste.
3
4 The original files are hosted here: https://github.com/sago007/PlatformFolders
5
6 Copyright (c) 2015-2016 Poul Sander
7
8 Permission is hereby granted, free of charge, to any person
9 obtaining a copy of this software and associated documentation files
10 (the "Software"), to deal in the Software without restriction,
11 including without limitation the rights to use, copy, modify, merge,
12 publish, distribute, sublicense, and/or sell copies of the Software,
13 and to permit persons to whom the Software is furnished to do so,
14 subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be
17 included in all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
23 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
24 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 SOFTWARE.
27 */
28
29 #include "platform_folders.h"
30 #include <iostream>
31 #include <stdexcept>
32 #include <cstdio>
33 #include <cstdlib>
34
35 #ifndef _WIN32
36
37 #include <pwd.h>
38 #include <unistd.h>
39
40 /**
41 * Retrives the effective user's home dir.
42 * If the user is running as root we ignore the HOME environment. It works badly with sudo.
43 * Writing to $HOME as root implies security concerns that a multiplatform program cannot be assumed to handle.
44 * @return The home directory. HOME environment is respected for non-root users if it exists.
45 */
46 static std::string getHome() {
47 std::string res;
48 int uid = getuid();
49 const char* homeEnv = std::getenv("HOME");
50 if ( uid != 0 && homeEnv) {
51 //We only acknowlegde HOME if not root.
52 res = homeEnv;
53 return res;
54 }
55 struct passwd* pw = nullptr;
56 struct passwd pwd;
57 long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
58 if (bufsize < 0) {
59 bufsize = 16384;
60 }
61 std::vector<char> buffer;
62 buffer.resize(bufsize);
63 int error_code = getpwuid_r(uid, &pwd, buffer.data(), buffer.size(), &pw);
64 if (error_code) {
65 throw std::runtime_error("Unable to get passwd struct.");
66 }
67 const char* tempRes = pw->pw_dir;
68 if (!tempRes) {
69 throw std::runtime_error("User has no home directory");
70 }
71 res = tempRes;
72 return res;
73 }
74
75 #endif
76
77 #ifdef _WIN32
78 // Make sure we don't bring in all the extra junk with windows.h
79 #ifndef WIN32_LEAN_AND_MEAN
80 #define WIN32_LEAN_AND_MEAN
81 #endif
82 // stringapiset.h depends on this
83 #include <windows.h>
84 // For SUCCEEDED macro
85 #include <winerror.h>
86 // For WideCharToMultiByte
87 #include <stringapiset.h>
88 // For SHGetFolderPathW and various CSIDL "magic numbers"
89 #include <shlobj.h>
90
91 namespace sago {
92 namespace internal {
93
94 std::string win32_utf16_to_utf8(const wchar_t* wstr) {
95 std::string res;
96 // If the 6th parameter is 0 then WideCharToMultiByte returns the number of bytes needed to store the result.
97 int actualSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nullptr, 0, nullptr, nullptr);
98 if (actualSize > 0) {
99 //If the converted UTF-8 string could not be in the initial buffer. Allocate one that can hold it.
100 std::vector<char> buffer(actualSize);
101 actualSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &buffer[0], static_cast<int>(buffer.size()), nullptr, nullptr);
102 res = buffer.data();
103 }
104 if (actualSize == 0) {
105 // WideCharToMultiByte return 0 for errors.
106 throw std::runtime_error("UTF16 to UTF8 failed with error code: " + std::to_string(GetLastError()));
107 }
108 return res;
109 }
110
111 } // namesapce internal
112 } // namespace sago
113
114 class FreeCoTaskMemory {
115 LPWSTR pointer = NULL;
116 public:
117 explicit FreeCoTaskMemory(LPWSTR pointer) : pointer(pointer) {};
118 ~FreeCoTaskMemory() {
119 CoTaskMemFree(pointer);
120 }
121 };
122
123 static std::string GetKnownWindowsFolder(REFKNOWNFOLDERID folderId, const char* errorMsg) {
124 LPWSTR wszPath = NULL;
125 HRESULT hr;
126 hr = SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, NULL, &wszPath);
127 FreeCoTaskMemory scopeBoundMemory(wszPath);
128
129 if (!SUCCEEDED(hr)) {
130 throw std::runtime_error(errorMsg);
131 }
132 return sago::internal::win32_utf16_to_utf8(wszPath);
133 }
134
135 static std::string GetAppData() {
136 return GetKnownWindowsFolder(FOLDERID_RoamingAppData, "RoamingAppData could not be found");
137 }
138
139 static std::string GetAppDataCommon() {
140 return GetKnownWindowsFolder(FOLDERID_ProgramData, "ProgramData could not be found");
141 }
142
143 static std::string GetAppDataLocal() {
144 return GetKnownWindowsFolder(FOLDERID_LocalAppData, "LocalAppData could not be found");
145 }
146 #elif defined(__APPLE__)
147 #else
148 #include <map>
149 #include <fstream>
150 #include <sys/types.h>
151 // For strlen and strtok
152 #include <cstring>
153 #include <sstream>
154 //Typically Linux. For easy reading the comments will just say Linux but should work with most *nixes
155
156 static void throwOnRelative(const char* envName, const char* envValue) {
157 if (envValue[0] != '/') {
158 char buffer[200];
159 std::snprintf(buffer, sizeof(buffer), "Environment \"%s\" does not start with an '/'. XDG specifies that the value must be absolute. The current value is: \"%s\"", envName, envValue);
160 throw std::runtime_error(buffer);
161 }
162 }
163
164
165
166 static std::string getLinuxFolderDefault(const char* envName, const char* defaultRelativePath) {
167 std::string res;
168 const char* tempRes = std::getenv(envName);
169 if (tempRes) {
170 throwOnRelative(envName, tempRes);
171 res = tempRes;
172 return res;
173 }
174 res = getHome() + "/" + defaultRelativePath;
175 return res;
176 }
177
178 static void appendExtraFolders(const char* envName, const char* defaultValue, std::vector<std::string>& folders) {
179 const char* envValue = std::getenv(envName);
180 if (!envValue) {
181 envValue = defaultValue;
182 }
183 sago::internal::appendExtraFoldersTokenizer(envName, envValue, folders);
184 }
185
186 #endif
187
188
189 namespace sago {
190
191 #if !defined(_WIN32) && !defined(__APPLE__)
192 namespace internal {
193 void appendExtraFoldersTokenizer(const char* envName, const char* envValue, std::vector<std::string>& folders) {
194 std::stringstream ss(envValue);
195 std::string value;
196 while (std::getline(ss, value, ':')) {
197 if (value[0] == '/') {
198 folders.push_back(value);
199 }
200 else {
201 //Unless the system is wrongly configured this should never happen... But of course some systems will be incorectly configured.
202 //The XDG documentation indicates that the folder should be ignored but that the program should continue.
203 std::cerr << "Skipping path \"" << value << "\" in \"" << envName << "\" because it does not start with a \"/\"\n";
204 }
205 }
206 }
207 }
208 #endif
209
210 std::string getDataHome() {
211 #ifdef _WIN32
212 return GetAppData();
213 #elif defined(__APPLE__)
214 return getHome()+"/Library/Application Support";
215 #else
216 return getLinuxFolderDefault("XDG_DATA_HOME", ".local/share");
217 #endif
218 }
219
220 std::string getConfigHome() {
221 #ifdef _WIN32
222 return GetAppData();
223 #elif defined(__APPLE__)
224 return getHome()+"/Library/Application Support";
225 #else
226 return getLinuxFolderDefault("XDG_CONFIG_HOME", ".config");
227 #endif
228 }
229
230 std::string getCacheDir() {
231 #ifdef _WIN32
232 return GetAppDataLocal();
233 #elif defined(__APPLE__)
234 return getHome()+"/Library/Caches";
235 #else
236 return getLinuxFolderDefault("XDG_CACHE_HOME", ".cache");
237 #endif
238 }
239
240 std::string getStateDir() {
241 #ifdef _WIN32
242 return GetAppDataLocal();
243 #elif defined(__APPLE__)
244 return getHome()+"/Library/Application Support";
245 #else
246 return getLinuxFolderDefault("XDG_STATE_HOME", ".local/state");
247 #endif
248 }
249
250 void appendAdditionalDataDirectories(std::vector<std::string>& homes) {
251 #ifdef _WIN32
252 homes.push_back(GetAppDataCommon());
253 #elif !defined(__APPLE__)
254 appendExtraFolders("XDG_DATA_DIRS", "/usr/local/share/:/usr/share/", homes);
255 #endif
256 }
257
258 void appendAdditionalConfigDirectories(std::vector<std::string>& homes) {
259 #ifdef _WIN32
260 homes.push_back(GetAppDataCommon());
261 #elif !defined(__APPLE__)
262 appendExtraFolders("XDG_CONFIG_DIRS", "/etc/xdg", homes);
263 #endif
264 }
265
266 #if !defined(_WIN32) && !defined(__APPLE__)
267 struct PlatformFolders::PlatformFoldersData {
268 std::map<std::string, std::string> folders;
269 };
270
271 static void PlatformFoldersAddFromFile(const std::string& filename, std::map<std::string, std::string>& folders) {
272 std::ifstream infile(filename.c_str());
273 std::string line;
274 while (std::getline(infile, line)) {
275 if (line.length() == 0 || line.at(0) == '#' || line.substr(0, 4) != "XDG_" || line.find("_DIR") == std::string::npos) {
276 continue;
277 }
278 try {
279 std::size_t splitPos = line.find('=');
280 std::string key = line.substr(0, splitPos);
281 std::size_t valueStart = line.find('"', splitPos);
282 std::size_t valueEnd = line.find('"', valueStart+1);
283 std::string value = line.substr(valueStart+1, valueEnd - valueStart - 1);
284 folders[key] = value;
285 }
286 catch (std::exception& e) {
287 std::cerr << "WARNING: Failed to process \"" << line << "\" from \"" << filename << "\". Error: "<< e.what() << "\n";
288 continue;
289 }
290 }
291 }
292
293 static void PlatformFoldersFillData(std::map<std::string, std::string>& folders) {
294 folders["XDG_DOCUMENTS_DIR"] = "$HOME/Documents";
295 folders["XDG_DESKTOP_DIR"] = "$HOME/Desktop";
296 folders["XDG_DOWNLOAD_DIR"] = "$HOME/Downloads";
297 folders["XDG_MUSIC_DIR"] = "$HOME/Music";
298 folders["XDG_PICTURES_DIR"] = "$HOME/Pictures";
299 folders["XDG_PUBLICSHARE_DIR"] = "$HOME/Public";
300 folders["XDG_TEMPLATES_DIR"] = "$HOME/.Templates";
301 folders["XDG_VIDEOS_DIR"] = "$HOME/Videos";
302 PlatformFoldersAddFromFile( getConfigHome()+"/user-dirs.dirs", folders);
303 for (std::map<std::string, std::string>::iterator itr = folders.begin() ; itr != folders.end() ; ++itr ) {
304 std::string& value = itr->second;
305 if (value.compare(0, 5, "$HOME") == 0) {
306 value = getHome() + value.substr(5, std::string::npos);
307 }
308 }
309 }
310 #endif
311
312 PlatformFolders::PlatformFolders() {
313 #if !defined(_WIN32) && !defined(__APPLE__)
314 this->data = new PlatformFolders::PlatformFoldersData();
315 try {
316 PlatformFoldersFillData(data->folders);
317 }
318 catch (...) {
319 delete this->data;
320 throw;
321 }
322 #endif
323 }
324
325 PlatformFolders::~PlatformFolders() {
326 #if !defined(_WIN32) && !defined(__APPLE__)
327 delete this->data;
328 #endif
329 }
330
331 std::string PlatformFolders::getDocumentsFolder() const {
332 #ifdef _WIN32
333 return GetKnownWindowsFolder(FOLDERID_Documents, "Failed to find My Documents folder");
334 #elif defined(__APPLE__)
335 return getHome()+"/Documents";
336 #else
337 return data->folders["XDG_DOCUMENTS_DIR"];
338 #endif
339 }
340
341 std::string PlatformFolders::getDesktopFolder() const {
342 #ifdef _WIN32
343 return GetKnownWindowsFolder(FOLDERID_Desktop, "Failed to find Desktop folder");
344 #elif defined(__APPLE__)
345 return getHome()+"/Desktop";
346 #else
347 return data->folders["XDG_DESKTOP_DIR"];
348 #endif
349 }
350
351 std::string PlatformFolders::getPicturesFolder() const {
352 #ifdef _WIN32
353 return GetKnownWindowsFolder(FOLDERID_Pictures, "Failed to find My Pictures folder");
354 #elif defined(__APPLE__)
355 return getHome()+"/Pictures";
356 #else
357 return data->folders["XDG_PICTURES_DIR"];
358 #endif
359 }
360
361 std::string PlatformFolders::getPublicFolder() const {
362 #ifdef _WIN32
363 return GetKnownWindowsFolder(FOLDERID_Public, "Failed to find the Public folder");
364 #elif defined(__APPLE__)
365 return getHome()+"/Public";
366 #else
367 return data->folders["XDG_PUBLICSHARE_DIR"];
368 #endif
369 }
370
371 std::string PlatformFolders::getDownloadFolder1() const {
372 #ifdef _WIN32
373 return GetKnownWindowsFolder(FOLDERID_Downloads, "Failed to find My Downloads folder");
374 #elif defined(__APPLE__)
375 return getHome()+"/Downloads";
376 #else
377 return data->folders["XDG_DOWNLOAD_DIR"];
378 #endif
379 }
380
381 std::string PlatformFolders::getMusicFolder() const {
382 #ifdef _WIN32
383 return GetKnownWindowsFolder(FOLDERID_Music, "Failed to find My Music folder");
384 #elif defined(__APPLE__)
385 return getHome()+"/Music";
386 #else
387 return data->folders["XDG_MUSIC_DIR"];
388 #endif
389 }
390
391 std::string PlatformFolders::getVideoFolder() const {
392 #ifdef _WIN32
393 return GetKnownWindowsFolder(FOLDERID_Videos, "Failed to find My Video folder");
394 #elif defined(__APPLE__)
395 return getHome()+"/Movies";
396 #else
397 return data->folders["XDG_VIDEOS_DIR"];
398 #endif
399 }
400
401 std::string PlatformFolders::getSaveGamesFolder1() const {
402 #ifdef _WIN32
403 //A dedicated Save Games folder was not introduced until Vista. For XP and older save games are most often saved in a normal folder named "My Games".
404 //Data that should not be user accessible should be placed under GetDataHome() instead
405 return GetKnownWindowsFolder(FOLDERID_Documents, "Failed to find My Documents folder")+"\\My Games";
406 #elif defined(__APPLE__)
407 return getHome()+"/Library/Application Support";
408 #else
409 return getDataHome();
410 #endif
411 }
412
413 std::string getDesktopFolder() {
414 return PlatformFolders().getDesktopFolder();
415 }
416
417 std::string getDocumentsFolder() {
418 return PlatformFolders().getDocumentsFolder();
419 }
420
421 std::string getDownloadFolder() {
422 return PlatformFolders().getDownloadFolder1();
423 }
424
425 std::string getDownloadFolder1() {
426 return getDownloadFolder();
427 }
428
429 std::string getPicturesFolder() {
430 return PlatformFolders().getPicturesFolder();
431 }
432
433 std::string getPublicFolder() {
434 return PlatformFolders().getPublicFolder();
435 }
436
437 std::string getMusicFolder() {
438 return PlatformFolders().getMusicFolder();
439 }
440
441 std::string getVideoFolder() {
442 return PlatformFolders().getVideoFolder();
443 }
444
445 std::string getSaveGamesFolder1() {
446 return PlatformFolders().getSaveGamesFolder1();
447 }
448
449 std::string getSaveGamesFolder2() {
450 #ifdef _WIN32
451 return GetKnownWindowsFolder(FOLDERID_SavedGames, "Failed to find Saved Games folder");
452 #else
453 return PlatformFolders().getSaveGamesFolder1();
454 #endif
455 }
456
457 } //namespace sago