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