]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
PRVM: fix a use of strlcpy on an unterminated source
[xonotic/darkplaces.git] / host.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2000-2021 DarkPlaces contributors
4
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.
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.
13
14 See the GNU General Public License for more details.
15
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.
19
20 */
21 // host.c -- coordinates spawning and killing of local servers
22
23 #include "quakedef.h"
24
25 #include <time.h>
26 #include "libcurl.h"
27 #include "taskqueue.h"
28 #include "utf8lib.h"
29
30 /*
31
32 A server can always be started, even if the system started out as a client
33 to a remote system.
34
35 A client can NOT be started if the system started as a dedicated server.
36
37 Memory is cleared / released when a server or client begins, not when they end.
38
39 */
40
41 host_static_t host;
42
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."};
48
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"};
55
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"};
58
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"};
61
62 cvar_t host_isclient = {CF_SHARED | CF_READONLY, "_host_isclient", "0", "If 1, clientside is active."};
63
64 /*
65 ================
66 Host_AbortCurrentFrame
67
68 aborts the current host frame and goes on with the next one
69 ================
70 */
71 void Host_AbortCurrentFrame(void)
72 {
73         // in case we were previously nice, make us mean again
74         Sys_MakeProcessMean();
75
76         longjmp (host.abortframe, 1);
77 }
78
79 /*
80 ================
81 Host_Error
82
83 This shuts down both the client and server
84 ================
85 */
86 void Host_Error (const char *error, ...)
87 {
88         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
89         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
90         static qbool hosterror = false;
91         va_list argptr;
92         int outfd = sys.outfd;
93
94         // set output to stderr
95         sys.outfd = fileno(stderr);
96
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();
100
101         va_start (argptr,error);
102         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
103         va_end (argptr);
104
105         Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
106
107         // LadyHavoc: if crashing very early, or currently shutting down, do
108         // Sys_Error instead
109         if (host.framecount < 3 || host.state == host_shutdown)
110                 Sys_Error ("Host_Error: %s", hosterrorstring1);
111
112         if (hosterror)
113                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
114         hosterror = true;
115
116         dp_strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
117
118         CL_Parse_DumpPacket();
119
120         CL_Parse_ErrorCleanUp();
121
122         //PR_Crash();
123
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);
127 #ifdef CONFIG_MENU
128         PRVM_Crash(MVM_prog);
129 #endif
130
131         Cvar_SetValueQuick(&csqc_progcrc, -1);
132         Cvar_SetValueQuick(&csqc_progsize, -1);
133
134         if(host.hook.SV_Shutdown)
135                 host.hook.SV_Shutdown();
136
137         if (cls.state == ca_dedicated)
138                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
139
140         // prevent an endless loop if the error was triggered by a command
141         Cbuf_Clear(cmd_local->cbuf);
142
143         CL_Disconnect();
144         cls.demonum = -1;
145
146         hosterror = false;
147
148         // restore configured outfd
149         sys.outfd = outfd;
150
151         Host_AbortCurrentFrame();
152 }
153
154 /*
155 ==================
156 Host_Quit_f
157 ==================
158 */
159 static void Host_Quit_f(cmd_state_t *cmd)
160 {
161         if(host.state == host_shutdown)
162                 Con_Printf("shutting down already!\n");
163         else
164                 host.state = host_shutdown;
165 }
166
167 static void Host_Version_f(cmd_state_t *cmd)
168 {
169         Con_Printf("Version: %s\n", engineversion);
170 }
171
172 static void Host_Framerate_c(cvar_t *var)
173 {
174         if (var->value < 0.00001 && var->value != 0)
175                 Cvar_SetValueQuick(var, 0);
176 }
177
178 // TODO: Find a better home for this.
179 static void SendCvar_f(cmd_state_t *cmd)
180 {
181         if(cmd->source == src_local && host.hook.SV_SendCvar)
182         {
183                 host.hook.SV_SendCvar(cmd);
184                 return;
185         }
186         if(cmd->source == src_client && host.hook.CL_SendCvar)
187         {
188                 host.hook.CL_SendCvar(cmd);
189                 return;
190         }
191 }
192
193 /*
194 ===============
195 Host_SaveConfig_f
196
197 Writes key bindings and archived cvars to config.cfg
198 ===============
199 */
200 void Host_SaveConfig(const char *file)
201 {
202         qfile_t *f;
203
204 // dedicated servers initialize the host but don't parse and set the
205 // config.cfg cvars
206         // LadyHavoc: don't save a config if it crashed in startup
207         if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
208         {
209                 f = FS_OpenRealFile(file, "wb", false);
210                 if (!f)
211                 {
212                         Con_Printf(CON_ERROR "Couldn't write %s\n", file);
213                         return;
214                 }
215                 else
216                         Con_Printf("Saving config to %s ...\n", file);
217
218                 Key_WriteBindings (f);
219                 Cvar_WriteVariables (&cvars_all, f);
220
221                 FS_Close (f);
222         }
223 }
224
225 static void Host_SaveConfig_f(cmd_state_t *cmd)
226 {
227         const char *file = CONFIGFILENAME;
228
229         if(Cmd_Argc(cmd) >= 2)
230                 file = Cmd_Argv(cmd, 1);
231
232         Host_SaveConfig(file);
233 }
234
235 static void Host_AddConfigText(cmd_state_t *cmd)
236 {
237         // set up the default startmap_sp and startmap_dm aliases (mods can
238         // override these) and then execute the quake.rc startup script
239         if (gamemode == GAME_NEHAHRA)
240                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
241         else if (gamemode == GAME_TRANSFUSION)
242                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
243         else if (gamemode == GAME_TEU)
244                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
245         else
246                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
247         Cbuf_Execute(cmd->cbuf);
248 }
249
250 /*
251 ===============
252 Host_LoadConfig_f
253
254 Resets key bindings and cvars to defaults and then reloads scripts
255 ===============
256 */
257 static void Host_LoadConfig_f(cmd_state_t *cmd)
258 {
259         // reset all cvars, commands and aliases to init values
260         Cmd_RestoreInitState();
261 #ifdef CONFIG_MENU
262         // prepend a menu restart command to execute after the config
263         Cbuf_InsertText(cmd_local, "\nmenu_restart\n");
264 #endif
265         // reset cvars to their defaults, and then exec startup scripts again
266         Host_AddConfigText(cmd_local);
267 }
268
269 /*
270 =======================
271 Host_InitLocal
272 ======================
273 */
274 extern cvar_t r_texture_jpeg_fastpicmip;
275 static void Host_InitLocal (void)
276 {
277         Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
278         Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
279         Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
280         Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
281         Cmd_AddCommand(CF_SHARED, "sendcvar", SendCvar_f, "sends the value of a cvar to the server as a sentcvar command, for use by QuakeC");
282         Cvar_RegisterVariable (&host_framerate);
283         Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
284         Cvar_RegisterVariable (&host_speeds);
285         Cvar_RegisterVariable (&host_maxwait);
286         Cvar_RegisterVariable (&host_isclient);
287
288         Cvar_RegisterVariable (&developer);
289         Cvar_RegisterVariable (&developer_extra);
290         Cvar_RegisterVariable (&developer_insane);
291         Cvar_RegisterVariable (&developer_loadfile);
292         Cvar_RegisterVariable (&developer_loading);
293         Cvar_RegisterVariable (&developer_entityparsing);
294
295         Cvar_RegisterVariable (&timestamps);
296         Cvar_RegisterVariable (&timeformat);
297
298         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
299 }
300
301 char engineversion[128];
302
303
304 static qfile_t *locksession_fh = NULL;
305 static qbool locksession_run = false;
306 static void Host_InitSession(void)
307 {
308         int i;
309         char *buf;
310         Cvar_RegisterVariable(&sessionid);
311         Cvar_RegisterVariable(&locksession);
312
313         // load the session ID into the read-only cvar
314         if ((i = Sys_CheckParm("-sessionid")) && (i + 1 < sys.argc))
315         {
316                 if(sys.argv[i+1][0] == '.')
317                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
318                 else
319                 {
320                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
321                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
322                         Cvar_SetQuick(&sessionid, buf);
323                 }
324         }
325 }
326
327 void Host_LockSession(void)
328 {
329         if(locksession_run)
330                 return;
331         locksession_run = true;
332         if(locksession.integer != 0 && !Sys_CheckParm("-readonly"))
333         {
334                 char vabuf[1024];
335                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
336                 FS_CreatePath(p);
337                 locksession_fh = FS_SysOpen(p, "wl", false);
338                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
339                 if(!locksession_fh)
340                 {
341                         if(locksession.integer == 2)
342                         {
343                                 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);
344                         }
345                         else
346                         {
347                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
348                         }
349                 }
350         }
351 }
352
353 void Host_UnlockSession(void)
354 {
355         if(!locksession_run)
356                 return;
357         locksession_run = false;
358
359         if(locksession_fh)
360         {
361                 FS_Close(locksession_fh);
362                 // NOTE: we can NOT unlink the lock here, as doing so would
363                 // create a race condition if another process created it
364                 // between our close and our unlink
365                 locksession_fh = NULL;
366         }
367 }
368
369 /*
370 ====================
371 Host_Init
372 ====================
373 */
374 static void Host_Init (void)
375 {
376         int i;
377         char vabuf[1024];
378
379         Sys_SDL_Init();
380
381         Memory_Init();
382
383         host.hook.ConnectLocal = NULL;
384         host.hook.Disconnect = NULL;
385         host.hook.ToggleMenu = NULL;
386         host.hook.CL_Intermission = NULL;
387         host.hook.SV_Shutdown = NULL;
388
389         host.state = host_init;
390
391         if (setjmp(host.abortframe)) // Huh?!
392                 Sys_Error("Engine initialization failed. Check the console (if available) for additional information.\n");
393
394         if (Sys_CheckParm("-profilegameonly"))
395                 Sys_AllowProfiling(false);
396
397         // LadyHavoc: quake never seeded the random number generator before... heh
398         if (Sys_CheckParm("-benchmark"))
399                 srand(0); // predictable random sequence for -benchmark
400         else
401                 srand((unsigned int)time(NULL));
402
403         // FIXME: this is evil, but possibly temporary
404         // LadyHavoc: doesn't seem very temporary...
405         // LadyHavoc: made this a saved cvar
406 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
407         if (Sys_CheckParm("-developer"))
408         {
409                 developer.value = developer.integer = 1;
410                 developer.string = "1";
411         }
412
413         if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
414         {
415                 developer.value = developer.integer = 1;
416                 developer.string = "1";
417                 developer_extra.value = developer_extra.integer = 1;
418                 developer_extra.string = "1";
419                 developer_insane.value = developer_insane.integer = 1;
420                 developer_insane.string = "1";
421                 developer_memory.value = developer_memory.integer = 1;
422                 developer_memory.string = "1";
423                 developer_memorydebug.value = developer_memorydebug.integer = 1;
424                 developer_memorydebug.string = "1";
425         }
426
427         if (Sys_CheckParm("-developer3"))
428         {
429                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
430                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
431         }
432
433         // -dedicated is checked in SV_ServerOptions() but that's too late for Cvar_RegisterVariable() to skip all the client-only cvars
434         if (Sys_CheckParm ("-dedicated") || !cl_available)
435                 cls.state = ca_dedicated;
436
437         // initialize console command/cvar/alias/command execution systems
438         Cmd_Init();
439
440         // initialize memory subsystem cvars/commands
441         Memory_Init_Commands();
442
443         // initialize console and logging and its cvars/commands
444         // this enables Con_Printf() messages to be coloured
445         Con_Init();
446
447         // initialize various cvars that could not be initialized earlier
448         u8_Init();
449         Curl_Init_Commands();
450         Sys_Init_Commands();
451         COM_Init_Commands();
452
453         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name, gamename)
454         FS_Init();
455
456         // ASAP! construct a version string for the corner of the console and for crash messages
457         dpsnprintf (engineversion, sizeof (engineversion), "%s %s%s, buildstring: %s", gamename, DP_OS_NAME, cls.state == ca_dedicated ? " dedicated" : "", buildstring);
458         Con_Printf("%s\n", engineversion);
459
460         // initialize process nice level
461         Sys_InitProcessNice();
462
463         // initialize ixtable
464         Mathlib_Init();
465
466         // register the cvars for session locking
467         Host_InitSession();
468
469         // must be after FS_Init
470         Crypto_Init();
471         Crypto_Init_Commands();
472
473         NetConn_Init();
474         Curl_Init();
475         PRVM_Init();
476         Mod_Init();
477         World_Init();
478         SV_Init();
479         Host_InitLocal();
480
481         Thread_Init();
482         TaskQueue_Init();
483
484         CL_Init();
485
486         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
487         // NOTE: menu commands are freed by Cmd_RestoreInitState
488         Cmd_SaveInitState();
489
490         // FIXME: put this into some neat design, but the menu should be allowed to crash
491         // without crashing the whole game, so this should just be a short-time solution
492
493         // here comes the not so critical stuff
494
495         Host_AddConfigText(cmd_local);
496
497         // if quake.rc is missing, use default
498         if (!FS_FileExists("quake.rc"))
499         {
500                 Cbuf_AddText(cmd_local, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
501                 Cbuf_Execute(cmd_local->cbuf);
502         }
503
504         host.state = host_active;
505
506         CL_StartVideo();
507
508         Log_Start();
509
510         if (cls.state != ca_dedicated)
511         {
512                 // put up the loading image so the user doesn't stare at a black screen...
513                 SCR_BeginLoadingPlaque(true);
514                 S_Startup();
515 #ifdef CONFIG_MENU
516                 MR_Init();
517 #endif
518         }
519
520         // check for special benchmark mode
521 // 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)
522         i = Sys_CheckParm("-benchmark");
523         if (i && i + 1 < sys.argc)
524         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
525         {
526                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
527                 Cbuf_Execute(cmd_local->cbuf);
528         }
529
530         // check for special demo mode
531 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
532         i = Sys_CheckParm("-demo");
533         if (i && i + 1 < sys.argc)
534         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
535         {
536                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
537                 Cbuf_Execute(cmd_local->cbuf);
538         }
539
540 #ifdef CONFIG_VIDEO_CAPTURE
541 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
542         i = Sys_CheckParm("-capturedemo");
543         if (i && i + 1 < sys.argc)
544         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
545         {
546                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
547                 Cbuf_Execute((cmd_local)->cbuf);
548         }
549 #endif
550
551         if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
552         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
553         {
554                 Cbuf_AddText(cmd_local, "startmap_dm\n");
555                 Cbuf_Execute(cmd_local->cbuf);
556         }
557
558         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
559         {
560 #ifdef CONFIG_MENU
561                 Cbuf_AddText(cmd_local, "togglemenu 1\n");
562 #endif
563                 Cbuf_Execute(cmd_local->cbuf);
564         }
565
566         Con_DPrint("========Initialized=========\n");
567
568         if (cls.state != ca_dedicated)
569                 SV_StartThread();
570 }
571
572 /*
573 ===============
574 Host_Shutdown
575
576 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
577 to run quit through here before the final handoff to the sys code.
578 ===============
579 */
580 void Host_Shutdown(void)
581 {
582         static qbool isdown = false;
583
584         if (isdown)
585         {
586                 Con_Print(CON_WARN "recursive shutdown\n");
587                 return;
588         }
589         if (setjmp(host.abortframe))
590         {
591                 Con_Print(CON_WARN "aborted the quitting frame?!?\n");
592                 return;
593         }
594         isdown = true;
595
596         if(cls.state != ca_dedicated)
597                 CL_Shutdown();
598
599         // end the server thread
600         if (svs.threaded)
601                 SV_StopThread();
602
603         // shut down local server if active
604         if(host.hook.SV_Shutdown)
605                 host.hook.SV_Shutdown();
606
607         // AK shutdown PRVM
608         // AK hmm, no PRVM_Shutdown(); yet
609
610         Host_SaveConfig(CONFIGFILENAME);
611
612         Curl_Shutdown ();
613         NetConn_Shutdown ();
614
615         SV_StopThread();
616         TaskQueue_Shutdown();
617         Thread_Shutdown();
618         Cmd_Shutdown();
619         Sys_SDL_Shutdown();
620         Log_Close();
621         Crypto_Shutdown();
622
623         Host_UnlockSession();
624
625         Con_Shutdown();
626         Memory_Shutdown();
627 }
628
629 //============================================================================
630
631 /*
632 ==================
633 Host_Frame
634
635 Runs all active servers
636 ==================
637 */
638 static double Host_Frame(double time)
639 {
640         double cl_wait, sv_wait;
641
642         TaskQueue_Frame(false);
643
644         // keep the random time dependent, but not when playing demos/benchmarking
645         if(!*sv_random_seed.string && !host.restless)
646                 rand();
647
648         NetConn_UpdateSockets();
649
650         Log_DestBuffer_Flush();
651
652         // Run any downloads
653         Curl_Frame();
654
655         // get new SDL events and add commands from keybindings to the cbuf
656         Sys_SDL_HandleEvents();
657
658         // process console commands
659         Cbuf_Frame(host.cbuf);
660
661         R_TimeReport("---");
662
663         // if the accumulators haven't become positive yet, wait a while
664         sv_wait = - SV_Frame(time);
665         cl_wait = - CL_Frame(time);
666
667         Mem_CheckSentinelsGlobal();
668
669         if (cls.state == ca_dedicated)
670                 return sv_wait; // dedicated
671         else if (!sv.active || svs.threaded)
672                 return cl_wait; // connected to server, main menu, or server is on different thread
673         else
674                 return min(cl_wait, sv_wait); // listen server or singleplayer
675 }
676
677 // Cloudwalk: Most overpowered function declaration...
678 static inline double Host_UpdateTime (double newtime, double oldtime)
679 {
680         double time = newtime - oldtime;
681
682         if (time < 0)
683         {
684                 // warn if it's significant
685                 if (time < -0.01)
686                         Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
687                 time = 0;
688         }
689         else if (time >= 1800)
690         {
691                 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
692                 time = 0;
693         }
694
695         return time;
696 }
697
698 void Host_Main(void)
699 {
700         double time, oldtime, sleeptime;
701
702         Host_Init(); // Start!
703
704         host.realtime = 0;
705         oldtime = Sys_DirtyTime();
706
707         // Main event loop
708         while(host.state != host_shutdown)
709         {
710                 // Something bad happened, or the server disconnected
711                 if (setjmp(host.abortframe))
712                 {
713                         host.state = host_active; // In case we were loading
714                         continue;
715                 }
716
717                 host.dirtytime = Sys_DirtyTime();
718                 host.realtime += time = Host_UpdateTime(host.dirtytime, oldtime);
719                 oldtime = host.dirtytime;
720
721                 sleeptime = Host_Frame(time);
722                 ++host.framecount;
723                 sleeptime -= Sys_DirtyTime() - host.dirtytime; // execution time
724                 host.sleeptime = Sys_Sleep(sleeptime);
725         }
726
727         return;
728 }