]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
98b85b7d00dcedceab0a2e3b80a9539b786ac591
[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__)
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 #ifdef USE_GETTEXT
562         bool found_localedir = false;
563 #  ifdef STATIC_LOCALEDIR
564         if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
565                 found_localedir = true;
566                 path_locale = STATIC_LOCALEDIR;
567                 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
568         } else {
569                 path_locale = getDataPath("locale");
570                 if (fs::PathExists(path_locale)) {
571                         found_localedir = true;
572                         infostream << "Using in-place locale directory " << path_locale
573                                 << " even though a static one was provided "
574                                 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
575                 }
576         }
577 #  else
578         path_locale = getDataPath("locale");
579         if (fs::PathExists(path_locale)) {
580                 found_localedir = true;
581         }
582 #  endif
583         if (!found_localedir) {
584                 warningstream << "Couldn't find a locale directory!" << std::endl;
585         }
586 #endif  // USE_GETTEXT
587 }
588
589
590
591 void setXorgClassHint(const video::SExposedVideoData &video_data,
592         const std::string &name)
593 {
594 #ifdef XORG_USED
595         if (video_data.OpenGLLinux.X11Display == NULL)
596                 return;
597
598         XClassHint *classhint = XAllocClassHint();
599         classhint->res_name  = (char *)name.c_str();
600         classhint->res_class = (char *)name.c_str();
601
602         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
603                 video_data.OpenGLLinux.X11Window, classhint);
604         XFree(classhint);
605 #endif
606 }
607
608
609 ////
610 //// Video/Display Information (Client-only)
611 ////
612
613 #ifndef SERVER
614
615 static irr::IrrlichtDevice *device;
616
617 void initIrrlicht(irr::IrrlichtDevice *device_)
618 {
619         device = device_;
620 }
621
622 v2u32 getWindowSize()
623 {
624         return device->getVideoDriver()->getScreenSize();
625 }
626
627
628 std::vector<core::vector3d<u32> > getSupportedVideoModes()
629 {
630         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
631         sanity_check(nulldevice != NULL);
632
633         std::vector<core::vector3d<u32> > mlist;
634         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
635
636         u32 num_modes = modelist->getVideoModeCount();
637         for (u32 i = 0; i != num_modes; i++) {
638                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
639                 s32 mode_depth = modelist->getVideoModeDepth(i);
640                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
641         }
642
643         nulldevice->drop();
644
645         return mlist;
646 }
647
648 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
649 {
650         std::vector<irr::video::E_DRIVER_TYPE> drivers;
651
652         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
653                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
654                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
655         }
656
657         return drivers;
658 }
659
660 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
661 {
662         static const char *driver_ids[] = {
663                 "null",
664                 "software",
665                 "burningsvideo",
666                 "direct3d8",
667                 "direct3d9",
668                 "opengl",
669                 "ogles1",
670                 "ogles2",
671         };
672
673         return driver_ids[type];
674 }
675
676
677 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
678 {
679         static const char *driver_names[] = {
680                 "NULL Driver",
681                 "Software Renderer",
682                 "Burning's Video",
683                 "Direct3D 8",
684                 "Direct3D 9",
685                 "OpenGL",
686                 "OpenGL ES1",
687                 "OpenGL ES2",
688         };
689
690         return driver_names[type];
691 }
692
693 #       ifndef __ANDROID__
694 #               ifdef XORG_USED
695
696 static float calcDisplayDensity()
697 {
698         const char *current_display = getenv("DISPLAY");
699
700         if (current_display != NULL) {
701                 Display *x11display = XOpenDisplay(current_display);
702
703                 if (x11display != NULL) {
704                         /* try x direct */
705                         float dpi_height = floor(DisplayHeight(x11display, 0) /
706                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
707                         float dpi_width = floor(DisplayWidth(x11display, 0) /
708                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
709
710                         XCloseDisplay(x11display);
711
712                         return std::max(dpi_height,dpi_width) / 96.0;
713                 }
714         }
715
716         /* return manually specified dpi */
717         return g_settings->getFloat("screen_dpi")/96.0;
718 }
719
720
721 float getDisplayDensity()
722 {
723         static float cached_display_density = calcDisplayDensity();
724         return cached_display_density;
725 }
726
727
728 #               else // XORG_USED
729 float getDisplayDensity()
730 {
731         return g_settings->getFloat("screen_dpi")/96.0;
732 }
733 #               endif // XORG_USED
734
735 v2u32 getDisplaySize()
736 {
737         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
738
739         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
740         nulldevice -> drop();
741
742         return deskres;
743 }
744 #       endif // __ANDROID__
745 #endif // SERVER
746
747
748 ////
749 //// OS-specific Secure Random
750 ////
751
752 #ifdef WIN32
753
754 bool secure_rand_fill_buf(void *buf, size_t len)
755 {
756         HCRYPTPROV wctx;
757
758         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
759                 return false;
760
761         CryptGenRandom(wctx, len, (BYTE *)buf);
762         CryptReleaseContext(wctx, 0);
763         return true;
764 }
765
766 #else
767
768 bool secure_rand_fill_buf(void *buf, size_t len)
769 {
770         // N.B.  This function checks *only* for /dev/urandom, because on most
771         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
772         // is exceptionally uncommon for there to be a situation where /dev/random
773         // exists but /dev/urandom does not.  This guesswork is necessary since
774         // random devices are not covered by any POSIX standard...
775         FILE *fp = fopen("/dev/urandom", "rb");
776         if (!fp)
777                 return false;
778
779         bool success = fread(buf, len, 1, fp) == 1;
780
781         fclose(fp);
782         return success;
783 }
784
785 #endif
786
787 } //namespace porting