]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
29af62f7d6347a18e37c9ad4e707bb8fb73ee23f
[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         #include <shellapi.h>
37 #endif
38 #if !defined(_WIN32)
39         #include <unistd.h>
40         #include <sys/utsname.h>
41         #if !defined(__ANDROID__)
42                 #include <spawn.h>
43         #endif
44 #endif
45 #if defined(__hpux)
46         #define _PSTAT64
47         #include <sys/pstat.h>
48 #endif
49 #if defined(__ANDROID__)
50         #include "porting_android.h"
51 #endif
52 #if defined(__APPLE__)
53         // For _NSGetEnviron()
54         // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
55         #include <crt_externs.h>
56 #endif
57
58 #include "config.h"
59 #include "debug.h"
60 #include "filesys.h"
61 #include "log.h"
62 #include "util/string.h"
63 #include <list>
64 #include <cstdarg>
65 #include <cstdio>
66
67 namespace porting
68 {
69
70 /*
71         Signal handler (grabs Ctrl-C on POSIX systems)
72 */
73
74 bool g_killed = false;
75
76 bool *signal_handler_killstatus()
77 {
78         return &g_killed;
79 }
80
81 #if !defined(_WIN32) // POSIX
82         #include <signal.h>
83
84 void signal_handler(int sig)
85 {
86         if (!g_killed) {
87                 if (sig == SIGINT) {
88                         dstream << "INFO: signal_handler(): "
89                                 << "Ctrl-C pressed, shutting down." << std::endl;
90                 } else if (sig == SIGTERM) {
91                         dstream << "INFO: signal_handler(): "
92                                 << "got SIGTERM, shutting down." << std::endl;
93                 }
94
95                 // Comment out for less clutter when testing scripts
96                 /*dstream << "INFO: sigint_handler(): "
97                                 << "Printing debug stacks" << std::endl;
98                 debug_stacks_print();*/
99
100                 g_killed = true;
101         } else {
102                 (void)signal(sig, SIG_DFL);
103         }
104 }
105
106 void signal_handler_init(void)
107 {
108         (void)signal(SIGINT, signal_handler);
109         (void)signal(SIGTERM, signal_handler);
110 }
111
112 #else // _WIN32
113         #include <signal.h>
114
115 BOOL WINAPI event_handler(DWORD sig)
116 {
117         switch (sig) {
118         case CTRL_C_EVENT:
119         case CTRL_CLOSE_EVENT:
120         case CTRL_LOGOFF_EVENT:
121         case CTRL_SHUTDOWN_EVENT:
122                 if (!g_killed) {
123                         dstream << "INFO: event_handler(): "
124                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
125                                 " shutting down." << std::endl;
126                         g_killed = true;
127                 } else {
128                         (void)signal(SIGINT, SIG_DFL);
129                 }
130                 break;
131         case CTRL_BREAK_EVENT:
132                 break;
133         }
134
135         return TRUE;
136 }
137
138 void signal_handler_init(void)
139 {
140         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
141 }
142
143 #endif
144
145
146 /*
147         Path mangler
148 */
149
150 // Default to RUN_IN_PLACE style relative paths
151 std::string path_share = "..";
152 std::string path_user = "..";
153 std::string path_locale = path_share + DIR_DELIM + "locale";
154 std::string path_cache = path_user + DIR_DELIM + "cache";
155
156
157 std::string getDataPath(const char *subpath)
158 {
159         return path_share + DIR_DELIM + subpath;
160 }
161
162 void pathRemoveFile(char *path, char delim)
163 {
164         // Remove filename and path delimiter
165         int i;
166         for(i = strlen(path)-1; i>=0; i--)
167         {
168                 if(path[i] == delim)
169                         break;
170         }
171         path[i] = 0;
172 }
173
174 bool detectMSVCBuildDir(const std::string &path)
175 {
176         const char *ends[] = {
177                 "bin\\Release",
178                 "bin\\MinSizeRel",
179                 "bin\\RelWithDebInfo",
180                 "bin\\Debug",
181                 "bin\\Build",
182                 NULL
183         };
184         return (!removeStringEnd(path, ends).empty());
185 }
186
187 std::string get_sysinfo()
188 {
189 #ifdef _WIN32
190
191         std::ostringstream oss;
192         LPSTR filePath = new char[MAX_PATH];
193         UINT blockSize;
194         VS_FIXEDFILEINFO *fixedFileInfo;
195
196         GetSystemDirectoryA(filePath, MAX_PATH);
197         PathAppendA(filePath, "kernel32.dll");
198
199         DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
200         LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
201
202         GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
203         VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
204
205         oss << "Windows/"
206                 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
207                 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
208                 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
209
210         #ifdef _WIN64
211         oss << "x86_64";
212         #else
213         BOOL is64 = FALSE;
214         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
215                 oss << "x86_64"; // 32-bit app on 64-bit OS
216         else
217                 oss << "x86";
218         #endif
219
220         delete[] lpVersionInfo;
221         delete[] filePath;
222
223         return oss.str();
224 #else
225         struct utsname osinfo;
226         uname(&osinfo);
227         return std::string(osinfo.sysname) + "/"
228                 + osinfo.release + " " + osinfo.machine;
229 #endif
230 }
231
232
233 bool getCurrentWorkingDir(char *buf, size_t len)
234 {
235 #ifdef _WIN32
236         DWORD ret = GetCurrentDirectory(len, buf);
237         return (ret != 0) && (ret <= len);
238 #else
239         return getcwd(buf, len);
240 #endif
241 }
242
243
244 bool getExecPathFromProcfs(char *buf, size_t buflen)
245 {
246 #ifndef _WIN32
247         buflen--;
248
249         ssize_t len;
250         if ((len = readlink("/proc/self/exe",     buf, buflen)) == -1 &&
251                 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
252                 (len = readlink("/proc/curproc/exe",  buf, buflen)) == -1)
253                 return false;
254
255         buf[len] = '\0';
256         return true;
257 #else
258         return false;
259 #endif
260 }
261
262 //// Windows
263 #if defined(_WIN32)
264
265 bool getCurrentExecPath(char *buf, size_t len)
266 {
267         DWORD written = GetModuleFileNameA(NULL, buf, len);
268         if (written == 0 || written == len)
269                 return false;
270
271         return true;
272 }
273
274
275 //// Linux
276 #elif defined(__linux__)
277
278 bool getCurrentExecPath(char *buf, size_t len)
279 {
280         if (!getExecPathFromProcfs(buf, len))
281                 return false;
282
283         return true;
284 }
285
286
287 //// Mac OS X, Darwin
288 #elif defined(__APPLE__)
289
290 bool getCurrentExecPath(char *buf, size_t len)
291 {
292         uint32_t lenb = (uint32_t)len;
293         if (_NSGetExecutablePath(buf, &lenb) == -1)
294                 return false;
295
296         return true;
297 }
298
299
300 //// FreeBSD, NetBSD, DragonFlyBSD
301 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
302
303 bool getCurrentExecPath(char *buf, size_t len)
304 {
305         // Try getting path from procfs first, since valgrind
306         // doesn't work with the latter
307         if (getExecPathFromProcfs(buf, len))
308                 return true;
309
310         int mib[4];
311
312         mib[0] = CTL_KERN;
313         mib[1] = KERN_PROC;
314         mib[2] = KERN_PROC_PATHNAME;
315         mib[3] = -1;
316
317         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
318                 return false;
319
320         return true;
321 }
322
323
324 //// Solaris
325 #elif defined(__sun) || defined(sun)
326
327 bool getCurrentExecPath(char *buf, size_t len)
328 {
329         const char *exec = getexecname();
330         if (exec == NULL)
331                 return false;
332
333         if (strlcpy(buf, exec, len) >= len)
334                 return false;
335
336         return true;
337 }
338
339
340 // HP-UX
341 #elif defined(__hpux)
342
343 bool getCurrentExecPath(char *buf, size_t len)
344 {
345         struct pst_status psts;
346
347         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
348                 return false;
349
350         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
351                 return false;
352
353         return true;
354 }
355
356
357 #else
358
359 bool getCurrentExecPath(char *buf, size_t len)
360 {
361         return false;
362 }
363
364 #endif
365
366
367 //// Non-Windows
368 #if !defined(_WIN32)
369
370 const char *getHomeOrFail()
371 {
372         const char *home = getenv("HOME");
373         // In rare cases the HOME environment variable may be unset
374         FATAL_ERROR_IF(!home,
375                 "Required environment variable HOME is not set");
376         return home;
377 }
378
379 #endif
380
381
382 //// Windows
383 #if defined(_WIN32)
384
385 bool setSystemPaths()
386 {
387         char buf[BUFSIZ];
388
389         // Find path of executable and set path_share relative to it
390         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
391                 "Failed to get current executable path");
392         pathRemoveFile(buf, '\\');
393
394         std::string exepath(buf);
395
396         // Use ".\bin\.."
397         path_share = exepath + "\\..";
398         if (detectMSVCBuildDir(exepath)) {
399                 // The msvc build dir schould normaly not be present if properly installed,
400                 // but its usefull for debugging.
401                 path_share += DIR_DELIM "..";
402         }
403
404         // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
405         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
406         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
407
408         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
409         return true;
410 }
411
412
413 //// Linux
414 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
415
416 bool setSystemPaths()
417 {
418         char buf[BUFSIZ];
419
420         if (!getCurrentExecPath(buf, sizeof(buf))) {
421 #ifdef __ANDROID__
422                 errorstream << "Unable to read bindir "<< std::endl;
423 #else
424                 FATAL_ERROR("Unable to read bindir");
425 #endif
426                 return false;
427         }
428
429         pathRemoveFile(buf, '/');
430         std::string bindir(buf);
431
432         // Find share directory from these.
433         // It is identified by containing the subdirectory "builtin".
434         std::list<std::string> trylist;
435         std::string static_sharedir = STATIC_SHAREDIR;
436         if (!static_sharedir.empty() && static_sharedir != ".")
437                 trylist.push_back(static_sharedir);
438
439         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
440                 DIR_DELIM + PROJECT_NAME);
441         trylist.push_back(bindir + DIR_DELIM "..");
442
443 #ifdef __ANDROID__
444         trylist.push_back(path_user);
445 #endif
446
447         for (std::list<std::string>::const_iterator
448                         i = trylist.begin(); i != trylist.end(); ++i) {
449                 const std::string &trypath = *i;
450                 if (!fs::PathExists(trypath) ||
451                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
452                         warningstream << "system-wide share not found at \""
453                                         << trypath << "\""<< std::endl;
454                         continue;
455                 }
456
457                 // Warn if was not the first alternative
458                 if (i != trylist.begin()) {
459                         warningstream << "system-wide share found at \""
460                                         << trypath << "\"" << std::endl;
461                 }
462
463                 path_share = trypath;
464                 break;
465         }
466
467 #ifndef __ANDROID__
468         path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
469                 + PROJECT_NAME;
470 #endif
471
472         return true;
473 }
474
475
476 //// Mac OS X
477 #elif defined(__APPLE__)
478
479 bool setSystemPaths()
480 {
481         CFBundleRef main_bundle = CFBundleGetMainBundle();
482         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
483         char path[PATH_MAX];
484         if (CFURLGetFileSystemRepresentation(resources_url,
485                         TRUE, (UInt8 *)path, PATH_MAX)) {
486                 path_share = std::string(path);
487         } else {
488                 warningstream << "Could not determine bundle resource path" << std::endl;
489         }
490         CFRelease(resources_url);
491
492         path_user = std::string(getHomeOrFail())
493                 + "/Library/Application Support/"
494                 + PROJECT_NAME;
495         return true;
496 }
497
498
499 #else
500
501 bool setSystemPaths()
502 {
503         path_share = STATIC_SHAREDIR;
504         path_user  = std::string(getHomeOrFail()) + DIR_DELIM "."
505                 + lowercase(PROJECT_NAME);
506         return true;
507 }
508
509
510 #endif
511
512 void migrateCachePath()
513 {
514         const std::string local_cache_path = path_user + DIR_DELIM + "cache";
515
516         // Delete tmp folder if it exists (it only ever contained
517         // a temporary ogg file, which is no longer used).
518         if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
519                 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
520
521         // Bail if migration impossible
522         if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
523                         || fs::PathExists(path_cache)) {
524                 return;
525         }
526         if (!fs::Rename(local_cache_path, path_cache)) {
527                 errorstream << "Failed to migrate local cache path "
528                         "to system path!" << std::endl;
529         }
530 }
531
532 void initializePaths()
533 {
534 #if RUN_IN_PLACE
535         char buf[BUFSIZ];
536
537         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
538
539         bool success =
540                 getCurrentExecPath(buf, sizeof(buf)) ||
541                 getExecPathFromProcfs(buf, sizeof(buf));
542
543         if (success) {
544                 pathRemoveFile(buf, DIR_DELIM_CHAR);
545                 std::string execpath(buf);
546
547                 path_share = execpath + DIR_DELIM "..";
548                 path_user  = execpath + DIR_DELIM "..";
549
550                 if (detectMSVCBuildDir(execpath)) {
551                         path_share += DIR_DELIM "..";
552                         path_user  += DIR_DELIM "..";
553                 }
554         } else {
555                 errorstream << "Failed to get paths by executable location, "
556                         "trying cwd" << std::endl;
557
558                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
559                         FATAL_ERROR("Ran out of methods to get paths");
560
561                 size_t cwdlen = strlen(buf);
562                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
563                         cwdlen--;
564                         buf[cwdlen] = '\0';
565                 }
566
567                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
568                         pathRemoveFile(buf, DIR_DELIM_CHAR);
569
570                 std::string execpath(buf);
571
572                 path_share = execpath;
573                 path_user  = execpath;
574         }
575         path_cache = path_user + DIR_DELIM + "cache";
576 #else
577         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
578
579         if (!setSystemPaths())
580                 errorstream << "Failed to get one or more system-wide path" << std::endl;
581
582
583 #  ifdef _WIN32
584         path_cache = path_user + DIR_DELIM + "cache";
585 #  else
586         // Initialize path_cache
587         // First try $XDG_CACHE_HOME/PROJECT_NAME
588         const char *cache_dir = getenv("XDG_CACHE_HOME");
589         const char *home_dir = getenv("HOME");
590         if (cache_dir) {
591                 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
592         } else if (home_dir) {
593                 // Then try $HOME/.cache/PROJECT_NAME
594                 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
595                         + DIR_DELIM + PROJECT_NAME;
596         } else {
597                 // If neither works, use $PATH_USER/cache
598                 path_cache = path_user + DIR_DELIM + "cache";
599         }
600         // Migrate cache folder to new location if possible
601         migrateCachePath();
602 #  endif // _WIN32
603 #endif // RUN_IN_PLACE
604
605         infostream << "Detected share path: " << path_share << std::endl;
606         infostream << "Detected user path: " << path_user << std::endl;
607         infostream << "Detected cache path: " << path_cache << std::endl;
608
609 #if USE_GETTEXT
610         bool found_localedir = false;
611 #  ifdef STATIC_LOCALEDIR
612         /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
613          * doesn't necessarily contain our locale files, so check data path first. */
614         path_locale = getDataPath("locale");
615         if (fs::PathExists(path_locale)) {
616                 found_localedir = true;
617                 infostream << "Using in-place locale directory " << path_locale
618                         << " even though a static one was provided." << std::endl;
619         } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
620                 found_localedir = true;
621                 path_locale = STATIC_LOCALEDIR;
622                 infostream << "Using static locale directory " << STATIC_LOCALEDIR
623                         << std::endl;
624         }
625 #  else
626         path_locale = getDataPath("locale");
627         if (fs::PathExists(path_locale)) {
628                 found_localedir = true;
629         }
630 #  endif
631         if (!found_localedir) {
632                 warningstream << "Couldn't find a locale directory!" << std::endl;
633         }
634 #endif  // USE_GETTEXT
635 }
636
637 ////
638 //// OS-specific Secure Random
639 ////
640
641 #ifdef WIN32
642
643 bool secure_rand_fill_buf(void *buf, size_t len)
644 {
645         HCRYPTPROV wctx;
646
647         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
648                 return false;
649
650         CryptGenRandom(wctx, len, (BYTE *)buf);
651         CryptReleaseContext(wctx, 0);
652         return true;
653 }
654
655 #else
656
657 bool secure_rand_fill_buf(void *buf, size_t len)
658 {
659         // N.B.  This function checks *only* for /dev/urandom, because on most
660         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
661         // is exceptionally uncommon for there to be a situation where /dev/random
662         // exists but /dev/urandom does not.  This guesswork is necessary since
663         // random devices are not covered by any POSIX standard...
664         FILE *fp = fopen("/dev/urandom", "rb");
665         if (!fp)
666                 return false;
667
668         bool success = fread(buf, len, 1, fp) == 1;
669
670         fclose(fp);
671         return success;
672 }
673
674 #endif
675
676 void attachOrCreateConsole()
677 {
678 #ifdef _WIN32
679         static bool consoleAllocated = false;
680         const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
681         if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
682                 freopen("CONOUT$", "w", stdout);
683                 freopen("CONOUT$", "w", stderr);
684                 consoleAllocated = true;
685         }
686 #endif
687 }
688
689 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
690 {
691         // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
692         //  Many of the MSVC / Windows printf-style functions do not support positional
693         //  arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
694         //  platforms, but defer to _vsprintf_p on MSVC / Windows.
695         // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
696         //  _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
697         //  above FFmpeg link).
698         va_list args;
699         va_start(args, fmt);
700 #ifndef _MSC_VER
701         int c = vsnprintf(buf, buf_size, fmt, args);
702 #else  // _MSC_VER
703         int c = _vsprintf_p(buf, buf_size, fmt, args);
704         if (c == -1)
705                 c = _vscprintf_p(fmt, args);
706 #endif // _MSC_VER
707         va_end(args);
708         return c;
709 }
710
711 bool openURL(const std::string &url)
712 {
713         if ((url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") ||
714                         url.find_first_of("\r\n") != std::string::npos) {
715                 errorstream << "Invalid url: " << url << std::endl;
716                 return false;
717         }
718
719 #if defined(_WIN32)
720         return (intptr_t)ShellExecuteA(NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
721 #elif defined(__ANDROID__)
722         openURLAndroid(url);
723         return true;
724 #elif defined(__APPLE__)
725         const char *argv[] = {"open", url.c_str(), NULL};
726         return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv,
727                 (*_NSGetEnviron())) == 0;
728 #else
729         const char *argv[] = {"xdg-open", url.c_str(), NULL};
730         return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
731 #endif
732 }
733
734 // Load performance counter frequency only once at startup
735 #ifdef _WIN32
736
737 inline double get_perf_freq()
738 {
739         LARGE_INTEGER freq;
740         QueryPerformanceFrequency(&freq);
741         return freq.QuadPart;
742 }
743
744 double perf_freq = get_perf_freq();
745
746 #endif
747
748 } //namespace porting