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