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