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