Fix mouse events sent to wrong GUI elements when dragging
[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 #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         std::string exepath(buf);
384
385         // Use ".\bin\.."
386         path_share = exepath + "\\..";
387         if (detectMSVCBuildDir(exepath)) {
388                 // The msvc build dir schould normaly not be present if properly installed,
389                 // but its usefull for debugging.
390                 path_share += DIR_DELIM "..";
391         }
392
393         // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
394         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
395         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
396
397         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
398         return true;
399 }
400
401
402 //// Linux
403 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
404
405 bool setSystemPaths()
406 {
407         char buf[BUFSIZ];
408
409         if (!getCurrentExecPath(buf, sizeof(buf))) {
410 #ifdef __ANDROID__
411                 errorstream << "Unable to read bindir "<< std::endl;
412 #else
413                 FATAL_ERROR("Unable to read bindir");
414 #endif
415                 return false;
416         }
417
418         pathRemoveFile(buf, '/');
419         std::string bindir(buf);
420
421         // Find share directory from these.
422         // It is identified by containing the subdirectory "builtin".
423         std::list<std::string> trylist;
424         std::string static_sharedir = STATIC_SHAREDIR;
425         if (!static_sharedir.empty() && static_sharedir != ".")
426                 trylist.push_back(static_sharedir);
427
428         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
429                 DIR_DELIM + PROJECT_NAME);
430         trylist.push_back(bindir + DIR_DELIM "..");
431
432 #ifdef __ANDROID__
433         trylist.push_back(path_user);
434 #endif
435
436         for (std::list<std::string>::const_iterator
437                         i = trylist.begin(); i != trylist.end(); ++i) {
438                 const std::string &trypath = *i;
439                 if (!fs::PathExists(trypath) ||
440                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
441                         warningstream << "system-wide share not found at \""
442                                         << trypath << "\""<< std::endl;
443                         continue;
444                 }
445
446                 // Warn if was not the first alternative
447                 if (i != trylist.begin()) {
448                         warningstream << "system-wide share found at \""
449                                         << trypath << "\"" << std::endl;
450                 }
451
452                 path_share = trypath;
453                 break;
454         }
455
456 #ifndef __ANDROID__
457         path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
458                 + PROJECT_NAME;
459 #endif
460
461         return true;
462 }
463
464
465 //// Mac OS X
466 #elif defined(__APPLE__)
467
468 bool setSystemPaths()
469 {
470         CFBundleRef main_bundle = CFBundleGetMainBundle();
471         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
472         char path[PATH_MAX];
473         if (CFURLGetFileSystemRepresentation(resources_url,
474                         TRUE, (UInt8 *)path, PATH_MAX)) {
475                 path_share = std::string(path);
476         } else {
477                 warningstream << "Could not determine bundle resource path" << std::endl;
478         }
479         CFRelease(resources_url);
480
481         path_user = std::string(getHomeOrFail())
482                 + "/Library/Application Support/"
483                 + PROJECT_NAME;
484         return true;
485 }
486
487
488 #else
489
490 bool setSystemPaths()
491 {
492         path_share = STATIC_SHAREDIR;
493         path_user  = std::string(getHomeOrFail()) + DIR_DELIM "."
494                 + lowercase(PROJECT_NAME);
495         return true;
496 }
497
498
499 #endif
500
501 void migrateCachePath()
502 {
503         const std::string local_cache_path = path_user + DIR_DELIM + "cache";
504
505         // Delete tmp folder if it exists (it only ever contained
506         // a temporary ogg file, which is no longer used).
507         if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
508                 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
509
510         // Bail if migration impossible
511         if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
512                         || fs::PathExists(path_cache)) {
513                 return;
514         }
515         if (!fs::Rename(local_cache_path, path_cache)) {
516                 errorstream << "Failed to migrate local cache path "
517                         "to system path!" << std::endl;
518         }
519 }
520
521 void initializePaths()
522 {
523 #if RUN_IN_PLACE
524         char buf[BUFSIZ];
525
526         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
527
528         bool success =
529                 getCurrentExecPath(buf, sizeof(buf)) ||
530                 getExecPathFromProcfs(buf, sizeof(buf));
531
532         if (success) {
533                 pathRemoveFile(buf, DIR_DELIM_CHAR);
534                 std::string execpath(buf);
535
536                 path_share = execpath + DIR_DELIM "..";
537                 path_user  = execpath + DIR_DELIM "..";
538
539                 if (detectMSVCBuildDir(execpath)) {
540                         path_share += DIR_DELIM "..";
541                         path_user  += DIR_DELIM "..";
542                 }
543         } else {
544                 errorstream << "Failed to get paths by executable location, "
545                         "trying cwd" << std::endl;
546
547                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
548                         FATAL_ERROR("Ran out of methods to get paths");
549
550                 size_t cwdlen = strlen(buf);
551                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
552                         cwdlen--;
553                         buf[cwdlen] = '\0';
554                 }
555
556                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
557                         pathRemoveFile(buf, DIR_DELIM_CHAR);
558
559                 std::string execpath(buf);
560
561                 path_share = execpath;
562                 path_user  = execpath;
563         }
564         path_cache = path_user + DIR_DELIM + "cache";
565 #else
566         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
567
568         if (!setSystemPaths())
569                 errorstream << "Failed to get one or more system-wide path" << std::endl;
570
571
572 #  ifdef _WIN32
573         path_cache = path_user + DIR_DELIM + "cache";
574 #  else
575         // Initialize path_cache
576         // First try $XDG_CACHE_HOME/PROJECT_NAME
577         const char *cache_dir = getenv("XDG_CACHE_HOME");
578         const char *home_dir = getenv("HOME");
579         if (cache_dir) {
580                 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
581         } else if (home_dir) {
582                 // Then try $HOME/.cache/PROJECT_NAME
583                 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
584                         + DIR_DELIM + PROJECT_NAME;
585         } else {
586                 // If neither works, use $PATH_USER/cache
587                 path_cache = path_user + DIR_DELIM + "cache";
588         }
589         // Migrate cache folder to new location if possible
590         migrateCachePath();
591 #  endif // _WIN32
592 #endif // RUN_IN_PLACE
593
594         infostream << "Detected share path: " << path_share << std::endl;
595         infostream << "Detected user path: " << path_user << std::endl;
596         infostream << "Detected cache path: " << path_cache << std::endl;
597
598 #if USE_GETTEXT
599         bool found_localedir = false;
600 #  ifdef STATIC_LOCALEDIR
601         if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
602                 found_localedir = true;
603                 path_locale = STATIC_LOCALEDIR;
604                 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
605         } else {
606                 path_locale = getDataPath("locale");
607                 if (fs::PathExists(path_locale)) {
608                         found_localedir = true;
609                         infostream << "Using in-place locale directory " << path_locale
610                                 << " even though a static one was provided "
611                                 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
612                 }
613         }
614 #  else
615         path_locale = getDataPath("locale");
616         if (fs::PathExists(path_locale)) {
617                 found_localedir = true;
618         }
619 #  endif
620         if (!found_localedir) {
621                 warningstream << "Couldn't find a locale directory!" << std::endl;
622         }
623 #endif  // USE_GETTEXT
624 }
625
626 ////
627 //// OS-specific Secure Random
628 ////
629
630 #ifdef WIN32
631
632 bool secure_rand_fill_buf(void *buf, size_t len)
633 {
634         HCRYPTPROV wctx;
635
636         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
637                 return false;
638
639         CryptGenRandom(wctx, len, (BYTE *)buf);
640         CryptReleaseContext(wctx, 0);
641         return true;
642 }
643
644 #else
645
646 bool secure_rand_fill_buf(void *buf, size_t len)
647 {
648         // N.B.  This function checks *only* for /dev/urandom, because on most
649         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
650         // is exceptionally uncommon for there to be a situation where /dev/random
651         // exists but /dev/urandom does not.  This guesswork is necessary since
652         // random devices are not covered by any POSIX standard...
653         FILE *fp = fopen("/dev/urandom", "rb");
654         if (!fp)
655                 return false;
656
657         bool success = fread(buf, len, 1, fp) == 1;
658
659         fclose(fp);
660         return success;
661 }
662
663 #endif
664
665 void attachOrCreateConsole()
666 {
667 #ifdef _WIN32
668         static bool consoleAllocated = false;
669         const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
670         if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
671                 freopen("CONOUT$", "w", stdout);
672                 freopen("CONOUT$", "w", stderr);
673                 consoleAllocated = true;
674         }
675 #endif
676 }
677
678 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
679 {
680         // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
681         //  Many of the MSVC / Windows printf-style functions do not support positional
682         //  arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
683         //  platforms, but defer to _vsprintf_p on MSVC / Windows.
684         // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
685         //  _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
686         //  above FFmpeg link).
687         va_list args;
688         va_start(args, fmt);
689 #ifndef _MSC_VER
690         int c = vsnprintf(buf, buf_size, fmt, args);
691 #else  // _MSC_VER
692         int c = _vsprintf_p(buf, buf_size, fmt, args);
693         if (c == -1)
694                 c = _vscprintf_p(fmt, args);
695 #endif // _MSC_VER
696         va_end(args);
697         return c;
698 }
699
700 // Load performance counter frequency only once at startup
701 #ifdef _WIN32
702
703 inline double get_perf_freq()
704 {
705         LARGE_INTEGER freq;
706         QueryPerformanceFrequency(&freq);
707         return freq.QuadPart;
708 }
709
710 double perf_freq = get_perf_freq();
711
712 #endif
713
714 } //namespace porting