]> git.lizzy.rs Git - minetest.git/blob - src/porting.cpp
Mgvalleys: use standard caves
[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\\MinSizeRel",
167                 "bin\\RelWithDebInfo",
168                 "bin\\Debug",
169                 "bin\\Build",
170                 NULL
171         };
172         return (removeStringEnd(path, ends) != "");
173 }
174
175 std::string get_sysinfo()
176 {
177 #ifdef _WIN32
178         OSVERSIONINFO osvi;
179         std::ostringstream oss;
180         std::string tmp;
181         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
182         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
183         GetVersionEx(&osvi);
184         tmp = osvi.szCSDVersion;
185         std::replace(tmp.begin(), tmp.end(), ' ', '_');
186
187         oss << "Windows/" << osvi.dwMajorVersion << "."
188                 << osvi.dwMinorVersion;
189         if (osvi.szCSDVersion[0])
190                 oss << "-" << tmp;
191         oss << " ";
192         #ifdef _WIN64
193         oss << "x86_64";
194         #else
195         BOOL is64 = FALSE;
196         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
197                 oss << "x86_64"; // 32-bit app on 64-bit OS
198         else
199                 oss << "x86";
200         #endif
201
202         return oss.str();
203 #else
204         struct utsname osinfo;
205         uname(&osinfo);
206         return std::string(osinfo.sysname) + "/"
207                 + osinfo.release + " " + osinfo.machine;
208 #endif
209 }
210
211
212 bool getCurrentWorkingDir(char *buf, size_t len)
213 {
214 #ifdef _WIN32
215         DWORD ret = GetCurrentDirectory(len, buf);
216         return (ret != 0) && (ret <= len);
217 #else
218         return getcwd(buf, len);
219 #endif
220 }
221
222
223 bool getExecPathFromProcfs(char *buf, size_t buflen)
224 {
225 #ifndef _WIN32
226         buflen--;
227
228         ssize_t len;
229         if ((len = readlink("/proc/self/exe",     buf, buflen)) == -1 &&
230                 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
231                 (len = readlink("/proc/curproc/exe",  buf, buflen)) == -1)
232                 return false;
233
234         buf[len] = '\0';
235         return true;
236 #else
237         return false;
238 #endif
239 }
240
241 //// Windows
242 #if defined(_WIN32)
243
244 bool getCurrentExecPath(char *buf, size_t len)
245 {
246         DWORD written = GetModuleFileNameA(NULL, buf, len);
247         if (written == 0 || written == len)
248                 return false;
249
250         return true;
251 }
252
253
254 //// Linux
255 #elif defined(linux) || defined(__linux) || defined(__linux__)
256
257 bool getCurrentExecPath(char *buf, size_t len)
258 {
259         if (!getExecPathFromProcfs(buf, len))
260                 return false;
261
262         return true;
263 }
264
265
266 //// Mac OS X, Darwin
267 #elif defined(__APPLE__)
268
269 bool getCurrentExecPath(char *buf, size_t len)
270 {
271         uint32_t lenb = (uint32_t)len;
272         if (_NSGetExecutablePath(buf, &lenb) == -1)
273                 return false;
274
275         return true;
276 }
277
278
279 //// FreeBSD, NetBSD, DragonFlyBSD
280 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
281
282 bool getCurrentExecPath(char *buf, size_t len)
283 {
284         // Try getting path from procfs first, since valgrind
285         // doesn't work with the latter
286         if (getExecPathFromProcfs(buf, len))
287                 return true;
288
289         int mib[4];
290
291         mib[0] = CTL_KERN;
292         mib[1] = KERN_PROC;
293         mib[2] = KERN_PROC_PATHNAME;
294         mib[3] = -1;
295
296         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
297                 return false;
298
299         return true;
300 }
301
302
303 //// Solaris
304 #elif defined(__sun) || defined(sun)
305
306 bool getCurrentExecPath(char *buf, size_t len)
307 {
308         const char *exec = getexecname();
309         if (exec == NULL)
310                 return false;
311
312         if (strlcpy(buf, exec, len) >= len)
313                 return false;
314
315         return true;
316 }
317
318
319 // HP-UX
320 #elif defined(__hpux)
321
322 bool getCurrentExecPath(char *buf, size_t len)
323 {
324         struct pst_status psts;
325
326         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
327                 return false;
328
329         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
330                 return false;
331
332         return true;
333 }
334
335
336 #else
337
338 bool getCurrentExecPath(char *buf, size_t len)
339 {
340         return false;
341 }
342
343 #endif
344
345
346 //// Windows
347 #if defined(_WIN32)
348
349 bool setSystemPaths()
350 {
351         char buf[BUFSIZ];
352
353         // Find path of executable and set path_share relative to it
354         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
355                 "Failed to get current executable path");
356         pathRemoveFile(buf, '\\');
357
358         // Use ".\bin\.."
359         path_share = std::string(buf) + "\\..";
360
361         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
362         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
363         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
364
365         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
366         return true;
367 }
368
369
370 //// Linux
371 #elif defined(linux) || defined(__linux)
372
373 bool setSystemPaths()
374 {
375         char buf[BUFSIZ];
376
377         if (!getCurrentExecPath(buf, sizeof(buf))) {
378 #ifdef __ANDROID__
379                 errorstream << "Unable to read bindir "<< std::endl;
380 #else
381                 FATAL_ERROR("Unable to read bindir");
382 #endif
383                 return false;
384         }
385
386         pathRemoveFile(buf, '/');
387         std::string bindir(buf);
388
389         // Find share directory from these.
390         // It is identified by containing the subdirectory "builtin".
391         std::list<std::string> trylist;
392         std::string static_sharedir = STATIC_SHAREDIR;
393         if (static_sharedir != "" && static_sharedir != ".")
394                 trylist.push_back(static_sharedir);
395
396         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
397                 DIR_DELIM + PROJECT_NAME);
398         trylist.push_back(bindir + DIR_DELIM "..");
399
400 #ifdef __ANDROID__
401         trylist.push_back(path_user);
402 #endif
403
404         for (std::list<std::string>::const_iterator
405                         i = trylist.begin(); i != trylist.end(); i++) {
406                 const std::string &trypath = *i;
407                 if (!fs::PathExists(trypath) ||
408                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
409                         warningstream << "system-wide share not found at \""
410                                         << trypath << "\""<< std::endl;
411                         continue;
412                 }
413
414                 // Warn if was not the first alternative
415                 if (i != trylist.begin()) {
416                         warningstream << "system-wide share found at \""
417                                         << trypath << "\"" << std::endl;
418                 }
419
420                 path_share = trypath;
421                 break;
422         }
423
424 #ifndef __ANDROID__
425         path_user = std::string(getenv("HOME")) + DIR_DELIM "."
426                 + PROJECT_NAME;
427 #endif
428
429         return true;
430 }
431
432
433 //// Mac OS X
434 #elif defined(__APPLE__)
435
436 bool setSystemPaths()
437 {
438         CFBundleRef main_bundle = CFBundleGetMainBundle();
439         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
440         char path[PATH_MAX];
441         if (CFURLGetFileSystemRepresentation(resources_url,
442                         TRUE, (UInt8 *)path, PATH_MAX)) {
443                 path_share = std::string(path);
444         } else {
445                 warningstream << "Could not determine bundle resource path" << std::endl;
446         }
447         CFRelease(resources_url);
448
449         path_user = std::string(getenv("HOME"))
450                 + "/Library/Application Support/"
451                 + PROJECT_NAME;
452         return true;
453 }
454
455
456 #else
457
458 bool setSystemPaths()
459 {
460         path_share = STATIC_SHAREDIR;
461         path_user  = std::string(getenv("HOME")) + DIR_DELIM "."
462                 + lowercase(PROJECT_NAME);
463         return true;
464 }
465
466
467 #endif
468
469 void migrateCachePath()
470 {
471         const std::string local_cache_path = path_user + DIR_DELIM + "cache";
472
473         // Delete tmp folder if it exists (it only ever contained
474         // a temporary ogg file, which is no longer used).
475         if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
476                 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
477
478         // Bail if migration impossible
479         if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
480                         || fs::PathExists(path_cache)) {
481                 return;
482         }
483         if (!fs::Rename(local_cache_path, path_cache)) {
484                 errorstream << "Failed to migrate local cache path "
485                         "to system path!" << std::endl;
486         }
487 }
488
489 void initializePaths()
490 {
491 #if RUN_IN_PLACE
492         char buf[BUFSIZ];
493
494         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
495
496         bool success =
497                 getCurrentExecPath(buf, sizeof(buf)) ||
498                 getExecPathFromProcfs(buf, sizeof(buf));
499
500         if (success) {
501                 pathRemoveFile(buf, DIR_DELIM_CHAR);
502                 std::string execpath(buf);
503
504                 path_share = execpath + DIR_DELIM "..";
505                 path_user  = execpath + DIR_DELIM "..";
506
507                 if (detectMSVCBuildDir(execpath)) {
508                         path_share += DIR_DELIM "..";
509                         path_user  += DIR_DELIM "..";
510                 }
511         } else {
512                 errorstream << "Failed to get paths by executable location, "
513                         "trying cwd" << std::endl;
514
515                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
516                         FATAL_ERROR("Ran out of methods to get paths");
517
518                 size_t cwdlen = strlen(buf);
519                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
520                         cwdlen--;
521                         buf[cwdlen] = '\0';
522                 }
523
524                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
525                         pathRemoveFile(buf, DIR_DELIM_CHAR);
526
527                 std::string execpath(buf);
528
529                 path_share = execpath;
530                 path_user  = execpath;
531         }
532         path_cache = path_user + DIR_DELIM + "cache";
533 #else
534         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
535
536         if (!setSystemPaths())
537                 errorstream << "Failed to get one or more system-wide path" << std::endl;
538
539         // Initialize path_cache
540         // First try $XDG_CACHE_HOME/PROJECT_NAME
541         const char *cache_dir = getenv("XDG_CACHE_HOME");
542         const char *home_dir = getenv("HOME");
543         if (cache_dir) {
544                 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
545         } else if (home_dir) {
546                 // Then try $HOME/.cache/PROJECT_NAME
547                 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
548                         + DIR_DELIM + PROJECT_NAME;
549         } else {
550                 // If neither works, use $PATH_USER/cache
551                 path_cache = path_user + DIR_DELIM + "cache";
552         }
553         // Migrate cache folder to new location if possible
554         migrateCachePath();
555 #endif
556
557         infostream << "Detected share path: " << path_share << std::endl;
558         infostream << "Detected user path: " << path_user << std::endl;
559         infostream << "Detected cache path: " << path_cache << std::endl;
560
561         bool found_localedir = false;
562 #ifdef STATIC_LOCALEDIR
563         if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
564                 found_localedir = true;
565                 path_locale = STATIC_LOCALEDIR;
566                 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
567         } else {
568                 path_locale = getDataPath("locale");
569                 if (fs::PathExists(path_locale)) {
570                         found_localedir = true;
571                         infostream << "Using in-place locale directory " << path_locale
572                                 << " even though a static one was provided "
573                                 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
574                 }
575         }
576 #else
577         path_locale = getDataPath("locale");
578         if (fs::PathExists(path_locale)) {
579                 found_localedir = true;
580         }
581 #endif
582         if (!found_localedir) {
583                 errorstream << "Couldn't find a locale directory!" << std::endl;
584         }
585 }
586
587
588
589 void setXorgClassHint(const video::SExposedVideoData &video_data,
590         const std::string &name)
591 {
592 #ifdef XORG_USED
593         if (video_data.OpenGLLinux.X11Display == NULL)
594                 return;
595
596         XClassHint *classhint = XAllocClassHint();
597         classhint->res_name  = (char *)name.c_str();
598         classhint->res_class = (char *)name.c_str();
599
600         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
601                 video_data.OpenGLLinux.X11Window, classhint);
602         XFree(classhint);
603 #endif
604 }
605
606
607 ////
608 //// Video/Display Information (Client-only)
609 ////
610
611 #ifndef SERVER
612
613 static irr::IrrlichtDevice *device;
614
615 void initIrrlicht(irr::IrrlichtDevice *device_)
616 {
617         device = device_;
618 }
619
620 v2u32 getWindowSize()
621 {
622         return device->getVideoDriver()->getScreenSize();
623 }
624
625
626 std::vector<core::vector3d<u32> > getSupportedVideoModes()
627 {
628         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
629         sanity_check(nulldevice != NULL);
630
631         std::vector<core::vector3d<u32> > mlist;
632         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
633
634         u32 num_modes = modelist->getVideoModeCount();
635         for (u32 i = 0; i != num_modes; i++) {
636                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
637                 s32 mode_depth = modelist->getVideoModeDepth(i);
638                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
639         }
640
641         nulldevice->drop();
642
643         return mlist;
644 }
645
646 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
647 {
648         std::vector<irr::video::E_DRIVER_TYPE> drivers;
649
650         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
651                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
652                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
653         }
654
655         return drivers;
656 }
657
658 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
659 {
660         static const char *driver_ids[] = {
661                 "null",
662                 "software",
663                 "burningsvideo",
664                 "direct3d8",
665                 "direct3d9",
666                 "opengl",
667                 "ogles1",
668                 "ogles2",
669         };
670
671         return driver_ids[type];
672 }
673
674
675 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
676 {
677         static const char *driver_names[] = {
678                 "NULL Driver",
679                 "Software Renderer",
680                 "Burning's Video",
681                 "Direct3D 8",
682                 "Direct3D 9",
683                 "OpenGL",
684                 "OpenGL ES1",
685                 "OpenGL ES2",
686         };
687
688         return driver_names[type];
689 }
690
691 #       ifndef __ANDROID__
692 #               ifdef XORG_USED
693
694 static float calcDisplayDensity()
695 {
696         const char *current_display = getenv("DISPLAY");
697
698         if (current_display != NULL) {
699                 Display *x11display = XOpenDisplay(current_display);
700
701                 if (x11display != NULL) {
702                         /* try x direct */
703                         float dpi_height = floor(DisplayHeight(x11display, 0) /
704                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
705                         float dpi_width = floor(DisplayWidth(x11display, 0) /
706                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
707
708                         XCloseDisplay(x11display);
709
710                         return std::max(dpi_height,dpi_width) / 96.0;
711                 }
712         }
713
714         /* return manually specified dpi */
715         return g_settings->getFloat("screen_dpi")/96.0;
716 }
717
718
719 float getDisplayDensity()
720 {
721         static float cached_display_density = calcDisplayDensity();
722         return cached_display_density;
723 }
724
725
726 #               else // XORG_USED
727 float getDisplayDensity()
728 {
729         return g_settings->getFloat("screen_dpi")/96.0;
730 }
731 #               endif // XORG_USED
732
733 v2u32 getDisplaySize()
734 {
735         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
736
737         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
738         nulldevice -> drop();
739
740         return deskres;
741 }
742 #       endif // __ANDROID__
743 #endif // SERVER
744
745
746 ////
747 //// OS-specific Secure Random
748 ////
749
750 #ifdef WIN32
751
752 bool secure_rand_fill_buf(void *buf, size_t len)
753 {
754         HCRYPTPROV wctx;
755
756         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
757                 return false;
758
759         CryptGenRandom(wctx, len, (BYTE *)buf);
760         CryptReleaseContext(wctx, 0);
761         return true;
762 }
763
764 #else
765
766 bool secure_rand_fill_buf(void *buf, size_t len)
767 {
768         // N.B.  This function checks *only* for /dev/urandom, because on most
769         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
770         // is exceptionally uncommon for there to be a situation where /dev/random
771         // exists but /dev/urandom does not.  This guesswork is necessary since
772         // random devices are not covered by any POSIX standard...
773         FILE *fp = fopen("/dev/urandom", "rb");
774         if (!fp)
775                 return false;
776
777         bool success = fread(buf, len, 1, fp) == 1;
778
779         fclose(fp);
780         return success;
781 }
782
783 #endif
784
785 } //namespace porting