4a72e90fdc26416e8bc909ab2b196481bc1d565c
[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__)
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 #if !defined(_WIN32) && !defined(__APPLE__) && \
45         !defined(__ANDROID__) && !defined(SERVER)
46         #define XORG_USED
47 #endif
48 #ifdef XORG_USED
49         #include <X11/Xlib.h>
50         #include <X11/Xutil.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 "settings.h"
59 #include <list>
60
61 namespace porting
62 {
63
64 /*
65         Signal handler (grabs Ctrl-C on POSIX systems)
66 */
67
68 bool g_killed = false;
69
70 bool * signal_handler_killstatus(void)
71 {
72         return &g_killed;
73 }
74
75 #if !defined(_WIN32) // POSIX
76         #include <signal.h>
77
78 void sigint_handler(int sig)
79 {
80         if (!g_killed) {
81                 dstream << "INFO: sigint_handler(): "
82                         << "Ctrl-C pressed, shutting down." << std::endl;
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(SIGINT, SIG_DFL);
92         }
93 }
94
95 void signal_handler_init(void)
96 {
97         (void)signal(SIGINT, sigint_handler);
98 }
99
100 #else // _WIN32
101         #include <signal.h>
102
103 BOOL WINAPI event_handler(DWORD sig)
104 {
105         switch (sig) {
106         case CTRL_C_EVENT:
107         case CTRL_CLOSE_EVENT:
108         case CTRL_LOGOFF_EVENT:
109         case CTRL_SHUTDOWN_EVENT:
110                 if (!g_killed) {
111                         dstream << "INFO: event_handler(): "
112                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
113                                 " shutting down." << std::endl;
114                         g_killed = true;
115                 } else {
116                         (void)signal(SIGINT, SIG_DFL);
117                 }
118                 break;
119         case CTRL_BREAK_EVENT:
120                 break;
121         }
122
123         return TRUE;
124 }
125
126 void signal_handler_init(void)
127 {
128         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
129 }
130
131 #endif
132
133
134 /*
135         Path mangler
136 */
137
138 // Default to RUN_IN_PLACE style relative paths
139 std::string path_share = "..";
140 std::string path_user = "..";
141 std::string path_locale = path_share + DIR_DELIM + "locale";
142 std::string path_cache = path_user + DIR_DELIM + "cache";
143
144
145 std::string getDataPath(const char *subpath)
146 {
147         return path_share + DIR_DELIM + subpath;
148 }
149
150 void pathRemoveFile(char *path, char delim)
151 {
152         // Remove filename and path delimiter
153         int i;
154         for(i = strlen(path)-1; i>=0; i--)
155         {
156                 if(path[i] == delim)
157                         break;
158         }
159         path[i] = 0;
160 }
161
162 bool detectMSVCBuildDir(const std::string &path)
163 {
164         const char *ends[] = {
165                 "bin\\Release",
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) || defined(__linux) || 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) || 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 #else
531         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
532
533         if (!setSystemPaths())
534                 errorstream << "Failed to get one or more system-wide path" << std::endl;
535
536         // Initialize path_cache
537         // First try $XDG_CACHE_HOME/PROJECT_NAME
538         const char *cache_dir = getenv("XDG_CACHE_HOME");
539         if (cache_dir) {
540                 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
541         } else {
542                 // Then try $HOME/.cache/PROJECT_NAME
543                 const char *home_dir = getenv("HOME");
544                 if (home_dir) {
545                         path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
546                                 + DIR_DELIM + PROJECT_NAME;
547                 }
548                 // If neither works, leave it at $PATH_USER/cache
549         }
550         // Migrate cache folder to new location if possible
551         migrateCachePath();
552 #endif
553
554         infostream << "Detected share path: " << path_share << std::endl;
555         infostream << "Detected user path: " << path_user << std::endl;
556         infostream << "Detected cache path: " << path_cache << std::endl;
557
558         bool found_localedir = false;
559 #ifdef STATIC_LOCALEDIR
560         if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
561                 found_localedir = true;
562                 path_locale = STATIC_LOCALEDIR;
563                 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
564         } else {
565                 path_locale = getDataPath("locale");
566                 if (fs::PathExists(path_locale)) {
567                         found_localedir = true;
568                         infostream << "Using in-place locale directory " << path_locale
569                                 << " even though a static one was provided "
570                                 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
571                 }
572         }
573 #else
574         path_locale = getDataPath("locale");
575         if (fs::PathExists(path_locale)) {
576                 found_localedir = true;
577         }
578 #endif
579         if (!found_localedir) {
580                 errorstream << "Couldn't find a locale directory!" << std::endl;
581         }
582 }
583
584
585
586 void setXorgClassHint(const video::SExposedVideoData &video_data,
587         const std::string &name)
588 {
589 #ifdef XORG_USED
590         if (video_data.OpenGLLinux.X11Display == NULL)
591                 return;
592
593         XClassHint *classhint = XAllocClassHint();
594         classhint->res_name  = (char *)name.c_str();
595         classhint->res_class = (char *)name.c_str();
596
597         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
598                 video_data.OpenGLLinux.X11Window, classhint);
599         XFree(classhint);
600 #endif
601 }
602
603
604 ////
605 //// Video/Display Information (Client-only)
606 ////
607
608 #ifndef SERVER
609
610 static irr::IrrlichtDevice *device;
611
612 void initIrrlicht(irr::IrrlichtDevice *device_)
613 {
614         device = device_;
615 }
616
617 v2u32 getWindowSize()
618 {
619         return device->getVideoDriver()->getScreenSize();
620 }
621
622
623 std::vector<core::vector3d<u32> > getSupportedVideoModes()
624 {
625         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
626         sanity_check(nulldevice != NULL);
627
628         std::vector<core::vector3d<u32> > mlist;
629         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
630
631         u32 num_modes = modelist->getVideoModeCount();
632         for (u32 i = 0; i != num_modes; i++) {
633                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
634                 s32 mode_depth = modelist->getVideoModeDepth(i);
635                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
636         }
637
638         nulldevice->drop();
639
640         return mlist;
641 }
642
643 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
644 {
645         std::vector<irr::video::E_DRIVER_TYPE> drivers;
646
647         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
648                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
649                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
650         }
651
652         return drivers;
653 }
654
655 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
656 {
657         static const char *driver_ids[] = {
658                 "null",
659                 "software",
660                 "burningsvideo",
661                 "direct3d8",
662                 "direct3d9",
663                 "opengl",
664                 "ogles1",
665                 "ogles2",
666         };
667
668         return driver_ids[type];
669 }
670
671
672 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
673 {
674         static const char *driver_names[] = {
675                 "NULL Driver",
676                 "Software Renderer",
677                 "Burning's Video",
678                 "Direct3D 8",
679                 "Direct3D 9",
680                 "OpenGL",
681                 "OpenGL ES1",
682                 "OpenGL ES2",
683         };
684
685         return driver_names[type];
686 }
687
688 #       ifndef __ANDROID__
689 #               ifdef XORG_USED
690
691 static float calcDisplayDensity()
692 {
693         const char *current_display = getenv("DISPLAY");
694
695         if (current_display != NULL) {
696                 Display *x11display = XOpenDisplay(current_display);
697
698                 if (x11display != NULL) {
699                         /* try x direct */
700                         float dpi_height = floor(DisplayHeight(x11display, 0) /
701                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
702                         float dpi_width = floor(DisplayWidth(x11display, 0) /
703                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
704
705                         XCloseDisplay(x11display);
706
707                         return std::max(dpi_height,dpi_width) / 96.0;
708                 }
709         }
710
711         /* return manually specified dpi */
712         return g_settings->getFloat("screen_dpi")/96.0;
713 }
714
715
716 float getDisplayDensity()
717 {
718         static float cached_display_density = calcDisplayDensity();
719         return cached_display_density;
720 }
721
722
723 #               else // XORG_USED
724 float getDisplayDensity()
725 {
726         return g_settings->getFloat("screen_dpi")/96.0;
727 }
728 #               endif // XORG_USED
729
730 v2u32 getDisplaySize()
731 {
732         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
733
734         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
735         nulldevice -> drop();
736
737         return deskres;
738 }
739 #       endif // __ANDROID__
740 #endif // SERVER
741
742
743 ////
744 //// OS-specific Secure Random
745 ////
746
747 #ifdef WIN32
748
749 bool secure_rand_fill_buf(void *buf, size_t len)
750 {
751         HCRYPTPROV wctx;
752
753         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
754                 return false;
755
756         CryptGenRandom(wctx, len, (BYTE *)buf);
757         CryptReleaseContext(wctx, 0);
758         return true;
759 }
760
761 #else
762
763 bool secure_rand_fill_buf(void *buf, size_t len)
764 {
765         // N.B.  This function checks *only* for /dev/urandom, because on most
766         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
767         // is exceptionally uncommon for there to be a situation where /dev/random
768         // exists but /dev/urandom does not.  This guesswork is necessary since
769         // random devices are not covered by any POSIX standard...
770         FILE *fp = fopen("/dev/urandom", "rb");
771         if (!fp)
772                 return false;
773
774         bool success = fread(buf, len, 1, fp) == 1;
775
776         fclose(fp);
777         return success;
778 }
779
780 #endif
781
782 } //namespace porting