2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2000-2021 DarkPlaces contributors
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
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.
14 See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 // host.c -- coordinates spawning and killing of local servers
27 #include "taskqueue.h"
32 A server can always be started, even if the system started out as a client
35 A client can NOT be started if the system started as a dedicated server.
37 Memory is cleared / released when a server or client begins, not when they end.
43 // pretend frames take this amount of time (in seconds), 0 = realtime
44 cvar_t host_framerate = {CF_CLIENT | CF_SERVER, "host_framerate","0", "locks frame timing to this value in seconds, 0.05 is 20fps for example, note that this can easily run too fast, use cl_maxfps if you want to limit your framerate instead, or sys_ticrate to limit server speed"};
45 // shows time used by certain subsystems
46 cvar_t host_speeds = {CF_CLIENT | CF_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
47 cvar_t host_maxwait = {CF_CLIENT | CF_SERVER, "host_maxwait","1000", "maximum sleep time requested from the operating system in millisecond. Larger sleeps will be done using multiple host_maxwait length sleeps. Lowering this value will increase CPU load, but may help working around problems with accuracy of sleep times."};
49 cvar_t developer = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "developer","0", "shows debugging messages and information (recommended for all developers and level designers); the value -1 also suppresses buffering and logging these messages"};
50 cvar_t developer_extra = {CF_CLIENT | CF_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
51 cvar_t developer_insane = {CF_CLIENT | CF_SERVER, "developer_insane", "0", "prints huge streams of information about internal workings, entire contents of files being read/written, etc. Not recommended!"};
52 cvar_t developer_loadfile = {CF_CLIENT | CF_SERVER, "developer_loadfile","0", "prints name and size of every file loaded via the FS_LoadFile function (which is almost everything)"};
53 cvar_t developer_loading = {CF_CLIENT | CF_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
54 cvar_t developer_entityparsing = {CF_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
56 cvar_t timestamps = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timestamps", "0", "prints timestamps on console messages"};
57 cvar_t timeformat = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
59 cvar_t sessionid = {CF_CLIENT | CF_SERVER | CF_READONLY, "sessionid", "", "ID of the current session (use the -sessionid parameter to set it); this is always either empty or begins with a dot (.)"};
60 cvar_t locksession = {CF_CLIENT | CF_SERVER, "locksession", "0", "Lock the session? 0 = no, 1 = yes and abort on failure, 2 = yes and continue on failure"};
62 cvar_t host_isclient = {CF_SHARED | CF_READONLY, "_host_isclient", "0", "If 1, clientside is active."};
66 Host_AbortCurrentFrame
68 aborts the current host frame and goes on with the next one
71 void Host_AbortCurrentFrame(void)
73 // in case we were previously nice, make us mean again
74 Sys_MakeProcessMean();
76 longjmp (host.abortframe, 1);
83 This shuts down both the client and server
86 void Host_Error (const char *error, ...)
88 static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
89 static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
90 static qbool hosterror = false;
92 int outfd = sys.outfd;
94 // set output to stderr
95 sys.outfd = fileno(stderr);
97 // turn off rcon redirect if it was active when the crash occurred
98 // to prevent loops when it is a networking problem
99 Con_Rcon_Redirect_Abort();
101 va_start (argptr,error);
102 dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
105 Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
107 // LadyHavoc: if crashing very early, or currently shutting down, do
109 if (host.framecount < 3 || host.state == host_shutdown)
110 Sys_Abort ("Host_Error during %s: %s", host.framecount < 3 ? "startup" : "shutdown", hosterrorstring1);
113 Sys_Abort ("Host_Error: recursively entered (original error was: %s new error is: %s)", hosterrorstring2, hosterrorstring1);
116 dp_strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
118 CL_Parse_DumpPacket();
120 CL_Parse_ErrorCleanUp();
124 // print out where the crash happened, if it was caused by QC (and do a cleanup)
125 PRVM_Crash(SVVM_prog);
126 PRVM_Crash(CLVM_prog);
128 PRVM_Crash(MVM_prog);
131 Cvar_SetValueQuick(&csqc_progcrc, -1);
132 Cvar_SetValueQuick(&csqc_progsize, -1);
134 if(host.hook.SV_Shutdown)
135 host.hook.SV_Shutdown();
137 if (cls.state == ca_dedicated)
138 Sys_Abort ("Host_Error: %s",hosterrorstring2); // dedicated servers exit
140 // prevent an endless loop if the error was triggered by a command
141 Cbuf_Clear(cmd_local->cbuf);
143 // DP8 TODO: send a disconnect message indicating we errored out, see Sys_Abort() and Sys_HandleCrash()
149 // restore configured outfd
152 Host_AbortCurrentFrame();
160 static void Host_Quit_f(cmd_state_t *cmd)
162 if(host.state == host_shutdown)
163 Con_Printf("shutting down already!\n");
165 host.state = host_shutdown;
168 static void Host_Version_f(cmd_state_t *cmd)
170 Con_Printf("Version: %s\n", engineversion);
173 static void Host_Framerate_c(cvar_t *var)
175 if (var->value < 0.00001 && var->value != 0)
176 Cvar_SetValueQuick(var, 0);
179 // TODO: Find a better home for this.
180 static void SendCvar_f(cmd_state_t *cmd)
182 if(cmd->source == src_local && host.hook.SV_SendCvar)
184 host.hook.SV_SendCvar(cmd);
187 if(cmd->source == src_client && host.hook.CL_SendCvar)
189 host.hook.CL_SendCvar(cmd);
198 Writes key bindings and archived cvars to config.cfg
201 void Host_SaveConfig(const char *file)
205 // dedicated servers initialize the host but don't parse and set the
207 // LadyHavoc: don't save a config if it crashed in startup
208 if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
210 f = FS_OpenRealFile(file, "wb", false);
213 Con_Printf(CON_ERROR "Couldn't write %s\n", file);
217 Con_Printf("Saving config to %s ...\n", file);
219 Key_WriteBindings (f);
220 Cvar_WriteVariables (&cvars_all, f);
226 static void Host_SaveConfig_f(cmd_state_t *cmd)
228 const char *file = CONFIGFILENAME;
230 if(Cmd_Argc(cmd) >= 2)
231 file = Cmd_Argv(cmd, 1);
233 Host_SaveConfig(file);
236 static void Host_AddConfigText(cmd_state_t *cmd)
238 // set up the default startmap_sp and startmap_dm aliases (mods can
239 // override these) and then execute the quake.rc startup script
240 if (gamemode == GAME_NEHAHRA)
241 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
242 else if (gamemode == GAME_TRANSFUSION)
243 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
244 else if (gamemode == GAME_TEU)
245 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
247 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
248 Cbuf_Execute(cmd->cbuf);
255 Resets key bindings and cvars to defaults and then reloads scripts
258 static void Host_LoadConfig_f(cmd_state_t *cmd)
260 // reset all cvars, commands and aliases to init values
261 Cmd_RestoreInitState();
263 // prepend a menu restart command to execute after the config
264 Cbuf_InsertText(cmd_local, "\nmenu_restart\n");
266 // reset cvars to their defaults, and then exec startup scripts again
267 Host_AddConfigText(cmd_local);
271 =======================
273 ======================
275 extern cvar_t r_texture_jpeg_fastpicmip;
276 static void Host_InitLocal (void)
278 Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
279 Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
280 Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
281 Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
282 Cmd_AddCommand(CF_SHARED, "sendcvar", SendCvar_f, "sends the value of a cvar to the server as a sentcvar command, for use by QuakeC");
283 Cvar_RegisterVariable (&host_framerate);
284 Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
285 Cvar_RegisterVariable (&host_speeds);
286 Cvar_RegisterVariable (&host_maxwait);
287 Cvar_RegisterVariable (&host_isclient);
289 Cvar_RegisterVariable (&developer);
290 Cvar_RegisterVariable (&developer_extra);
291 Cvar_RegisterVariable (&developer_insane);
292 Cvar_RegisterVariable (&developer_loadfile);
293 Cvar_RegisterVariable (&developer_loading);
294 Cvar_RegisterVariable (&developer_entityparsing);
296 Cvar_RegisterVariable (×tamps);
297 Cvar_RegisterVariable (&timeformat);
299 Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
302 char engineversion[128];
305 static qfile_t *locksession_fh = NULL;
306 static qbool locksession_run = false;
307 static void Host_InitSession(void)
311 Cvar_RegisterVariable(&sessionid);
312 Cvar_RegisterVariable(&locksession);
314 // load the session ID into the read-only cvar
315 if ((i = Sys_CheckParm("-sessionid")) && (i + 1 < sys.argc))
317 if(sys.argv[i+1][0] == '.')
318 Cvar_SetQuick(&sessionid, sys.argv[i+1]);
321 buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
322 dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
323 Cvar_SetQuick(&sessionid, buf);
328 void Host_LockSession(void)
332 locksession_run = true;
333 if(locksession.integer != 0 && !Sys_CheckParm("-readonly"))
336 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
338 locksession_fh = FS_SysOpen(p, "wl", false);
339 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
342 if(locksession.integer == 2)
344 Con_Printf(CON_WARN "WARNING: session lock %s could not be acquired. Please run with -sessionid and an unique session name. Continuing anyway.\n", p);
348 Sys_Abort("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
354 void Host_UnlockSession(void)
358 locksession_run = false;
362 FS_Close(locksession_fh);
363 // NOTE: we can NOT unlink the lock here, as doing so would
364 // create a race condition if another process created it
365 // between our close and our unlink
366 locksession_fh = NULL;
375 static void Host_Init (void)
384 host.hook.ConnectLocal = NULL;
385 host.hook.Disconnect = NULL;
386 host.hook.ToggleMenu = NULL;
387 host.hook.CL_Intermission = NULL;
388 host.hook.SV_Shutdown = NULL;
390 host.state = host_init;
392 if (setjmp(host.abortframe)) // Huh?!
393 Sys_Abort("Engine initialization failed. Check the console (if available) for additional information.\n");
395 if (Sys_CheckParm("-profilegameonly"))
396 Sys_AllowProfiling(false);
398 // LadyHavoc: quake never seeded the random number generator before... heh
399 if (Sys_CheckParm("-benchmark"))
400 srand(0); // predictable random sequence for -benchmark
402 srand((unsigned int)time(NULL));
404 // FIXME: this is evil, but possibly temporary
405 // LadyHavoc: doesn't seem very temporary...
406 // LadyHavoc: made this a saved cvar
407 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
408 if (Sys_CheckParm("-developer"))
410 developer.value = developer.integer = 1;
411 developer.string = "1";
414 if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
416 developer.value = developer.integer = 1;
417 developer.string = "1";
418 developer_extra.value = developer_extra.integer = 1;
419 developer_extra.string = "1";
420 developer_insane.value = developer_insane.integer = 1;
421 developer_insane.string = "1";
422 developer_memory.value = developer_memory.integer = 1;
423 developer_memory.string = "1";
424 developer_memorydebug.value = developer_memorydebug.integer = 1;
425 developer_memorydebug.string = "1";
428 if (Sys_CheckParm("-developer3"))
430 gl_paranoid.integer = 1;gl_paranoid.string = "1";
431 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
434 // -dedicated is checked in SV_ServerOptions() but that's too late for Cvar_RegisterVariable() to skip all the client-only cvars
435 if (Sys_CheckParm ("-dedicated") || !cl_available)
436 cls.state = ca_dedicated;
438 // initialize console command/cvar/alias/command execution systems
441 // initialize memory subsystem cvars/commands
442 Memory_Init_Commands();
444 // initialize console and logging and its cvars/commands
445 // this enables Con_Printf() messages to be coloured
448 // initialize various cvars that could not be initialized earlier
450 Curl_Init_Commands();
454 // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name, gamename)
457 // ASAP! construct a version string for the corner of the console and for crash messages
458 dpsnprintf (engineversion, sizeof (engineversion), "%s %s%s, buildstring: %s", gamename, DP_OS_NAME, cls.state == ca_dedicated ? " dedicated" : "", buildstring);
459 Con_Printf("%s\n", engineversion);
461 // initialize process nice level
462 Sys_InitProcessNice();
464 // initialize ixtable
467 // register the cvars for session locking
470 // must be after FS_Init
472 Crypto_Init_Commands();
487 // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
488 // NOTE: menu commands are freed by Cmd_RestoreInitState
491 // FIXME: put this into some neat design, but the menu should be allowed to crash
492 // without crashing the whole game, so this should just be a short-time solution
494 // here comes the not so critical stuff
496 Host_AddConfigText(cmd_local);
498 // if quake.rc is missing, use default
499 if (!FS_FileExists("quake.rc"))
501 Cbuf_AddText(cmd_local, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
502 Cbuf_Execute(cmd_local->cbuf);
505 host.state = host_active;
511 if (cls.state != ca_dedicated)
513 // put up the loading image so the user doesn't stare at a black screen...
514 SCR_BeginLoadingPlaque(true);
521 // check for special benchmark mode
522 // COMMANDLINEOPTION: Client: -benchmark <demoname> runs a timedemo and quits, results of any timedemo can be found in gamedir/benchmark.log (for example id1/benchmark.log)
523 i = Sys_CheckParm("-benchmark");
524 if (i && i + 1 < sys.argc)
525 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
527 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
528 Cbuf_Execute(cmd_local->cbuf);
531 // check for special demo mode
532 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
533 i = Sys_CheckParm("-demo");
534 if (i && i + 1 < sys.argc)
535 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
537 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
538 Cbuf_Execute(cmd_local->cbuf);
541 #ifdef CONFIG_VIDEO_CAPTURE
542 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
543 i = Sys_CheckParm("-capturedemo");
544 if (i && i + 1 < sys.argc)
545 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
547 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
548 Cbuf_Execute((cmd_local)->cbuf);
552 if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
553 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
555 Cbuf_AddText(cmd_local, "startmap_dm\n");
556 Cbuf_Execute(cmd_local->cbuf);
559 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
562 Cbuf_AddText(cmd_local, "togglemenu 1\n");
564 Cbuf_Execute(cmd_local->cbuf);
567 Con_DPrint("========Initialized=========\n");
569 if (cls.state != ca_dedicated)
577 Cleanly shuts down after the main loop exits.
580 static void Host_Shutdown(void)
582 if (Sys_CheckParm("-profilegameonly"))
583 Sys_AllowProfiling(false);
585 if(cls.state != ca_dedicated)
588 // end the server thread
592 // shut down local server if active
593 if(host.hook.SV_Shutdown)
594 host.hook.SV_Shutdown();
597 // AK hmm, no PRVM_Shutdown(); yet
599 Host_SaveConfig(CONFIGFILENAME);
605 TaskQueue_Shutdown();
612 Host_UnlockSession();
618 //============================================================================
624 Runs all active servers
627 static double Host_Frame(double time)
629 double cl_wait, sv_wait;
631 TaskQueue_Frame(false);
633 // keep the random time dependent, but not when playing demos/benchmarking
634 if(!*sv_random_seed.string && !host.restless)
637 NetConn_UpdateSockets();
639 Log_DestBuffer_Flush();
644 // get new SDL events and add commands from keybindings to the cbuf
645 Sys_SDL_HandleEvents();
647 // process console commands
648 Cbuf_Frame(host.cbuf);
652 // if the accumulators haven't become positive yet, wait a while
653 sv_wait = - SV_Frame(time);
654 cl_wait = - CL_Frame(time);
656 Mem_CheckSentinelsGlobal();
658 if (cls.state == ca_dedicated)
659 return sv_wait; // dedicated
660 else if (!sv.active || svs.threaded)
661 return cl_wait; // connected to server, main menu, or server is on different thread
663 return min(cl_wait, sv_wait); // listen server or singleplayer
666 // Cloudwalk: Most overpowered function declaration...
667 static inline double Host_UpdateTime (double newtime, double oldtime)
669 double time = newtime - oldtime;
673 // warn if it's significant
675 Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
678 else if (time >= 1800)
680 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
689 double time, oldtime, sleeptime;
691 Host_Init(); // Start!
694 oldtime = Sys_DirtyTime();
697 while(host.state != host_shutdown)
699 // Something bad happened, or the server disconnected
700 if (setjmp(host.abortframe))
702 host.state = host_active; // In case we were loading
706 host.dirtytime = Sys_DirtyTime();
707 host.realtime += time = Host_UpdateTime(host.dirtytime, oldtime);
708 oldtime = host.dirtytime;
710 sleeptime = Host_Frame(time);
712 sleeptime -= Sys_DirtyTime() - host.dirtytime; // execution time
713 host.sleeptime = Sys_Sleep(sleeptime);