]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
Make Lint Happy
[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 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."
127                                 << std::endl;
128                         g_killed = true;
129                 } else {
130                         (void)signal(SIGINT, SIG_DFL);
131                 }
132                 break;
133         case CTRL_BREAK_EVENT:
134                 break;
135         }
136
137         return TRUE;
138 }
139
140 void signal_handler_init(void)
141 {
142         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
143 }
144
145 #endif
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 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                 if (path[i] == delim)
168                         break;
169         }
170         path[i] = 0;
171 }
172
173 bool detectMSVCBuildDir(const std::string &path)
174 {
175         const char *ends[] = {"bin\\Release", "bin\\MinSizeRel", "bin\\RelWithDebInfo",
176                         "bin\\Debug", "bin\\Build", NULL};
177         return (!removeStringEnd(path, ends).empty());
178 }
179
180 std::string get_sysinfo()
181 {
182 #ifdef _WIN32
183
184         std::ostringstream oss;
185         LPSTR filePath = new char[MAX_PATH];
186         UINT blockSize;
187         VS_FIXEDFILEINFO *fixedFileInfo;
188
189         GetSystemDirectoryA(filePath, MAX_PATH);
190         PathAppendA(filePath, "kernel32.dll");
191
192         DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
193         LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
194
195         GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
196         VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
197
198         oss << "Windows/" << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
199             << LOWORD(fixedFileInfo->dwProductVersionMS) << '.'               // Minor
200             << HIWORD(fixedFileInfo->dwProductVersionLS) << ' ';              // Build
201
202 #ifdef _WIN64
203         oss << "x86_64";
204 #else
205         BOOL is64 = FALSE;
206         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
207                 oss << "x86_64"; // 32-bit app on 64-bit OS
208         else
209                 oss << "x86";
210 #endif
211
212         delete[] lpVersionInfo;
213         delete[] filePath;
214
215         return oss.str();
216 #else
217         struct utsname osinfo;
218         uname(&osinfo);
219         return std::string(osinfo.sysname) + "/" + osinfo.release + " " + osinfo.machine;
220 #endif
221 }
222
223 bool getCurrentWorkingDir(char *buf, size_t len)
224 {
225 #ifdef _WIN32
226         DWORD ret = GetCurrentDirectory(len, buf);
227         return (ret != 0) && (ret <= len);
228 #else
229         return getcwd(buf, len);
230 #endif
231 }
232
233 bool getExecPathFromProcfs(char *buf, size_t buflen)
234 {
235 #ifndef _WIN32
236         buflen--;
237
238         ssize_t len;
239         if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
240                         (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
241                         (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
242                 return false;
243
244         buf[len] = '\0';
245         return true;
246 #else
247         return false;
248 #endif
249 }
250
251 //// Windows
252 #if defined(_WIN32)
253
254 bool getCurrentExecPath(char *buf, size_t len)
255 {
256         DWORD written = GetModuleFileNameA(NULL, buf, len);
257         if (written == 0 || written == len)
258                 return false;
259
260         return true;
261 }
262
263 //// Linux
264 #elif defined(__linux__)
265
266 bool getCurrentExecPath(char *buf, size_t len)
267 {
268         if (!getExecPathFromProcfs(buf, len))
269                 return false;
270
271         return true;
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 //// FreeBSD, NetBSD, DragonFlyBSD
287 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
288
289 bool getCurrentExecPath(char *buf, size_t len)
290 {
291         // Try getting path from procfs first, since valgrind
292         // doesn't work with the latter
293         if (getExecPathFromProcfs(buf, len))
294                 return true;
295
296         int mib[4];
297
298         mib[0] = CTL_KERN;
299         mib[1] = KERN_PROC;
300         mib[2] = KERN_PROC_PATHNAME;
301         mib[3] = -1;
302
303         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
304                 return false;
305
306         return true;
307 }
308
309 //// Solaris
310 #elif defined(__sun) || defined(sun)
311
312 bool getCurrentExecPath(char *buf, size_t len)
313 {
314         const char *exec = getexecname();
315         if (exec == NULL)
316                 return false;
317
318         if (strlcpy(buf, exec, len) >= len)
319                 return false;
320
321         return true;
322 }
323
324 // HP-UX
325 #elif defined(__hpux)
326
327 bool getCurrentExecPath(char *buf, size_t len)
328 {
329         struct pst_status psts;
330
331         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
332                 return false;
333
334         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
335                 return false;
336
337         return true;
338 }
339
340 #else
341
342 bool getCurrentExecPath(char *buf, size_t len)
343 {
344         return false;
345 }
346
347 #endif
348
349 //// Non-Windows
350 #if !defined(_WIN32)
351
352 const char *getHomeOrFail()
353 {
354         const char *home = getenv("HOME");
355         // In rare cases the HOME environment variable may be unset
356         FATAL_ERROR_IF(!home, "Required environment variable HOME is not set");
357         return home;
358 }
359
360 #endif
361
362 //// Windows
363 #if defined(_WIN32)
364
365 bool setSystemPaths()
366 {
367         char buf[BUFSIZ];
368
369         // Find path of executable and set path_share relative to it
370         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
371                         "Failed to get current executable path");
372         pathRemoveFile(buf, '\\');
373
374         std::string exepath(buf);
375
376         // Use ".\bin\.."
377         path_share = exepath + "\\..";
378         if (detectMSVCBuildDir(exepath)) {
379                 // The msvc build dir schould normaly not be present if properly
380                 // installed, but its usefull for debugging.
381                 path_share += DIR_DELIM "..";
382         }
383
384         // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
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_C;
389         return true;
390 }
391
392 //// Linux
393 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) ||               \
394                 defined(__DragonFly__)
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" DIR_DELIM +
420                           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 i = trylist.begin();
428                         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 \"" << trypath
433                                       << "\"" << 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 \"" << trypath
440                                       << "\"" << std::endl;
441                 }
442
443                 path_share = trypath;
444                 break;
445         }
446
447 #ifndef __ANDROID__
448         path_user = std::string(getHomeOrFail()) + DIR_DELIM "." + PROJECT_NAME;
449 #endif
450
451         return true;
452 }
453
454 //// Mac OS X
455 #elif defined(__APPLE__)
456
457 bool setSystemPaths()
458 {
459         CFBundleRef main_bundle = CFBundleGetMainBundle();
460         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
461         char path[PATH_MAX];
462         if (CFURLGetFileSystemRepresentation(
463                             resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
464                 path_share = std::string(path);
465         } else {
466                 warningstream << "Could not determine bundle resource path" << std::endl;
467         }
468         CFRelease(resources_url);
469
470         path_user = std::string(getHomeOrFail()) + "/Library/Application Support/" +
471                     PROJECT_NAME;
472         return true;
473 }
474
475 #else
476
477 bool setSystemPaths()
478 {
479         path_share = STATIC_SHAREDIR;
480         path_user = std::string(getHomeOrFail()) + DIR_DELIM "." +
481                     lowercase(PROJECT_NAME);
482         return true;
483 }
484
485 #endif
486
487 void migrateCachePath()
488 {
489         const std::string local_cache_path = path_user + DIR_DELIM + "cache";
490
491         // Delete tmp folder if it exists (it only ever contained
492         // a temporary ogg file, which is no longer used).
493         if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
494                 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
495
496         // Bail if migration impossible
497         if (path_cache == local_cache_path || !fs::PathExists(local_cache_path) ||
498                         fs::PathExists(path_cache)) {
499                 return;
500         }
501         if (!fs::Rename(local_cache_path, path_cache)) {
502                 errorstream << "Failed to migrate local cache path "
503                                "to system path!"
504                             << std::endl;
505         }
506 }
507
508 void initializePaths()
509 {
510 #if RUN_IN_PLACE
511         char buf[BUFSIZ];
512
513         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
514
515         bool success = getCurrentExecPath(buf, sizeof(buf)) ||
516                        getExecPathFromProcfs(buf, sizeof(buf));
517
518         if (success) {
519                 pathRemoveFile(buf, DIR_DELIM_CHAR);
520                 std::string execpath(buf);
521
522                 path_share = execpath + DIR_DELIM "..";
523                 path_user = execpath + DIR_DELIM "..";
524
525                 if (detectMSVCBuildDir(execpath)) {
526                         path_share += DIR_DELIM "..";
527                         path_user += DIR_DELIM "..";
528                 }
529         } else {
530                 errorstream << "Failed to get paths by executable location, "
531                                "trying cwd"
532                             << std::endl;
533
534                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
535                         FATAL_ERROR("Ran out of methods to get paths");
536
537                 size_t cwdlen = strlen(buf);
538                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
539                         cwdlen--;
540                         buf[cwdlen] = '\0';
541                 }
542
543                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
544                         pathRemoveFile(buf, DIR_DELIM_CHAR);
545
546                 std::string execpath(buf);
547
548                 path_share = execpath;
549                 path_user = execpath;
550         }
551         path_cache = path_user + DIR_DELIM + "cache";
552 #else
553         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
554
555         if (!setSystemPaths())
556                 errorstream << "Failed to get one or more system-wide path" << std::endl;
557
558 #ifdef _WIN32
559         path_cache = path_user + DIR_DELIM + "cache";
560 #else
561         // Initialize path_cache
562         // First try $XDG_CACHE_HOME/PROJECT_NAME
563         const char *cache_dir = getenv("XDG_CACHE_HOME");
564         const char *home_dir = getenv("HOME");
565         if (cache_dir) {
566                 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
567         } else if (home_dir) {
568                 // Then try $HOME/.cache/PROJECT_NAME
569                 path_cache = std::string(home_dir) + DIR_DELIM + ".cache" + DIR_DELIM +
570                              PROJECT_NAME;
571         } else {
572                 // If neither works, use $PATH_USER/cache
573                 path_cache = path_user + DIR_DELIM + "cache";
574         }
575         // Migrate cache folder to new location if possible
576         migrateCachePath();
577 #endif // _WIN32
578 #endif // RUN_IN_PLACE
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         /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
588          * doesn't necessarily contain our locale files, so check data path first. */
589         path_locale = getDataPath("locale");
590         if (fs::PathExists(path_locale)) {
591                 found_localedir = true;
592                 infostream << "Using in-place locale directory " << path_locale
593                            << " even though a static one was provided." << std::endl;
594         } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
595                 found_localedir = true;
596                 path_locale = STATIC_LOCALEDIR;
597                 infostream << "Using static locale directory " << STATIC_LOCALEDIR
598                            << std::endl;
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 ||
656                                  _fileno(stdout) == -1); // If output is redirected to e.g
657                                                          // a file
658         if (!consoleAllocated && redirected &&
659                         (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
660                 freopen("CONOUT$", "w", stdout);
661                 freopen("CONOUT$", "w", stderr);
662                 consoleAllocated = true;
663         }
664 #endif
665 }
666
667 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
668 {
669         // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
670         //  Many of the MSVC / Windows printf-style functions do not support positional
671         //  arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
672         //  platforms, but defer to _vsprintf_p on MSVC / Windows.
673         // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
674         //  _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
675         //  above FFmpeg link).
676         va_list args;
677         va_start(args, fmt);
678 #ifndef _MSC_VER
679         int c = vsnprintf(buf, buf_size, fmt, args);
680 #else  // _MSC_VER
681         int c = _vsprintf_p(buf, buf_size, fmt, args);
682         if (c == -1)
683                 c = _vscprintf_p(fmt, args);
684 #endif // _MSC_VER
685         va_end(args);
686         return c;
687 }
688
689 bool openURL(const std::string &url)
690 {
691         if ((url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") ||
692                         url.find_first_of("\r\n") != std::string::npos) {
693                 errorstream << "Invalid url: " << url << std::endl;
694                 return false;
695         }
696
697 #if defined(_WIN32)
698         return (intptr_t)ShellExecuteA(
699                                NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
700 #elif defined(__ANDROID__)
701         openURLAndroid(url);
702         return true;
703 #elif defined(__APPLE__)
704         const char *argv[] = {"open", url.c_str(), NULL};
705         return posix_spawnp(NULL, "open", NULL, NULL, (char **)argv,
706                                (*_NSGetEnviron())) == 0;
707 #else
708         const char *argv[] = {"xdg-open", url.c_str(), NULL};
709         return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char **)argv, environ) == 0;
710 #endif
711 }
712
713 // Load performance counter frequency only once at startup
714 #ifdef _WIN32
715
716 inline double get_perf_freq()
717 {
718         LARGE_INTEGER freq;
719         QueryPerformanceFrequency(&freq);
720         return freq.QuadPart;
721 }
722
723 double perf_freq = get_perf_freq();
724
725 #endif
726
727 } // namespace porting