1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 /*
21 Random portability stuff
22
23 See comments in porting.h
24 */
25
26 #include "porting.h"
27
28 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
31 extern char **environ;
32 #elif defined(_WIN32)
33 #include <windows.h>
34 #include <wincrypt.h>
35 #include <algorithm>
36 #include <shlwapi.h>
37 #include <shellapi.h>
38 #endif
39 #if !defined(_WIN32)
40 #include <unistd.h>
41 #include <sys/utsname.h>
42 #if !defined(__ANDROID__)
43 #include <spawn.h>
44 #endif
45 #endif
46 #if defined(__hpux)
47 #define _PSTAT64
48 #include <sys/pstat.h>
49 #endif
50 #if defined(__ANDROID__)
51 #include "porting_android.h"
52 #endif
53 #if defined(__APPLE__)
54 // For _NSGetEnviron()
55 // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
56 #include <crt_externs.h>
57 #endif
58
59 #if defined(__HAIKU__)
60 #include <FindDirectory.h>
61 #endif
62
63 #include "config.h"
64 #include "debug.h"
65 #include "filesys.h"
66 #include "log.h"
67 #include "util/string.h"
68 #include <list>
69 #include <cstdarg>
70 #include <cstdio>
71
72 namespace porting
73 {
74
75 /*
76 Signal handler (grabs Ctrl-C on POSIX systems)
77 */
78
79 bool g_killed = false;
80
signal_handler_killstatus()81 bool *signal_handler_killstatus()
82 {
83 return &g_killed;
84 }
85
86 #if !defined(_WIN32) // POSIX
87 #include <signal.h>
88
signal_handler(int sig)89 void signal_handler(int sig)
90 {
91 if (!g_killed) {
92 if (sig == SIGINT) {
93 dstream << "INFO: signal_handler(): "
94 << "Ctrl-C pressed, shutting down." << std::endl;
95 } else if (sig == SIGTERM) {
96 dstream << "INFO: signal_handler(): "
97 << "got SIGTERM, shutting down." << std::endl;
98 }
99
100 // Comment out for less clutter when testing scripts
101 /*dstream << "INFO: sigint_handler(): "
102 << "Printing debug stacks" << std::endl;
103 debug_stacks_print();*/
104
105 g_killed = true;
106 } else {
107 (void)signal(sig, SIG_DFL);
108 }
109 }
110
signal_handler_init(void)111 void signal_handler_init(void)
112 {
113 (void)signal(SIGINT, signal_handler);
114 (void)signal(SIGTERM, signal_handler);
115 }
116
117 #else // _WIN32
118 #include <signal.h>
119
event_handler(DWORD sig)120 BOOL WINAPI event_handler(DWORD sig)
121 {
122 switch (sig) {
123 case CTRL_C_EVENT:
124 case CTRL_CLOSE_EVENT:
125 case CTRL_LOGOFF_EVENT:
126 case CTRL_SHUTDOWN_EVENT:
127 if (!g_killed) {
128 dstream << "INFO: event_handler(): "
129 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
130 " shutting down." << std::endl;
131 g_killed = true;
132 } else {
133 (void)signal(SIGINT, SIG_DFL);
134 }
135 break;
136 case CTRL_BREAK_EVENT:
137 break;
138 }
139
140 return TRUE;
141 }
142
signal_handler_init(void)143 void signal_handler_init(void)
144 {
145 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
146 }
147
148 #endif
149
150
151 /*
152 Path mangler
153 */
154
155 // Default to RUN_IN_PLACE style relative paths
156 std::string path_share = "..";
157 std::string path_user = "..";
158 std::string path_locale = path_share + DIR_DELIM + "locale";
159 std::string path_cache = path_user + DIR_DELIM + "cache";
160
161
getDataPath(const char * subpath)162 std::string getDataPath(const char *subpath)
163 {
164 return path_share + DIR_DELIM + subpath;
165 }
166
pathRemoveFile(char * path,char delim)167 void pathRemoveFile(char *path, char delim)
168 {
169 // Remove filename and path delimiter
170 int i;
171 for(i = strlen(path)-1; i>=0; i--)
172 {
173 if(path[i] == delim)
174 break;
175 }
176 path[i] = 0;
177 }
178
detectMSVCBuildDir(const std::string & path)179 bool detectMSVCBuildDir(const std::string &path)
180 {
181 const char *ends[] = {
182 "bin\\Release",
183 "bin\\MinSizeRel",
184 "bin\\RelWithDebInfo",
185 "bin\\Debug",
186 "bin\\Build",
187 NULL
188 };
189 return (!removeStringEnd(path, ends).empty());
190 }
191
get_sysinfo()192 std::string get_sysinfo()
193 {
194 #ifdef _WIN32
195
196 std::ostringstream oss;
197 LPSTR filePath = new char[MAX_PATH];
198 UINT blockSize;
199 VS_FIXEDFILEINFO *fixedFileInfo;
200
201 GetSystemDirectoryA(filePath, MAX_PATH);
202 PathAppendA(filePath, "kernel32.dll");
203
204 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
205 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
206
207 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
208 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
209
210 oss << "Windows/"
211 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
212 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
213 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
214
215 #ifdef _WIN64
216 oss << "x86_64";
217 #else
218 BOOL is64 = FALSE;
219 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
220 oss << "x86_64"; // 32-bit app on 64-bit OS
221 else
222 oss << "x86";
223 #endif
224
225 delete[] lpVersionInfo;
226 delete[] filePath;
227
228 return oss.str();
229 #else
230 struct utsname osinfo;
231 uname(&osinfo);
232 return std::string(osinfo.sysname) + "/"
233 + osinfo.release + " " + osinfo.machine;
234 #endif
235 }
236
237
getCurrentWorkingDir(char * buf,size_t len)238 bool getCurrentWorkingDir(char *buf, size_t len)
239 {
240 #ifdef _WIN32
241 DWORD ret = GetCurrentDirectory(len, buf);
242 return (ret != 0) && (ret <= len);
243 #else
244 return getcwd(buf, len);
245 #endif
246 }
247
248
getExecPathFromProcfs(char * buf,size_t buflen)249 bool getExecPathFromProcfs(char *buf, size_t buflen)
250 {
251 #ifndef _WIN32
252 buflen--;
253
254 ssize_t len;
255 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
256 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
257 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
258 return false;
259
260 buf[len] = '\0';
261 return true;
262 #else
263 return false;
264 #endif
265 }
266
267 //// Windows
268 #if defined(_WIN32)
269
getCurrentExecPath(char * buf,size_t len)270 bool getCurrentExecPath(char *buf, size_t len)
271 {
272 DWORD written = GetModuleFileNameA(NULL, buf, len);
273 if (written == 0 || written == len)
274 return false;
275
276 return true;
277 }
278
279
280 //// Linux
281 #elif defined(__linux__)
282
getCurrentExecPath(char * buf,size_t len)283 bool getCurrentExecPath(char *buf, size_t len)
284 {
285 if (!getExecPathFromProcfs(buf, len))
286 return false;
287
288 return true;
289 }
290
291
292 //// Mac OS X, Darwin
293 #elif defined(__APPLE__)
294
getCurrentExecPath(char * buf,size_t len)295 bool getCurrentExecPath(char *buf, size_t len)
296 {
297 uint32_t lenb = (uint32_t)len;
298 if (_NSGetExecutablePath(buf, &lenb) == -1)
299 return false;
300
301 return true;
302 }
303
304
305 //// FreeBSD, NetBSD, DragonFlyBSD
306 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
307
getCurrentExecPath(char * buf,size_t len)308 bool getCurrentExecPath(char *buf, size_t len)
309 {
310 // Try getting path from procfs first, since valgrind
311 // doesn't work with the latter
312 if (getExecPathFromProcfs(buf, len))
313 return true;
314
315 int mib[4];
316
317 mib[0] = CTL_KERN;
318 mib[1] = KERN_PROC;
319 mib[2] = KERN_PROC_PATHNAME;
320 mib[3] = -1;
321
322 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
323 return false;
324
325 return true;
326 }
327
328 #elif defined(__HAIKU__)
329
getCurrentExecPath(char * buf,size_t len)330 bool getCurrentExecPath(char *buf, size_t len)
331 {
332 return find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, buf, len) == B_OK;
333 }
334
335 //// Solaris
336 #elif defined(__sun) || defined(sun)
337
getCurrentExecPath(char * buf,size_t len)338 bool getCurrentExecPath(char *buf, size_t len)
339 {
340 const char *exec = getexecname();
341 if (exec == NULL)
342 return false;
343
344 if (strlcpy(buf, exec, len) >= len)
345 return false;
346
347 return true;
348 }
349
350
351 // HP-UX
352 #elif defined(__hpux)
353
getCurrentExecPath(char * buf,size_t len)354 bool getCurrentExecPath(char *buf, size_t len)
355 {
356 struct pst_status psts;
357
358 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
359 return false;
360
361 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
362 return false;
363
364 return true;
365 }
366
367
368 #else
369
getCurrentExecPath(char * buf,size_t len)370 bool getCurrentExecPath(char *buf, size_t len)
371 {
372 return false;
373 }
374
375 #endif
376
377
378 //// Non-Windows
379 #if !defined(_WIN32)
380
getHomeOrFail()381 const char *getHomeOrFail()
382 {
383 const char *home = getenv("HOME");
384 // In rare cases the HOME environment variable may be unset
385 FATAL_ERROR_IF(!home,
386 "Required environment variable HOME is not set");
387 return home;
388 }
389
390 #endif
391
392
393 //// Windows
394 #if defined(_WIN32)
395
setSystemPaths()396 bool setSystemPaths()
397 {
398 char buf[BUFSIZ];
399
400 // Find path of executable and set path_share relative to it
401 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
402 "Failed to get current executable path");
403 pathRemoveFile(buf, '\\');
404
405 std::string exepath(buf);
406
407 // Use ".\bin\.."
408 path_share = exepath + "\\..";
409 if (detectMSVCBuildDir(exepath)) {
410 // The msvc build dir schould normaly not be present if properly installed,
411 // but its usefull for debugging.
412 path_share += DIR_DELIM "..";
413 }
414
415 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
416 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
417 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
418
419 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
420 return true;
421 }
422
423
424 //// Linux
425 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
426
setSystemPaths()427 bool setSystemPaths()
428 {
429 char buf[BUFSIZ];
430
431 if (!getCurrentExecPath(buf, sizeof(buf))) {
432 #ifdef __ANDROID__
433 errorstream << "Unable to read bindir "<< std::endl;
434 #else
435 FATAL_ERROR("Unable to read bindir");
436 #endif
437 return false;
438 }
439
440 pathRemoveFile(buf, '/');
441 std::string bindir(buf);
442
443 // Find share directory from these.
444 // It is identified by containing the subdirectory "builtin".
445 std::list<std::string> trylist;
446 std::string static_sharedir = STATIC_SHAREDIR;
447 if (!static_sharedir.empty() && static_sharedir != ".")
448 trylist.push_back(static_sharedir);
449
450 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
451 DIR_DELIM + PROJECT_NAME);
452 trylist.push_back(bindir + DIR_DELIM "..");
453
454 #ifdef __ANDROID__
455 trylist.push_back(path_user);
456 #endif
457
458 for (std::list<std::string>::const_iterator
459 i = trylist.begin(); i != trylist.end(); ++i) {
460 const std::string &trypath = *i;
461 if (!fs::PathExists(trypath) ||
462 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
463 warningstream << "system-wide share not found at \""
464 << trypath << "\""<< std::endl;
465 continue;
466 }
467
468 // Warn if was not the first alternative
469 if (i != trylist.begin()) {
470 warningstream << "system-wide share found at \""
471 << trypath << "\"" << std::endl;
472 }
473
474 path_share = trypath;
475 break;
476 }
477
478 #ifndef __ANDROID__
479 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
480 + PROJECT_NAME;
481 #endif
482
483 return true;
484 }
485
486
487 //// Mac OS X
488 #elif defined(__APPLE__)
489
setSystemPaths()490 bool setSystemPaths()
491 {
492 CFBundleRef main_bundle = CFBundleGetMainBundle();
493 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
494 char path[PATH_MAX];
495 if (CFURLGetFileSystemRepresentation(resources_url,
496 TRUE, (UInt8 *)path, PATH_MAX)) {
497 path_share = std::string(path);
498 } else {
499 warningstream << "Could not determine bundle resource path" << std::endl;
500 }
501 CFRelease(resources_url);
502
503 path_user = std::string(getHomeOrFail())
504 + "/Library/Application Support/"
505 + PROJECT_NAME;
506 return true;
507 }
508
509
510 #else
511
setSystemPaths()512 bool setSystemPaths()
513 {
514 path_share = STATIC_SHAREDIR;
515 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
516 + lowercase(PROJECT_NAME);
517 return true;
518 }
519
520
521 #endif
522
migrateCachePath()523 void migrateCachePath()
524 {
525 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
526
527 // Delete tmp folder if it exists (it only ever contained
528 // a temporary ogg file, which is no longer used).
529 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
530 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
531
532 // Bail if migration impossible
533 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
534 || fs::PathExists(path_cache)) {
535 return;
536 }
537 if (!fs::Rename(local_cache_path, path_cache)) {
538 errorstream << "Failed to migrate local cache path "
539 "to system path!" << std::endl;
540 }
541 }
542
initializePaths()543 void initializePaths()
544 {
545 #if RUN_IN_PLACE
546 char buf[BUFSIZ];
547
548 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
549
550 bool success =
551 getCurrentExecPath(buf, sizeof(buf)) ||
552 getExecPathFromProcfs(buf, sizeof(buf));
553
554 if (success) {
555 pathRemoveFile(buf, DIR_DELIM_CHAR);
556 std::string execpath(buf);
557
558 path_share = execpath + DIR_DELIM "..";
559 path_user = execpath + DIR_DELIM "..";
560
561 if (detectMSVCBuildDir(execpath)) {
562 path_share += DIR_DELIM "..";
563 path_user += DIR_DELIM "..";
564 }
565 } else {
566 errorstream << "Failed to get paths by executable location, "
567 "trying cwd" << std::endl;
568
569 if (!getCurrentWorkingDir(buf, sizeof(buf)))
570 FATAL_ERROR("Ran out of methods to get paths");
571
572 size_t cwdlen = strlen(buf);
573 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
574 cwdlen--;
575 buf[cwdlen] = '\0';
576 }
577
578 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
579 pathRemoveFile(buf, DIR_DELIM_CHAR);
580
581 std::string execpath(buf);
582
583 path_share = execpath;
584 path_user = execpath;
585 }
586 path_cache = path_user + DIR_DELIM + "cache";
587 #else
588 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
589
590 if (!setSystemPaths())
591 errorstream << "Failed to get one or more system-wide path" << std::endl;
592
593
594 # ifdef _WIN32
595 path_cache = path_user + DIR_DELIM + "cache";
596 # else
597 // Initialize path_cache
598 // First try $XDG_CACHE_HOME/PROJECT_NAME
599 const char *cache_dir = getenv("XDG_CACHE_HOME");
600 const char *home_dir = getenv("HOME");
601 if (cache_dir) {
602 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
603 } else if (home_dir) {
604 // Then try $HOME/.cache/PROJECT_NAME
605 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
606 + DIR_DELIM + PROJECT_NAME;
607 } else {
608 // If neither works, use $PATH_USER/cache
609 path_cache = path_user + DIR_DELIM + "cache";
610 }
611 // Migrate cache folder to new location if possible
612 migrateCachePath();
613 # endif // _WIN32
614 #endif // RUN_IN_PLACE
615
616 infostream << "Detected share path: " << path_share << std::endl;
617 infostream << "Detected user path: " << path_user << std::endl;
618 infostream << "Detected cache path: " << path_cache << std::endl;
619
620 #if USE_GETTEXT
621 bool found_localedir = false;
622 # ifdef STATIC_LOCALEDIR
623 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
624 * doesn't necessarily contain our locale files, so check data path first. */
625 path_locale = getDataPath("locale");
626 if (fs::PathExists(path_locale)) {
627 found_localedir = true;
628 infostream << "Using in-place locale directory " << path_locale
629 << " even though a static one was provided." << std::endl;
630 } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
631 found_localedir = true;
632 path_locale = STATIC_LOCALEDIR;
633 infostream << "Using static locale directory " << STATIC_LOCALEDIR
634 << std::endl;
635 }
636 # else
637 path_locale = getDataPath("locale");
638 if (fs::PathExists(path_locale)) {
639 found_localedir = true;
640 }
641 # endif
642 if (!found_localedir) {
643 warningstream << "Couldn't find a locale directory!" << std::endl;
644 }
645 #endif // USE_GETTEXT
646 }
647
648 ////
649 //// OS-specific Secure Random
650 ////
651
652 #ifdef WIN32
653
secure_rand_fill_buf(void * buf,size_t len)654 bool secure_rand_fill_buf(void *buf, size_t len)
655 {
656 HCRYPTPROV wctx;
657
658 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
659 return false;
660
661 CryptGenRandom(wctx, len, (BYTE *)buf);
662 CryptReleaseContext(wctx, 0);
663 return true;
664 }
665
666 #else
667
secure_rand_fill_buf(void * buf,size_t len)668 bool secure_rand_fill_buf(void *buf, size_t len)
669 {
670 // N.B. This function checks *only* for /dev/urandom, because on most
671 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
672 // is exceptionally uncommon for there to be a situation where /dev/random
673 // exists but /dev/urandom does not. This guesswork is necessary since
674 // random devices are not covered by any POSIX standard...
675 FILE *fp = fopen("/dev/urandom", "rb");
676 if (!fp)
677 return false;
678
679 bool success = fread(buf, len, 1, fp) == 1;
680
681 fclose(fp);
682 return success;
683 }
684
685 #endif
686
attachOrCreateConsole()687 void attachOrCreateConsole()
688 {
689 #ifdef _WIN32
690 static bool consoleAllocated = false;
691 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
692 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
693 freopen("CONOUT$", "w", stdout);
694 freopen("CONOUT$", "w", stderr);
695 consoleAllocated = true;
696 }
697 #endif
698 }
699
mt_snprintf(char * buf,const size_t buf_size,const char * fmt,...)700 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
701 {
702 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
703 // Many of the MSVC / Windows printf-style functions do not support positional
704 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
705 // platforms, but defer to _vsprintf_p on MSVC / Windows.
706 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
707 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
708 // above FFmpeg link).
709 va_list args;
710 va_start(args, fmt);
711 #ifndef _MSC_VER
712 int c = vsnprintf(buf, buf_size, fmt, args);
713 #else // _MSC_VER
714 int c = _vsprintf_p(buf, buf_size, fmt, args);
715 if (c == -1)
716 c = _vscprintf_p(fmt, args);
717 #endif // _MSC_VER
718 va_end(args);
719 return c;
720 }
721
open_uri(const std::string & uri)722 static bool open_uri(const std::string &uri)
723 {
724 if (uri.find_first_of("\r\n") != std::string::npos) {
725 errorstream << "Unable to open URI as it is invalid, contains new line: " << uri << std::endl;
726 return false;
727 }
728
729 #if defined(_WIN32)
730 return (intptr_t)ShellExecuteA(NULL, NULL, uri.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
731 #elif defined(__ANDROID__)
732 openURIAndroid(uri);
733 return true;
734 #elif defined(__APPLE__)
735 const char *argv[] = {"open", uri.c_str(), NULL};
736 return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv,
737 (*_NSGetEnviron())) == 0;
738 #else
739 const char *argv[] = {"xdg-open", uri.c_str(), NULL};
740 return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
741 #endif
742 }
743
open_url(const std::string & url)744 bool open_url(const std::string &url)
745 {
746 if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") {
747 errorstream << "Unable to open browser as URL is missing schema: " << url << std::endl;
748 return false;
749 }
750
751 return open_uri(url);
752 }
753
open_directory(const std::string & path)754 bool open_directory(const std::string &path)
755 {
756 if (!fs::IsDir(path)) {
757 errorstream << "Unable to open directory as it does not exist: " << path << std::endl;
758 return false;
759 }
760
761 return open_uri(path);
762 }
763
764 // Load performance counter frequency only once at startup
765 #ifdef _WIN32
766
get_perf_freq()767 inline double get_perf_freq()
768 {
769 LARGE_INTEGER freq;
770 QueryPerformanceFrequency(&freq);
771 return freq.QuadPart;
772 }
773
774 double perf_freq = get_perf_freq();
775
776 #endif
777
778 } //namespace porting
779