]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
Revert "Redirect stdin/stderr/stdout to /dev/null in daemon mode"
[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(__APPLE__)
29         #include <mach-o/dyld.h>
30         #include "CoreFoundation/CoreFoundation.h"
31 #elif defined(__FreeBSD__)
32         #include <sys/types.h>
33         #include <sys/sysctl.h>
34 #elif defined(_WIN32)
35         #include <algorithm>
36 #elif defined(__LINUX)
37         #include <sys/types.h>
38 #endif
39 #if !defined(_WIN32)
40         #include <sys/stat.h>
41         #include <unistd.h>
42         #include <sys/utsname.h>
43 #endif
44
45 #include "config.h"
46 #include "debug.h"
47 #include "filesys.h"
48 #include "log.h"
49 #include "util/string.h"
50 #include "main.h"
51 #include "settings.h"
52 #include <list>
53
54 namespace porting
55 {
56
57 /*
58         Signal handler (grabs Ctrl-C on POSIX systems)
59 */
60
61 bool g_killed = false;
62
63 bool * signal_handler_killstatus(void)
64 {
65         return &g_killed;
66 }
67
68 #if !defined(_WIN32) // POSIX
69         #include <signal.h>
70
71 void sigint_handler(int sig)
72 {
73         if(g_killed == false)
74         {
75                 dstream<<DTIME<<"INFO: sigint_handler(): "
76                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
77
78                 // Comment out for less clutter when testing scripts
79                 /*dstream<<DTIME<<"INFO: sigint_handler(): "
80                                 <<"Printing debug stacks"<<std::endl;
81                 debug_stacks_print();*/
82
83                 g_killed = true;
84         }
85         else
86         {
87                 (void)signal(SIGINT, SIG_DFL);
88         }
89 }
90
91 void signal_handler_init(void)
92 {
93         (void)signal(SIGINT, sigint_handler);
94 }
95
96 #else // _WIN32
97         #include <signal.h>
98
99         BOOL WINAPI event_handler(DWORD sig)
100         {
101                 switch(sig)
102                 {
103                 case CTRL_C_EVENT:
104                 case CTRL_CLOSE_EVENT:
105                 case CTRL_LOGOFF_EVENT:
106                 case CTRL_SHUTDOWN_EVENT:
107
108                         if(g_killed == false)
109                         {
110                                 dstream<<DTIME<<"INFO: event_handler(): "
111                                                 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
112                                 // Comment out for less clutter when testing scripts
113                                 /*dstream<<DTIME<<"INFO: event_handler(): "
114                                                 <<"Printing debug stacks"<<std::endl;
115                                 debug_stacks_print();*/
116
117                                 g_killed = true;
118                         }
119                         else
120                         {
121                                 (void)signal(SIGINT, SIG_DFL);
122                         }
123
124                         break;
125                 case CTRL_BREAK_EVENT:
126                         break;
127                 }
128
129                 return TRUE;
130         }
131
132 void signal_handler_init(void)
133 {
134         SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
135 }
136
137 #endif
138
139
140 /*
141         Multithreading support
142 */
143 int getNumberOfProcessors()
144 {
145 #if defined(_SC_NPROCESSORS_ONLN)
146
147         return sysconf(_SC_NPROCESSORS_ONLN);
148
149 #elif defined(__FreeBSD__) || defined(__APPLE__)
150
151         unsigned int len, count;
152         len = sizeof(count);
153         return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
154
155 #elif defined(_GNU_SOURCE)
156
157         return get_nprocs();
158
159 #elif defined(_WIN32)
160
161         SYSTEM_INFO sysinfo;
162         GetSystemInfo(&sysinfo);
163         return sysinfo.dwNumberOfProcessors;
164
165 #elif defined(PTW32_VERSION) || defined(__hpux)
166
167         return pthread_num_processors_np();
168
169 #else
170
171         return 1;
172
173 #endif
174 }
175
176
177 bool threadBindToProcessor(threadid_t tid, int pnumber)
178 {
179 #if defined(_WIN32)
180
181         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
182         if (!hThread)
183                 return false;
184
185         bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
186
187         CloseHandle(hThread);
188         return success;
189
190 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
191         || defined(__linux) || defined(linux)
192
193         cpu_set_t cpuset;
194
195         CPU_ZERO(&cpuset);
196         CPU_SET(pnumber, &cpuset);
197         return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
198
199 #elif defined(__sun) || defined(sun)
200
201         return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
202                                                 pnumber, NULL) == 0;
203
204 #elif defined(_AIX)
205         
206         return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
207
208 #elif defined(__hpux) || defined(hpux)
209
210         pthread_spu_t answer;
211
212         return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
213                                                                         &answer, pnumber, tid) == 0;
214         
215 #elif defined(__APPLE__)
216
217         struct thread_affinity_policy tapol;
218         
219         thread_port_t threadport = pthread_mach_thread_np(tid);
220         tapol.affinity_tag = pnumber + 1;
221         return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
222                         (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
223
224 #else
225
226         return false;
227
228 #endif
229 }
230
231
232 bool threadSetPriority(threadid_t tid, int prio)
233 {
234 #if defined(_WIN32)
235
236         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
237         if (!hThread)
238                 return false;
239
240         bool success = SetThreadPriority(hThread, prio) != 0;
241
242         CloseHandle(hThread);
243         return success;
244         
245 #else
246
247         struct sched_param sparam;
248         int policy;
249         
250         if (pthread_getschedparam(tid, &policy, &sparam) != 0)
251                 return false;
252                 
253         int min = sched_get_priority_min(policy);
254         int max = sched_get_priority_max(policy);
255
256         sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
257         return pthread_setschedparam(tid, policy, &sparam) == 0;
258         
259 #endif
260 }
261
262
263 /*
264         Path mangler
265 */
266
267 // Default to RUN_IN_PLACE style relative paths
268 std::string path_share = "..";
269 std::string path_user = "..";
270
271 std::string getDataPath(const char *subpath)
272 {
273         return path_share + DIR_DELIM + subpath;
274 }
275
276 void pathRemoveFile(char *path, char delim)
277 {
278         // Remove filename and path delimiter
279         int i;
280         for(i = strlen(path)-1; i>=0; i--)
281         {
282                 if(path[i] == delim)
283                         break;
284         }
285         path[i] = 0;
286 }
287
288 bool detectMSVCBuildDir(char *c_path)
289 {
290         std::string path(c_path);
291         const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
292         return (removeStringEnd(path, ends) != "");
293 }
294
295 std::string get_sysinfo()
296 {
297 #ifdef _WIN32
298         OSVERSIONINFO osvi;
299         std::ostringstream oss;
300         std::string tmp;
301         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
302         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
303         GetVersionEx(&osvi);
304         tmp = osvi.szCSDVersion;
305         std::replace(tmp.begin(), tmp.end(), ' ', '_');
306
307         oss << "Windows/" << osvi.dwMajorVersion << "."
308                 << osvi.dwMinorVersion;
309         if(osvi.szCSDVersion[0])
310                 oss << "-" << tmp;
311         oss << " ";
312         #ifdef _WIN64
313         oss << "x86_64";
314         #else
315         BOOL is64 = FALSE;
316         if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
317                 oss << "x86_64"; // 32-bit app on 64-bit OS
318         else
319                 oss << "x86";
320         #endif
321
322         return oss.str();
323 #else
324         struct utsname osinfo;
325         uname(&osinfo);
326         return std::string(osinfo.sysname) + "/"
327                 + osinfo.release + " " + osinfo.machine;
328 #endif
329 }
330
331 void initializePaths()
332 {
333 #if RUN_IN_PLACE
334         /*
335                 Use relative paths if RUN_IN_PLACE
336         */
337
338         infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
339
340         /*
341                 Windows
342         */
343         #if defined(_WIN32)
344
345         const DWORD buflen = 1000;
346         char buf[buflen];
347         DWORD len;
348
349         // Find path of executable and set path_share relative to it
350         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
351         assert(len < buflen);
352         pathRemoveFile(buf, '\\');
353
354         if(detectMSVCBuildDir(buf)){
355                 infostream<<"MSVC build directory detected"<<std::endl;
356                 path_share = std::string(buf) + "\\..\\..";
357                 path_user = std::string(buf) + "\\..\\..";
358         }
359         else{
360                 path_share = std::string(buf) + "\\..";
361                 path_user = std::string(buf) + "\\..";
362         }
363
364         /*
365                 Linux
366         */
367         #elif defined(linux)
368
369         char buf[BUFSIZ];
370         memset(buf, 0, BUFSIZ);
371         // Get path to executable
372         assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
373
374         pathRemoveFile(buf, '/');
375
376         path_share = std::string(buf) + "/..";
377         path_user = std::string(buf) + "/..";
378
379         /*
380                 OS X
381         */
382         #elif defined(__APPLE__)
383
384         //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
385         //TODO: Test this code
386         char buf[BUFSIZ];
387         uint32_t len = sizeof(buf);
388         assert(_NSGetExecutablePath(buf, &len) != -1);
389
390         pathRemoveFile(buf, '/');
391
392         path_share = std::string(buf) + "/..";
393         path_user = std::string(buf) + "/..";
394
395         /*
396                 FreeBSD
397         */
398         #elif defined(__FreeBSD__)
399
400         int mib[4];
401         char buf[BUFSIZ];
402         size_t len = sizeof(buf);
403
404         mib[0] = CTL_KERN;
405         mib[1] = KERN_PROC;
406         mib[2] = KERN_PROC_PATHNAME;
407         mib[3] = -1;
408         assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
409
410         pathRemoveFile(buf, '/');
411
412         path_share = std::string(buf) + "/..";
413         path_user = std::string(buf) + "/..";
414
415         #else
416
417         //TODO: Get path of executable. This assumes working directory is bin/
418         dstream<<"WARNING: Relative path not properly supported on this platform"
419                         <<std::endl;
420
421         /* scriptapi no longer allows paths that start with "..", so assuming that
422            the current working directory is bin/, strip off the last component. */
423         char *cwd = getcwd(NULL, 0);
424         pathRemoveFile(cwd, '/');
425         path_share = std::string(cwd);
426         path_user = std::string(cwd);
427
428         #endif
429
430 #else // RUN_IN_PLACE
431
432         /*
433                 Use platform-specific paths otherwise
434         */
435
436         infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
437
438         /*
439                 Windows
440         */
441         #if defined(_WIN32)
442
443         const DWORD buflen = 1000;
444         char buf[buflen];
445         DWORD len;
446
447         // Find path of executable and set path_share relative to it
448         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
449         assert(len < buflen);
450         pathRemoveFile(buf, '\\');
451
452         // Use ".\bin\.."
453         path_share = std::string(buf) + "\\..";
454
455         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
456         len = GetEnvironmentVariable("APPDATA", buf, buflen);
457         assert(len < buflen);
458         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
459
460         /*
461                 Linux
462         */
463         #elif defined(linux)
464
465         // Get path to executable
466         std::string bindir = "";
467         {
468                 char buf[BUFSIZ];
469                 memset(buf, 0, BUFSIZ);
470                 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
471                 pathRemoveFile(buf, '/');
472                 bindir = buf;
473         }
474
475         // Find share directory from these.
476         // It is identified by containing the subdirectory "builtin".
477         std::list<std::string> trylist;
478         std::string static_sharedir = STATIC_SHAREDIR;
479         if(static_sharedir != "" && static_sharedir != ".")
480                 trylist.push_back(static_sharedir);
481         trylist.push_back(
482                         bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
483         trylist.push_back(bindir + DIR_DELIM + "..");
484
485         for(std::list<std::string>::const_iterator i = trylist.begin();
486                         i != trylist.end(); i++)
487         {
488                 const std::string &trypath = *i;
489                 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
490                         dstream<<"WARNING: system-wide share not found at \""
491                                         <<trypath<<"\""<<std::endl;
492                         continue;
493                 }
494                 // Warn if was not the first alternative
495                 if(i != trylist.begin()){
496                         dstream<<"WARNING: system-wide share found at \""
497                                         <<trypath<<"\""<<std::endl;
498                 }
499                 path_share = trypath;
500                 break;
501         }
502
503         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
504
505         /*
506                 OS X
507         */
508         #elif defined(__APPLE__)
509
510         // Code based on
511         // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
512         CFBundleRef main_bundle = CFBundleGetMainBundle();
513         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
514         char path[PATH_MAX];
515         if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
516         {
517                 dstream<<"Bundle resource path: "<<path<<std::endl;
518                 //chdir(path);
519                 path_share = std::string(path) + DIR_DELIM + "share";
520         }
521         else
522         {
523                 // error!
524                 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
525         }
526         CFRelease(resources_url);
527
528         path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
529
530         #else // FreeBSD, and probably many other POSIX-like systems.
531
532         path_share = STATIC_SHAREDIR;
533         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
534
535         #endif
536
537 #endif // RUN_IN_PLACE
538 }
539
540 static irr::IrrlichtDevice* device;
541
542 void initIrrlicht(irr::IrrlichtDevice * _device)
543 {
544         device = _device;
545 }
546
547 #ifndef SERVER
548 v2u32 getWindowSize()
549 {
550         return device->getVideoDriver()->getScreenSize();
551 }
552
553
554 float getDisplayDensity()
555 {
556         float gui_scaling = g_settings->getFloat("gui_scaling");
557         // using Y here feels like a bug, this needs to be discussed later!
558         if (getWindowSize().Y <= 800) {
559                 return (2.0/3.0) * gui_scaling;
560         }
561         if (getWindowSize().Y <= 1280) {
562                 return 1.0 * gui_scaling;
563         }
564
565         return (4.0/3.0) * gui_scaling;
566 }
567
568 v2u32 getDisplaySize()
569 {
570         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
571
572         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
573         nulldevice -> drop();
574
575         return deskres;
576 }
577 #endif
578
579 #ifdef SERVER
580 #ifdef _WIN32
581 void daemonize()
582 {
583         errorstream << "daemonize not implemented on windows" << std::endl;
584 }
585 #else // assume posix like os
586
587 static std::string get_pidfile_path()
588 {
589         // make it static to make sure it won't change after first call to this fct
590         static std::string path_pidfile = "";
591         static bool initialized = false;
592
593         if (initialized)
594         {
595                 return path_pidfile;
596         }
597
598         g_settings->getNoEx("pidfile", path_pidfile);
599
600         if (path_pidfile == "") {
601 #ifdef RUN_IN_PLACE
602                 path_pidfile = "pidfile.pid";
603 #else
604                 path_pidfile = "/var/run/minetest.pid";
605 #endif
606         }
607         initialized = true;
608         return path_pidfile;
609 }
610
611
612 void daemonize()
613 {
614         std::string path_pidfile = get_pidfile_path();
615
616         FILE* pidfile = fopen(path_pidfile.c_str(),"r");
617
618         if (pidfile) {
619                 int pid = 0;
620                 if (fscanf(pidfile, "%i", &pid) == 1) {
621                         if (kill(pid, 0) == 0) {
622                                 errorstream <<
623                                                 "Minetestserver is already running with pid: "
624                                                 << pid << std::endl;
625                                 exit(-1);
626                         }
627                 } else {
628                         errorstream << "Pidfile \"" << path_pidfile << "\" "
629                                         "already exists but content is invalid" << std::endl <<
630                                         "Delete it manually if you're sure minetest isn't running!"
631                                         << std::endl;
632                         exit(-1);
633                 }
634                 fclose(pidfile);
635                 pidfile = 0;
636         }
637
638         pid_t pid = fork();
639
640         if (pid > 0) {
641                 pidfile = fopen(path_pidfile.c_str(),"w+");
642                 if (pidfile) {
643                         fprintf(pidfile,"%i",pid);
644                         fclose(pidfile);
645                 } else {
646                         errorstream << "Failed to create pidfile: \"" << path_pidfile
647                                         << "\""<< std::endl;
648                 }
649                 exit (0);
650         } else if (pid == 0) {
651                 fclose(stdout);
652                 fclose(stderr);
653                 return;
654         }
655
656         errorstream << "Failed to daemonize minetest, exiting" << std::endl;
657         exit(-1);
658 }
659
660 void cleanup_pid()
661 {
662         unlink(get_pidfile_path().c_str());
663 }
664 #endif
665 #endif
666
667 } //namespace porting
668