]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
Print error when HOME is not set (#7376)
[dragonfireclient.git] / src / porting.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 /*
21         Random portability stuff
22
23         See comments in porting.h
24 */
25
26 #include "porting.h"
27
28 #if defined(__FreeBSD__)  || defined(__NetBSD__) || defined(__DragonFly__)
29         #include <sys/types.h>
30         #include <sys/sysctl.h>
31 #elif defined(_WIN32)
32         #include <windows.h>
33         #include <wincrypt.h>
34         #include <algorithm>
35         #include <shlwapi.h>
36 #endif
37 #if !defined(_WIN32)
38         #include <unistd.h>
39         #include <sys/utsname.h>
40 #endif
41 #if defined(__hpux)
42         #define _PSTAT64
43         #include <sys/pstat.h>
44 #endif
45
46 #include "config.h"
47 #include "debug.h"
48 #include "filesys.h"
49 #include "log.h"
50 #include "util/string.h"
51 #include "settings.h"
52 #include <list>
53
54 namespace porting
55 {
56
57 /*
58         Signal handler (grabs Ctrl-C on POSIX systems)
59 */
60
61 bool g_killed = false;
62
63 bool *signal_handler_killstatus()
64 {
65         return &g_killed;
66 }
67
68 #if !defined(_WIN32) // POSIX
69         #include <signal.h>
70
71 void signal_handler(int sig)
72 {
73         if (!g_killed) {
74                 if (sig == SIGINT) {
75                         dstream << "INFO: signal_handler(): "
76                                 << "Ctrl-C pressed, shutting down." << std::endl;
77                 } else if (sig == SIGTERM) {
78                         dstream << "INFO: signal_handler(): "
79                                 << "got SIGTERM, shutting down." << std::endl;
80                 }
81
82                 // Comment out for less clutter when testing scripts
83                 /*dstream << "INFO: sigint_handler(): "
84                                 << "Printing debug stacks" << std::endl;
85                 debug_stacks_print();*/
86
87                 g_killed = true;
88         } else {
89                 (void)signal(sig, SIG_DFL);
90         }
91 }
92
93 void signal_handler_init(void)
94 {
95         (void)signal(SIGINT, signal_handler);
96         (void)signal(SIGTERM, signal_handler);
97 }
98
99 #else // _WIN32
100         #include <signal.h>
101
102 BOOL WINAPI event_handler(DWORD sig)
103 {
104         switch (sig) {
105         case CTRL_C_EVENT:
106         case CTRL_CLOSE_EVENT:
107         case CTRL_LOGOFF_EVENT:
108         case CTRL_SHUTDOWN_EVENT:
109                 if (!g_killed) {
110                         dstream << "INFO: event_handler(): "
111                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
112                                 " shutting down." << std::endl;
113                         g_killed = true;
114                 } else {
115                         (void)signal(SIGINT, SIG_DFL);
116                 }
117                 break;
118         case CTRL_BREAK_EVENT:
119                 break;
120         }
121
122         return TRUE;
123 }
124
125 void signal_handler_init(void)
126 {
127         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
128 }
129
130 #endif
131
132
133 /*
134         Path mangler
135 */
136
137 // Default to RUN_IN_PLACE style relative paths
138 std::string path_share = "..";
139 std::string path_user = "..";
140 std::string path_locale = path_share + DIR_DELIM + "locale";
141 std::string path_cache = path_user + DIR_DELIM + "cache";
142
143
144 std::string getDataPath(const char *subpath)
145 {
146         return path_share + DIR_DELIM + subpath;
147 }
148
149 void pathRemoveFile(char *path, char delim)
150 {
151         // Remove filename and path delimiter
152         int i;
153         for(i = strlen(path)-1; i>=0; i--)
154         {
155                 if(path[i] == delim)
156                         break;
157         }
158         path[i] = 0;
159 }
160
161 bool detectMSVCBuildDir(const std::string &path)
162 {
163         const char *ends[] = {
164                 "bin\\Release",
165                 "bin\\MinSizeRel",
166                 "bin\\RelWithDebInfo",
167                 "bin\\Debug",
168                 "bin\\Build",
169                 NULL
170         };
171         return (!removeStringEnd(path, ends).empty());
172 }
173
174 std::string get_sysinfo()
175 {
176 #ifdef _WIN32
177
178         std::ostringstream oss;
179         LPSTR filePath = new char[MAX_PATH];
180         UINT blockSize;
181         VS_FIXEDFILEINFO *fixedFileInfo;
182
183         GetSystemDirectoryA(filePath, MAX_PATH);
184         PathAppendA(filePath, "kernel32.dll");
185
186         DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
187         LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
188
189         GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
190         VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
191
192         oss << "Windows/"
193                 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
194                 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
195                 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
196
197         #ifdef _WIN64
198         oss << "x86_64";
199         #else
200         BOOL is64 = FALSE;
201         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
202                 oss << "x86_64"; // 32-bit app on 64-bit OS
203         else
204                 oss << "x86";
205         #endif
206
207         delete[] lpVersionInfo;
208         delete[] filePath;
209
210         return oss.str();
211 #else
212         struct utsname osinfo;
213         uname(&osinfo);
214         return std::string(osinfo.sysname) + "/"
215                 + osinfo.release + " " + osinfo.machine;
216 #endif
217 }
218
219
220 bool getCurrentWorkingDir(char *buf, size_t len)
221 {
222 #ifdef _WIN32
223         DWORD ret = GetCurrentDirectory(len, buf);
224         return (ret != 0) && (ret <= len);
225 #else
226         return getcwd(buf, len);
227 #endif
228 }
229
230
231 bool getExecPathFromProcfs(char *buf, size_t buflen)
232 {
233 #ifndef _WIN32
234         buflen--;
235
236         ssize_t len;
237         if ((len = readlink("/proc/self/exe",     buf, buflen)) == -1 &&
238                 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
239                 (len = readlink("/proc/curproc/exe",  buf, buflen)) == -1)
240                 return false;
241
242         buf[len] = '\0';
243         return true;
244 #else
245         return false;
246 #endif
247 }
248
249 //// Windows
250 #if defined(_WIN32)
251
252 bool getCurrentExecPath(char *buf, size_t len)
253 {
254         DWORD written = GetModuleFileNameA(NULL, buf, len);
255         if (written == 0 || written == len)
256                 return false;
257
258         return true;
259 }
260
261
262 //// Linux
263 #elif defined(__linux__)
264
265 bool getCurrentExecPath(char *buf, size_t len)
266 {
267         if (!getExecPathFromProcfs(buf, len))
268                 return false;
269
270         return true;
271 }
272
273
274 //// Mac OS X, Darwin
275 #elif defined(__APPLE__)
276
277 bool getCurrentExecPath(char *buf, size_t len)
278 {
279         uint32_t lenb = (uint32_t)len;
280         if (_NSGetExecutablePath(buf, &lenb) == -1)
281                 return false;
282
283         return true;
284 }
285
286
287 //// FreeBSD, NetBSD, DragonFlyBSD
288 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
289
290 bool getCurrentExecPath(char *buf, size_t len)
291 {
292         // Try getting path from procfs first, since valgrind
293         // doesn't work with the latter
294         if (getExecPathFromProcfs(buf, len))
295                 return true;
296
297         int mib[4];
298
299         mib[0] = CTL_KERN;
300         mib[1] = KERN_PROC;
301         mib[2] = KERN_PROC_PATHNAME;
302         mib[3] = -1;
303
304         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
305                 return false;
306
307         return true;
308 }
309
310
311 //// Solaris
312 #elif defined(__sun) || defined(sun)
313
314 bool getCurrentExecPath(char *buf, size_t len)
315 {
316         const char *exec = getexecname();
317         if (exec == NULL)
318                 return false;
319
320         if (strlcpy(buf, exec, len) >= len)
321                 return false;
322
323         return true;
324 }
325
326
327 // HP-UX
328 #elif defined(__hpux)
329
330 bool getCurrentExecPath(char *buf, size_t len)
331 {
332         struct pst_status psts;
333
334         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
335                 return false;
336
337         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
338                 return false;
339
340         return true;
341 }
342
343
344 #else
345
346 bool getCurrentExecPath(char *buf, size_t len)
347 {
348         return false;
349 }
350
351 #endif
352
353
354 //// Non-Windows
355 #if !defined(_WIN32)
356
357 const char *getHomeOrFail()
358 {
359         const char *home = getenv("HOME");
360         // In rare cases the HOME environment variable may be unset
361         FATAL_ERROR_IF(!home,
362                 "Required environment variable HOME is not set");
363         return home;
364 }
365
366 #endif
367
368
369 //// Windows
370 #if defined(_WIN32)
371
372 bool setSystemPaths()
373 {
374         char buf[BUFSIZ];
375
376         // Find path of executable and set path_share relative to it
377         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
378                 "Failed to get current executable path");
379         pathRemoveFile(buf, '\\');
380
381         // Use ".\bin\.."
382         path_share = std::string(buf) + "\\..";
383
384         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
385         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
386         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
387
388         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
389         return true;
390 }
391
392
393 //// Linux
394 #elif defined(__linux__)
395
396 bool setSystemPaths()
397 {
398         char buf[BUFSIZ];
399
400         if (!getCurrentExecPath(buf, sizeof(buf))) {
401 #ifdef __ANDROID__
402                 errorstream << "Unable to read bindir "<< std::endl;
403 #else
404                 FATAL_ERROR("Unable to read bindir");
405 #endif
406                 return false;
407         }
408
409         pathRemoveFile(buf, '/');
410         std::string bindir(buf);
411
412         // Find share directory from these.
413         // It is identified by containing the subdirectory "builtin".
414         std::list<std::string> trylist;
415         std::string static_sharedir = STATIC_SHAREDIR;
416         if (!static_sharedir.empty() && static_sharedir != ".")
417                 trylist.push_back(static_sharedir);
418
419         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
420                 DIR_DELIM + PROJECT_NAME);
421         trylist.push_back(bindir + DIR_DELIM "..");
422
423 #ifdef __ANDROID__
424         trylist.push_back(path_user);
425 #endif
426
427         for (std::list<std::string>::const_iterator
428                         i = trylist.begin(); i != trylist.end(); ++i) {
429                 const std::string &trypath = *i;
430                 if (!fs::PathExists(trypath) ||
431                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
432                         warningstream << "system-wide share not found at \""
433                                         << trypath << "\""<< std::endl;
434                         continue;
435                 }
436
437                 // Warn if was not the first alternative
438                 if (i != trylist.begin()) {
439                         warningstream << "system-wide share found at \""
440                                         << trypath << "\"" << std::endl;
441                 }
442
443                 path_share = trypath;
444                 break;
445         }
446
447 #ifndef __ANDROID__
448         path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
449                 + PROJECT_NAME;
450 #endif
451
452         return true;
453 }
454
455
456 //// Mac OS X
457 #elif defined(__APPLE__)
458
459 bool setSystemPaths()
460 {
461         CFBundleRef main_bundle = CFBundleGetMainBundle();
462         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
463         char path[PATH_MAX];
464         if (CFURLGetFileSystemRepresentation(resources_url,
465                         TRUE, (UInt8 *)path, PATH_MAX)) {
466                 path_share = std::string(path);
467         } else {
468                 warningstream << "Could not determine bundle resource path" << std::endl;
469         }
470         CFRelease(resources_url);
471
472         path_user = std::string(getHomeOrFail())
473                 + "/Library/Application Support/"
474                 + PROJECT_NAME;
475         return true;
476 }
477
478
479 #else
480
481 bool setSystemPaths()
482 {
483         path_share = STATIC_SHAREDIR;
484         path_user  = std::string(getHomeOrFail()) + DIR_DELIM "."
485                 + lowercase(PROJECT_NAME);
486         return true;
487 }
488
489
490 #endif
491
492 void migrateCachePath()
493 {
494         const std::string local_cache_path = path_user + DIR_DELIM + "cache";
495
496         // Delete tmp folder if it exists (it only ever contained
497         // a temporary ogg file, which is no longer used).
498         if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
499                 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
500
501         // Bail if migration impossible
502         if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
503                         || fs::PathExists(path_cache)) {
504                 return;
505         }
506         if (!fs::Rename(local_cache_path, path_cache)) {
507                 errorstream << "Failed to migrate local cache path "
508                         "to system path!" << std::endl;
509         }
510 }
511
512 void initializePaths()
513 {
514 #if RUN_IN_PLACE
515         char buf[BUFSIZ];
516
517         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
518
519         bool success =
520                 getCurrentExecPath(buf, sizeof(buf)) ||
521                 getExecPathFromProcfs(buf, sizeof(buf));
522
523         if (success) {
524                 pathRemoveFile(buf, DIR_DELIM_CHAR);
525                 std::string execpath(buf);
526
527                 path_share = execpath + DIR_DELIM "..";
528                 path_user  = execpath + DIR_DELIM "..";
529
530                 if (detectMSVCBuildDir(execpath)) {
531                         path_share += DIR_DELIM "..";
532                         path_user  += DIR_DELIM "..";
533                 }
534         } else {
535                 errorstream << "Failed to get paths by executable location, "
536                         "trying cwd" << std::endl;
537
538                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
539                         FATAL_ERROR("Ran out of methods to get paths");
540
541                 size_t cwdlen = strlen(buf);
542                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
543                         cwdlen--;
544                         buf[cwdlen] = '\0';
545                 }
546
547                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
548                         pathRemoveFile(buf, DIR_DELIM_CHAR);
549
550                 std::string execpath(buf);
551
552                 path_share = execpath;
553                 path_user  = execpath;
554         }
555         path_cache = path_user + DIR_DELIM + "cache";
556 #else
557         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
558
559         if (!setSystemPaths())
560                 errorstream << "Failed to get one or more system-wide path" << std::endl;
561
562         // Initialize path_cache
563         // First try $XDG_CACHE_HOME/PROJECT_NAME
564         const char *cache_dir = getenv("XDG_CACHE_HOME");
565         const char *home_dir = getenv("HOME");
566         if (cache_dir) {
567                 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
568         } else if (home_dir) {
569                 // Then try $HOME/.cache/PROJECT_NAME
570                 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
571                         + DIR_DELIM + PROJECT_NAME;
572         } else {
573                 // If neither works, use $PATH_USER/cache
574                 path_cache = path_user + DIR_DELIM + "cache";
575         }
576         // Migrate cache folder to new location if possible
577         migrateCachePath();
578 #endif
579
580         infostream << "Detected share path: " << path_share << std::endl;
581         infostream << "Detected user path: " << path_user << std::endl;
582         infostream << "Detected cache path: " << path_cache << std::endl;
583
584 #if USE_GETTEXT
585         bool found_localedir = false;
586 #  ifdef STATIC_LOCALEDIR
587         if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
588                 found_localedir = true;
589                 path_locale = STATIC_LOCALEDIR;
590                 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
591         } else {
592                 path_locale = getDataPath("locale");
593                 if (fs::PathExists(path_locale)) {
594                         found_localedir = true;
595                         infostream << "Using in-place locale directory " << path_locale
596                                 << " even though a static one was provided "
597                                 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
598                 }
599         }
600 #  else
601         path_locale = getDataPath("locale");
602         if (fs::PathExists(path_locale)) {
603                 found_localedir = true;
604         }
605 #  endif
606         if (!found_localedir) {
607                 warningstream << "Couldn't find a locale directory!" << std::endl;
608         }
609 #endif  // USE_GETTEXT
610 }
611
612 ////
613 //// OS-specific Secure Random
614 ////
615
616 #ifdef WIN32
617
618 bool secure_rand_fill_buf(void *buf, size_t len)
619 {
620         HCRYPTPROV wctx;
621
622         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
623                 return false;
624
625         CryptGenRandom(wctx, len, (BYTE *)buf);
626         CryptReleaseContext(wctx, 0);
627         return true;
628 }
629
630 #else
631
632 bool secure_rand_fill_buf(void *buf, size_t len)
633 {
634         // N.B.  This function checks *only* for /dev/urandom, because on most
635         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
636         // is exceptionally uncommon for there to be a situation where /dev/random
637         // exists but /dev/urandom does not.  This guesswork is necessary since
638         // random devices are not covered by any POSIX standard...
639         FILE *fp = fopen("/dev/urandom", "rb");
640         if (!fp)
641                 return false;
642
643         bool success = fread(buf, len, 1, fp) == 1;
644
645         fclose(fp);
646         return success;
647 }
648
649 #endif
650
651 void attachOrCreateConsole()
652 {
653 #ifdef _WIN32
654         static bool consoleAllocated = false;
655         const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
656         if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
657                 freopen("CONOUT$", "w", stdout);
658                 freopen("CONOUT$", "w", stderr);
659                 consoleAllocated = true;
660         }
661 #endif
662 }
663
664 // Load performance counter frequency only once at startup
665 #ifdef _WIN32
666
667 inline double get_perf_freq()
668 {
669         LARGE_INTEGER freq;
670         QueryPerformanceFrequency(&freq);
671         return freq.QuadPart;
672 }
673
674 double perf_freq = get_perf_freq();
675
676 #endif
677
678 } //namespace porting