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