autofly: small fix
[waspsaliva.git] / src / porting.cpp
blobd902d3737048d2b49d8025351a9f24c85e34d1b8
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
21 Random portability stuff
23 See comments in porting.h
26 #include "porting.h"
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
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>
68 namespace porting
72 Signal handler (grabs Ctrl-C on POSIX systems)
75 bool g_killed = false;
77 bool *signal_handler_killstatus()
79 return &g_killed;
82 #if !defined(_WIN32) // POSIX
83 #include <signal.h>
85 void signal_handler(int sig)
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;
96 // Comment out for less clutter when testing scripts
97 /*dstream << "INFO: sigint_handler(): "
98 << "Printing debug stacks" << std::endl;
99 debug_stacks_print();*/
101 g_killed = true;
102 } else {
103 (void)signal(sig, SIG_DFL);
107 void signal_handler_init(void)
109 (void)signal(SIGINT, signal_handler);
110 (void)signal(SIGTERM, signal_handler);
113 #else // _WIN32
114 #include <signal.h>
116 BOOL WINAPI event_handler(DWORD sig)
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);
131 break;
132 case CTRL_BREAK_EVENT:
133 break;
136 return TRUE;
139 void signal_handler_init(void)
141 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
144 #endif
148 Path mangler
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";
158 std::string getDataPath(const char *subpath)
160 return path_share + DIR_DELIM + subpath;
163 void pathRemoveFile(char *path, char delim)
165 // Remove filename and path delimiter
166 int i;
167 for(i = strlen(path)-1; i>=0; i--)
169 if(path[i] == delim)
170 break;
172 path[i] = 0;
175 bool detectMSVCBuildDir(const std::string &path)
177 const char *ends[] = {
178 "bin\\Release",
179 "bin\\MinSizeRel",
180 "bin\\RelWithDebInfo",
181 "bin\\Debug",
182 "bin\\Build",
183 NULL
185 return (!removeStringEnd(path, ends).empty());
188 std::string get_sysinfo()
190 #ifdef _WIN32
192 std::ostringstream oss;
193 LPSTR filePath = new char[MAX_PATH];
194 UINT blockSize;
195 VS_FIXEDFILEINFO *fixedFileInfo;
197 GetSystemDirectoryA(filePath, MAX_PATH);
198 PathAppendA(filePath, "kernel32.dll");
200 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
201 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
203 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
204 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
206 oss << "Windows/"
207 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
208 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
209 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
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
221 delete[] lpVersionInfo;
222 delete[] filePath;
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
234 bool getCurrentWorkingDir(char *buf, size_t len)
236 #ifdef _WIN32
237 DWORD ret = GetCurrentDirectory(len, buf);
238 return (ret != 0) && (ret <= len);
239 #else
240 return getcwd(buf, len);
241 #endif
245 bool getExecPathFromProcfs(char *buf, size_t buflen)
247 #ifndef _WIN32
248 buflen--;
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;
256 buf[len] = '\0';
257 return true;
258 #else
259 return false;
260 #endif
263 //// Windows
264 #if defined(_WIN32)
266 bool getCurrentExecPath(char *buf, size_t len)
268 DWORD written = GetModuleFileNameA(NULL, buf, len);
269 if (written == 0 || written == len)
270 return false;
272 return true;
276 //// Linux
277 #elif defined(__linux__)
279 bool getCurrentExecPath(char *buf, size_t len)
281 if (!getExecPathFromProcfs(buf, len))
282 return false;
284 return true;
288 //// Mac OS X, Darwin
289 #elif defined(__APPLE__)
291 bool getCurrentExecPath(char *buf, size_t len)
293 uint32_t lenb = (uint32_t)len;
294 if (_NSGetExecutablePath(buf, &lenb) == -1)
295 return false;
297 return true;
301 //// FreeBSD, NetBSD, DragonFlyBSD
302 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
304 bool getCurrentExecPath(char *buf, size_t len)
306 // Try getting path from procfs first, since valgrind
307 // doesn't work with the latter
308 if (getExecPathFromProcfs(buf, len))
309 return true;
311 int mib[4];
313 mib[0] = CTL_KERN;
314 mib[1] = KERN_PROC;
315 mib[2] = KERN_PROC_PATHNAME;
316 mib[3] = -1;
318 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
319 return false;
321 return true;
325 //// Solaris
326 #elif defined(__sun) || defined(sun)
328 bool getCurrentExecPath(char *buf, size_t len)
330 const char *exec = getexecname();
331 if (exec == NULL)
332 return false;
334 if (strlcpy(buf, exec, len) >= len)
335 return false;
337 return true;
341 // HP-UX
342 #elif defined(__hpux)
344 bool getCurrentExecPath(char *buf, size_t len)
346 struct pst_status psts;
348 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
349 return false;
351 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
352 return false;
354 return true;
358 #else
360 bool getCurrentExecPath(char *buf, size_t len)
362 return false;
365 #endif
368 //// Non-Windows
369 #if !defined(_WIN32)
371 const char *getHomeOrFail()
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;
380 #endif
383 //// Windows
384 #if defined(_WIN32)
386 bool setSystemPaths()
388 char buf[BUFSIZ];
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, '\\');
395 std::string exepath(buf);
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 "..";
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");
409 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
410 return true;
414 //// Linux
415 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
417 bool setSystemPaths()
419 char buf[BUFSIZ];
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;
430 pathRemoveFile(buf, '/');
431 std::string bindir(buf);
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);
440 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
441 DIR_DELIM + PROJECT_NAME);
442 trylist.push_back(bindir + DIR_DELIM "..");
444 #ifdef __ANDROID__
445 trylist.push_back(path_user);
446 #endif
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;
458 // Warn if was not the first alternative
459 if (i != trylist.begin()) {
460 warningstream << "system-wide share found at \""
461 << trypath << "\"" << std::endl;
464 path_share = trypath;
465 break;
468 #ifndef __ANDROID__
469 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
470 + PROJECT_NAME;
471 #endif
473 return true;
477 //// Mac OS X
478 #elif defined(__APPLE__)
480 bool setSystemPaths()
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;
491 CFRelease(resources_url);
493 path_user = std::string(getHomeOrFail())
494 + "/Library/Application Support/"
495 + PROJECT_NAME;
496 return true;
500 #else
502 bool setSystemPaths()
504 path_share = STATIC_SHAREDIR;
505 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
506 + lowercase(PROJECT_NAME);
507 return true;
511 #endif
513 void migrateCachePath()
515 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
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");
522 // Bail if migration impossible
523 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
524 || fs::PathExists(path_cache)) {
525 return;
527 if (!fs::Rename(local_cache_path, path_cache)) {
528 errorstream << "Failed to migrate local cache path "
529 "to system path!" << std::endl;
533 void initializePaths()
535 #if RUN_IN_PLACE
536 char buf[BUFSIZ];
538 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
540 bool success =
541 getCurrentExecPath(buf, sizeof(buf)) ||
542 getExecPathFromProcfs(buf, sizeof(buf));
544 if (success) {
545 pathRemoveFile(buf, DIR_DELIM_CHAR);
546 std::string execpath(buf);
548 path_share = execpath + DIR_DELIM "..";
549 path_user = execpath + DIR_DELIM "..";
551 if (detectMSVCBuildDir(execpath)) {
552 path_share += DIR_DELIM "..";
553 path_user += DIR_DELIM "..";
555 } else {
556 errorstream << "Failed to get paths by executable location, "
557 "trying cwd" << std::endl;
559 if (!getCurrentWorkingDir(buf, sizeof(buf)))
560 FATAL_ERROR("Ran out of methods to get paths");
562 size_t cwdlen = strlen(buf);
563 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
564 cwdlen--;
565 buf[cwdlen] = '\0';
568 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
569 pathRemoveFile(buf, DIR_DELIM_CHAR);
571 std::string execpath(buf);
573 path_share = execpath;
574 path_user = execpath;
576 path_cache = path_user + DIR_DELIM + "cache";
577 #else
578 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
580 if (!setSystemPaths())
581 errorstream << "Failed to get one or more system-wide path" << std::endl;
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";
601 // Migrate cache folder to new location if possible
602 migrateCachePath();
603 # endif // _WIN32
604 #endif // RUN_IN_PLACE
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;
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;
626 # else
627 path_locale = getDataPath("locale");
628 if (fs::PathExists(path_locale)) {
629 found_localedir = true;
631 # endif
632 if (!found_localedir) {
633 warningstream << "Couldn't find a locale directory!" << std::endl;
635 #endif // USE_GETTEXT
638 ////
639 //// OS-specific Secure Random
640 ////
642 #ifdef WIN32
644 bool secure_rand_fill_buf(void *buf, size_t len)
646 HCRYPTPROV wctx;
648 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
649 return false;
651 CryptGenRandom(wctx, len, (BYTE *)buf);
652 CryptReleaseContext(wctx, 0);
653 return true;
656 #else
658 bool secure_rand_fill_buf(void *buf, size_t len)
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;
669 bool success = fread(buf, len, 1, fp) == 1;
671 fclose(fp);
672 return success;
675 #endif
677 void attachOrCreateConsole()
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;
687 #endif
690 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
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;
712 bool openURL(const std::string &url)
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;
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
735 // Load performance counter frequency only once at startup
736 #ifdef _WIN32
738 inline double get_perf_freq()
740 LARGE_INTEGER freq;
741 QueryPerformanceFrequency(&freq);
742 return freq.QuadPart;
745 double perf_freq = get_perf_freq();
747 #endif
749 } //namespace porting