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