]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
Fix uses of strlcpy on unterminated source strings
[xonotic/darkplaces.git] / cmd.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cmd.c -- Quake script command processing module
21
22 #include "quakedef.h"
23 #include "thread.h"
24
25 cmd_state_t *cmd_local;
26 cmd_state_t *cmd_serverfromclient;
27
28 cmd_userdefined_t cmd_userdefined_all;
29 cmd_userdefined_t cmd_userdefined_null;
30
31 typedef struct cmd_iter_s {
32         cmd_state_t *cmd;
33 }
34 cmd_iter_t;
35
36 static cmd_iter_t *cmd_iter_all;
37
38 mempool_t *cbuf_mempool;
39
40 // we only run the +whatever commandline arguments once
41 qbool host_stuffcmdsrun = false;
42
43 //=============================================================================
44
45 void Cbuf_Lock(cmd_buf_t *cbuf)
46 {
47         Thread_LockMutex(cbuf->lock);
48 }
49
50 void Cbuf_Unlock(cmd_buf_t *cbuf)
51 {
52         Thread_UnlockMutex(cbuf->lock);
53 }
54
55
56 /*
57 ============
58 Cmd_Wait_f
59
60 Causes execution of the remainder of the command buffer to be delayed until
61 next frame.  This allows commands like:
62 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
63 ============
64 */
65 static void Cmd_Wait_f (cmd_state_t *cmd)
66 {
67         cmd->cbuf->wait = true;
68 }
69
70 /*
71 ============
72 Cmd_Defer_f
73
74 Cause a command to be executed after a delay.
75 ============
76 */
77 static void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending);
78 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize);
79 static void Cmd_Defer_f (cmd_state_t *cmd)
80 {
81         cmd_input_t *current;
82         cmd_buf_t *cbuf = cmd->cbuf;
83         unsigned int cmdsize;
84
85         if(Cmd_Argc(cmd) == 1)
86         {
87                 if(List_Is_Empty(&cbuf->deferred))
88                         Con_Printf("No commands are pending.\n");
89                 else
90                 {
91                         List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
92                                 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
93                 }
94         }
95         else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
96         {
97                 while(!List_Is_Empty(&cbuf->deferred))
98                 {
99                         cbuf->size -= List_Entry(cbuf->deferred.next, cmd_input_t, list)->length;
100                         List_Move_Tail(cbuf->deferred.next, &cbuf->free);
101                 }
102         }
103         else if(Cmd_Argc(cmd) == 3 && (cmdsize = strlen(Cmd_Argv(cmd, 2))) )
104         {
105                 Cbuf_Lock(cbuf);
106
107                 Cbuf_LinkString(cmd, &cbuf->deferred, NULL, Cmd_Argv(cmd, 2), false, cmdsize);
108                 List_Entry(cbuf->deferred.prev, cmd_input_t, list)->delay = atof(Cmd_Argv(cmd, 1));
109
110                 Cbuf_Unlock(cbuf);
111         }
112         else
113         {
114                 Con_Printf("usage: defer <seconds> <command>\n"
115                            "       defer clear\n");
116                 return;
117         }
118 }
119
120 /*
121 =============================================================================
122
123                                                 COMMAND BUFFER
124
125  * The Quake command-line is super basic. It can be entered in the console
126  * or in config files. A semicolon is used to terminate a command and chain
127  * them together. Otherwise, a newline delineates command input.
128  *
129  * In most engines, the Quake command-line is a simple linear text buffer that
130  * is parsed when it executes. In Darkplaces, we use a linked list of command
131  * input and parse the input on the spot.
132  *
133  * This was done because Darkplaces allows multiple command interpreters on the
134  * same thread. Previously, each interpreter maintained its own buffer and this
135  * caused problems related to execution order, and maintaining a single simple
136  * buffer for all interpreters makes it non-trivial to keep track of which
137  * command should execute on which interpreter.
138
139 =============================================================================
140 */
141
142 /*
143 ============
144 Cbuf_NodeGet
145
146 Returns an existing buffer node for appending or reuse, or allocates a new one
147 ============
148 */
149 static cmd_input_t *Cbuf_NodeGet(cmd_buf_t *cbuf, cmd_input_t *existing)
150 {
151         cmd_input_t *node;
152         if(existing && existing->pending)
153                 node = existing;
154         else if(!List_Is_Empty(&cbuf->free))
155         {
156                 node = List_Entry(cbuf->free.next, cmd_input_t, list);
157                 node->length = node->pending = 0;
158         }
159         else
160         {
161                 node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
162                 node->list.prev = node->list.next = &node->list;
163                 node->size = node->length = node->pending = 0;
164         }
165         return node;
166 }
167
168 /*
169 ============
170 Cbuf_LinkString
171
172 Copies a command string into a buffer node.
173 The input should not be null-terminated, the output will be.
174 ============
175 */
176 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize)
177 {
178         cmd_buf_t *cbuf = cmd->cbuf;
179         cmd_input_t *node = Cbuf_NodeGet(cbuf, existing);
180         unsigned int offset = node->length; // > 0 if(pending)
181
182         // node will match existing if its text was pending continuation
183         if(node != existing)
184         {
185                 node->source = cmd;
186                 List_Move_Tail(&node->list, head);
187         }
188
189         node->length += cmdsize;
190         if(node->size < node->length)
191         {
192                 node->text = (char *)Mem_Realloc(cbuf_mempool, node->text, node->length + 1);
193                 node->size = node->length;
194         }
195         cbuf->size += cmdsize;
196
197         dp_ustr2stp(&node->text[offset], node->length + 1, text, cmdsize);
198         //Con_Printf("^5Cbuf_LinkString(): %s `^7%s^5`\n", node->pending ? "append" : "new", &node->text[offset]);
199         node->pending = leavepending;
200 }
201
202 /*
203 ============
204 Cbuf_ParseText
205
206 Parses text to isolate command strings for linking into the buffer
207 separators: \n \r or unquoted and uncommented ';'
208 ============
209 */
210 static void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending)
211 {
212         unsigned int cmdsize = 0, start = 0, pos;
213         qbool quotes = false, comment = false;
214
215         for (pos = 0; text[pos]; ++pos)
216         {
217                 switch(text[pos])
218                 {
219                         case ';':
220                                 if (comment || quotes)
221                                         break;
222                         case '\r':
223                         case '\n':
224                                 comment = false;
225                                 quotes = false; // matches div0-stable
226                                 if (cmdsize)
227                                 {
228                                         Cbuf_LinkString(cmd, head, existing, &text[start], false, cmdsize);
229                                         cmdsize = 0;
230                                 }
231                                 else if (existing && existing->pending) // all I got was this lousy \n
232                                         existing->pending = false;
233                                 continue; // don't increment cmdsize
234
235                         case '/':
236                                 if (!quotes && text[pos + 1] == '/' && (pos == 0 || ISWHITESPACE(text[pos - 1])))
237                                         comment = true;
238                                 break;
239                         case '"':
240                                 if (!comment && (pos == 0 || text[pos - 1] != '\\'))
241                                         quotes = !quotes;
242                                 break;
243                 }
244
245                 if (!comment)
246                 {
247                         if (!cmdsize)
248                                 start = pos;
249                         ++cmdsize;
250                 }
251         }
252
253         if (cmdsize) // the line didn't end yet but we do have a string
254                 Cbuf_LinkString(cmd, head, existing, &text[start], allowpending, cmdsize);
255 }
256
257 /*
258 ============
259 Cbuf_AddText
260
261 Adds command text at the end of the buffer
262 ============
263 */
264 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
265 {
266         size_t l = strlen(text);
267         cmd_buf_t *cbuf = cmd->cbuf;
268         llist_t llist = {&llist, &llist};
269
270         if (cbuf->size + l > cbuf->maxsize)
271         {
272                 Con_Printf(CON_WARN "Cbuf_AddText: input too large, %zuKB ought to be enough for anybody.\n", cbuf->maxsize / 1024);
273                 return;
274         }
275
276         Cbuf_Lock(cbuf);
277
278         // If the string terminates but the (last) line doesn't, the node will be left in the pending state (to be continued).
279         Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.prev, cmd_input_t, list)), text, true);
280         List_Splice_Tail(&llist, &cbuf->start);
281
282         Cbuf_Unlock(cbuf);
283 }
284
285 /*
286 ============
287 Cbuf_InsertText
288
289 Adds command text immediately after the current command
290 ============
291 */
292 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
293 {
294         cmd_buf_t *cbuf = cmd->cbuf;
295         llist_t llist = {&llist, &llist};
296         size_t l = strlen(text);
297
298         if (cbuf->size + l > cbuf->maxsize)
299         {
300                 Con_Printf(CON_WARN "Cbuf_InsertText: input too large, %zuKB ought to be enough for anybody.\n", cbuf->maxsize / 1024);
301                 return;
302         }
303
304         Cbuf_Lock(cbuf);
305
306         // bones_was_here assertion: when prepending to the buffer it never makes sense to leave node(s) in the `pending` state,
307         // it would have been impossible to append to such text later in the old raw text buffer,
308         // and allowing it causes bugs when .cfg files lack \n at EOF (see: https://gitlab.com/xonotic/darkplaces/-/issues/378).
309         Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.next, cmd_input_t, list)), text, false);
310         List_Splice(&llist, &cbuf->start);
311
312         Cbuf_Unlock(cbuf);
313 }
314
315 /*
316 ============
317 Cbuf_Execute_Deferred --blub
318 ============
319 */
320 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
321 {
322         cmd_input_t *current, *n;
323         vec_t eat;
324
325         if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
326                 cbuf->deferred_oldtime = host.realtime;
327         eat = host.realtime - cbuf->deferred_oldtime;
328         if (eat < 1.0/128.0)
329                 return;
330         cbuf->deferred_oldtime = host.realtime;
331
332         List_For_Each_Entry_Safe(current, n, &cbuf->deferred, cmd_input_t, list)
333         {
334                 current->delay -= eat;
335                 if(current->delay <= 0)
336                 {
337                         Cbuf_AddText(current->source, current->text); // parse deferred string and append its cmdstring(s)
338                         List_Entry(cbuf->start.prev, cmd_input_t, list)->pending = false; // faster than div0-stable's Cbuf_AddText(";\n");
339                         List_Move_Tail(&current->list, &cbuf->free); // make deferred string memory available for reuse
340                         cbuf->size -= current->length;
341                 }
342         }
343 }
344
345 /*
346 ============
347 Cbuf_Execute
348 ============
349 */
350 extern qbool prvm_runawaycheck;
351 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias );
352 void Cbuf_Execute (cmd_buf_t *cbuf)
353 {
354         cmd_input_t *current;
355         char preprocessed[MAX_INPUTLINE];
356         char *firstchar;
357         unsigned int i = 0;
358
359         // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
360         cbuf->tokenizebufferpos = 0;
361
362         while (!List_Is_Empty(&cbuf->start))
363         {
364                 /*
365                  * Delete the text from the command buffer and move remaining
366                  * commands down. This is necessary because commands (exec, alias)
367                  * can insert data at the beginning of the text buffer
368                  */
369                 current = List_Entry(cbuf->start.next, cmd_input_t, list);
370
371                 /*
372                  * Assume we're rolling with the current command-line and
373                  * always set this false because alias expansion or cbuf insertion
374                  * without a newline may set this true, and cause weirdness.
375                  */
376                 current->pending = false;
377
378                 cbuf->size -= current->length;
379
380                 firstchar = current->text;
381                 while(*firstchar && ISWHITESPACE(*firstchar))
382                         ++firstchar;
383                 if((strncmp(firstchar, "alias", 5)   || !ISWHITESPACE(firstchar[5])) &&
384                    (strncmp(firstchar, "bind", 4)    || !ISWHITESPACE(firstchar[4])) &&
385                    (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
386                 {
387                         if(Cmd_PreprocessString(current->source, current->text, preprocessed, sizeof(preprocessed), NULL ))
388                                 Cmd_ExecuteString(current->source, preprocessed, src_local, false);
389                 }
390                 else
391                 {
392                         Cmd_ExecuteString (current->source, current->text, src_local, false);
393                 }
394
395                 // Recycle memory so using WASD doesn't cause a malloc and free
396                 List_Move_Tail(&current->list, &cbuf->free);
397
398                 current = NULL;
399
400                 if (cbuf->wait)
401                 {
402                         /*
403                          * Skip out while text still remains in
404                          * buffer, leaving it for next frame
405                          */
406                         cbuf->wait = false;
407                         break;
408                 }
409
410                 if (++i == 1000000 && prvm_runawaycheck)
411                 {
412                         Con_Printf(CON_WARN "Cbuf_Execute: runaway loop counter hit limit of %d commands, clearing command buffers!\n", i);
413                         Cbuf_Clear(cbuf);
414                 }
415         }
416 }
417
418 /*
419 ===================
420 Cbuf_Frame_Input
421
422 Add them exactly as if they had been typed at the console
423 ===================
424 */
425 static void Cbuf_Frame_Input(void)
426 {
427         char *line;
428
429         if ((line = Sys_ConsoleInput()))
430         {
431                 // bones_was_here: prepending allows a loop such as `alias foo "bar; wait; foo"; foo`
432                 // to be broken with an alias or unalias command
433                 Cbuf_InsertText(cmd_local, line);
434         }
435 }
436
437 void Cbuf_Frame(cmd_buf_t *cbuf)
438 {
439         // check for commands typed to the host
440         Cbuf_Frame_Input();
441
442 //      R_TimeReport("preconsole");
443
444         // execute commands queued with the defer command
445         Cbuf_Execute_Deferred(cbuf);
446         if (cbuf->size)
447         {
448                 SV_LockThreadMutex();
449                 Cbuf_Execute(cbuf);
450                 SV_UnlockThreadMutex();
451         }
452
453 //      R_TimeReport("console");
454 }
455
456 void Cbuf_Clear(cmd_buf_t *cbuf)
457 {
458         while (!List_Is_Empty(&cbuf->start))
459                 List_Move_Tail(cbuf->start.next, &cbuf->free);
460         while (!List_Is_Empty(&cbuf->deferred))
461                 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
462         cbuf->size = 0;
463 }
464
465 /*
466 ==============================================================================
467
468                                                 SCRIPT COMMANDS
469
470 ==============================================================================
471 */
472
473 /*
474 ===============
475 Cmd_StuffCmds_f
476
477 Adds command line parameters as script statements
478 Commands lead with a +, and continue until a - or another +
479 quake +prog jctest.qp +cmd amlev1
480 quake -nosound +cmd amlev1
481 ===============
482 */
483 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
484 {
485         int             i, j, l;
486         // this is for all commandline options combined (and is bounds checked)
487         char    build[MAX_INPUTLINE];
488
489         if (Cmd_Argc (cmd) != 1)
490         {
491                 Con_Print("stuffcmds : execute command line parameters\n");
492                 return;
493         }
494
495         // no reason to run the commandline arguments twice
496         if (host_stuffcmdsrun)
497                 return;
498
499         host_stuffcmdsrun = true;
500         build[0] = 0;
501         l = 0;
502         for (i = 0;i < sys.argc;i++)
503         {
504                 if (sys.argv[i] && sys.argv[i][0] == '+' && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9') && l + strlen(sys.argv[i]) - 1 <= sizeof(build) - 1)
505                 {
506                         j = 1;
507                         while (sys.argv[i][j])
508                                 build[l++] = sys.argv[i][j++];
509                         i++;
510                         for (;i < sys.argc;i++)
511                         {
512                                 if (!sys.argv[i])
513                                         continue;
514                                 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
515                                         break;
516                                 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
517                                         break;
518                                 build[l++] = ' ';
519                                 if (strchr(sys.argv[i], ' '))
520                                         build[l++] = '\"';
521                                 for (j = 0;sys.argv[i][j];j++)
522                                         build[l++] = sys.argv[i][j];
523                                 if (strchr(sys.argv[i], ' '))
524                                         build[l++] = '\"';
525                         }
526                         build[l++] = '\n';
527                         i--;
528                 }
529         }
530         // now terminate the combined string and prepend it to the command buffer
531         // we already reserved space for the terminator
532         build[l++] = 0;
533         Cbuf_InsertText (cmd, build);
534 }
535
536 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
537 {
538         char *f;
539         size_t filenameLen = strlen(filename);
540         qbool isdefaultcfg =
541                 !strcmp(filename, "default.cfg") ||
542                 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
543
544         if (!strcmp(filename, "config.cfg"))
545         {
546                 filename = CONFIGFILENAME;
547                 if (Sys_CheckParm("-noconfig"))
548                         return; // don't execute config.cfg
549         }
550
551         f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
552         if (!f)
553         {
554                 Con_Printf(CON_WARN "couldn't exec %s\n",filename);
555                 return;
556         }
557         Con_Printf("execing %s\n",filename);
558
559         // if executing default.cfg for the first time, lock the cvar defaults
560         // it may seem backwards to insert this text BEFORE the default.cfg
561         // but Cbuf_InsertText inserts before, so this actually ends up after it.
562         if (isdefaultcfg)
563                 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
564
565         Cbuf_InsertText (cmd, f);
566         Mem_Free(f);
567
568         if (isdefaultcfg)
569         {
570                 // special defaults for specific games go here, these execute before default.cfg
571                 // Nehahra pushable crates malfunction in some levels if this is on
572                 // Nehahra NPC AI is confused by blowupfallenzombies
573                 switch(gamemode)
574                 {
575                 case GAME_NORMAL:
576                         Cbuf_InsertText(cmd, "\n"
577 "sv_gameplayfix_blowupfallenzombies 0\n"
578 "sv_gameplayfix_findradiusdistancetobox 0\n"
579 "sv_gameplayfix_grenadebouncedownslopes 0\n"
580 "sv_gameplayfix_slidemoveprojectiles 0\n"
581 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
582 "sv_gameplayfix_setmodelrealbox 0\n"
583 "sv_gameplayfix_droptofloorstartsolid 0\n"
584 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
585 "sv_gameplayfix_noairborncorpse 0\n"
586 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
587 "sv_gameplayfix_easierwaterjump 0\n"
588 "sv_gameplayfix_delayprojectiles 0\n"
589 "sv_gameplayfix_multiplethinksperframe 0\n"
590 "sv_gameplayfix_fixedcheckwatertransition 0\n"
591 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
592 "sv_gameplayfix_swiminbmodels 0\n"
593 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
594 "sys_ticrate 0.01388889\n"
595 "r_shadow_gloss 1\n"
596 "r_shadow_bumpscale_basetexture 0\n"
597 "csqc_polygons_defaultmaterial_nocullface 0\n"
598                                 );
599                         break;
600                 case GAME_NEHAHRA:
601                         Cbuf_InsertText(cmd, "\n"
602 "sv_gameplayfix_blowupfallenzombies 0\n"
603 "sv_gameplayfix_findradiusdistancetobox 0\n"
604 "sv_gameplayfix_grenadebouncedownslopes 0\n"
605 "sv_gameplayfix_slidemoveprojectiles 0\n"
606 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
607 "sv_gameplayfix_setmodelrealbox 0\n"
608 "sv_gameplayfix_droptofloorstartsolid 0\n"
609 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
610 "sv_gameplayfix_noairborncorpse 0\n"
611 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
612 "sv_gameplayfix_easierwaterjump 0\n"
613 "sv_gameplayfix_delayprojectiles 0\n"
614 "sv_gameplayfix_multiplethinksperframe 0\n"
615 "sv_gameplayfix_fixedcheckwatertransition 0\n"
616 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
617 "sv_gameplayfix_swiminbmodels 0\n"
618 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
619 "sys_ticrate 0.01388889\n"
620 "r_shadow_gloss 1\n"
621 "r_shadow_bumpscale_basetexture 0\n"
622 "csqc_polygons_defaultmaterial_nocullface 0\n"
623                                 );
624                         break;
625                 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
626                 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
627                 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
628                 case GAME_HIPNOTIC:
629                 case GAME_QUOTH:
630                         Cbuf_InsertText(cmd, "\n"
631 "sv_gameplayfix_blowupfallenzombies 0\n"
632 "sv_gameplayfix_findradiusdistancetobox 0\n"
633 "sv_gameplayfix_grenadebouncedownslopes 0\n"
634 "sv_gameplayfix_slidemoveprojectiles 0\n"
635 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
636 "sv_gameplayfix_setmodelrealbox 0\n"
637 "sv_gameplayfix_droptofloorstartsolid 0\n"
638 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
639 "sv_gameplayfix_noairborncorpse 0\n"
640 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
641 "sv_gameplayfix_easierwaterjump 0\n"
642 "sv_gameplayfix_delayprojectiles 0\n"
643 "sv_gameplayfix_multiplethinksperframe 0\n"
644 "sv_gameplayfix_fixedcheckwatertransition 0\n"
645 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
646 "sv_gameplayfix_swiminbmodels 0\n"
647 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
648 "sys_ticrate 0.02\n"
649 "r_shadow_gloss 1\n"
650 "r_shadow_bumpscale_basetexture 0\n"
651 "csqc_polygons_defaultmaterial_nocullface 0\n"
652                                 );
653                         break;
654                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
655                 case GAME_ROGUE:
656                         Cbuf_InsertText(cmd, "\n"
657 "sv_gameplayfix_blowupfallenzombies 0\n"
658 "sv_gameplayfix_findradiusdistancetobox 0\n"
659 "sv_gameplayfix_grenadebouncedownslopes 0\n"
660 "sv_gameplayfix_slidemoveprojectiles 0\n"
661 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
662 "sv_gameplayfix_setmodelrealbox 0\n"
663 "sv_gameplayfix_droptofloorstartsolid 0\n"
664 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
665 "sv_gameplayfix_noairborncorpse 0\n"
666 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
667 "sv_gameplayfix_easierwaterjump 0\n"
668 "sv_gameplayfix_delayprojectiles 0\n"
669 "sv_gameplayfix_multiplethinksperframe 0\n"
670 "sv_gameplayfix_fixedcheckwatertransition 0\n"
671 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
672 "sv_gameplayfix_swiminbmodels 0\n"
673 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
674 "sys_ticrate 0.01388889\n"
675 "r_shadow_gloss 1\n"
676 "r_shadow_bumpscale_basetexture 0\n"
677 "csqc_polygons_defaultmaterial_nocullface 0\n"
678                                 );
679                         break;
680                 case GAME_TENEBRAE:
681                         Cbuf_InsertText(cmd, "\n"
682 "sv_gameplayfix_blowupfallenzombies 0\n"
683 "sv_gameplayfix_findradiusdistancetobox 0\n"
684 "sv_gameplayfix_grenadebouncedownslopes 0\n"
685 "sv_gameplayfix_slidemoveprojectiles 0\n"
686 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
687 "sv_gameplayfix_setmodelrealbox 0\n"
688 "sv_gameplayfix_droptofloorstartsolid 0\n"
689 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
690 "sv_gameplayfix_noairborncorpse 0\n"
691 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
692 "sv_gameplayfix_easierwaterjump 0\n"
693 "sv_gameplayfix_delayprojectiles 0\n"
694 "sv_gameplayfix_multiplethinksperframe 0\n"
695 "sv_gameplayfix_fixedcheckwatertransition 0\n"
696 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
697 "sv_gameplayfix_swiminbmodels 0\n"
698 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
699 "sys_ticrate 0.01388889\n"
700 "r_shadow_gloss 2\n"
701 "r_shadow_bumpscale_basetexture 4\n"
702 "csqc_polygons_defaultmaterial_nocullface 0\n"
703                                 );
704                         break;
705                 case GAME_NEXUIZ:
706                         Cbuf_InsertText(cmd, "\n"
707 "sv_gameplayfix_blowupfallenzombies 1\n"
708 "sv_gameplayfix_findradiusdistancetobox 1\n"
709 "sv_gameplayfix_grenadebouncedownslopes 1\n"
710 "sv_gameplayfix_slidemoveprojectiles 1\n"
711 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
712 "sv_gameplayfix_setmodelrealbox 1\n"
713 "sv_gameplayfix_droptofloorstartsolid 1\n"
714 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
715 "sv_gameplayfix_noairborncorpse 1\n"
716 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
717 "sv_gameplayfix_easierwaterjump 1\n"
718 "sv_gameplayfix_delayprojectiles 1\n"
719 "sv_gameplayfix_multiplethinksperframe 1\n"
720 "sv_gameplayfix_fixedcheckwatertransition 1\n"
721 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
722 "sv_gameplayfix_swiminbmodels 1\n"
723 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
724 "sys_ticrate 0.01388889\n"
725 "sv_gameplayfix_q2airaccelerate 1\n"
726 "sv_gameplayfix_stepmultipletimes 1\n"
727 "csqc_polygons_defaultmaterial_nocullface 1\n"
728 "con_chatsound_team_mask 13\n"
729                                 );
730                         break;
731                 case GAME_XONOTIC:
732                 case GAME_VORETOURNAMENT:
733                         // compatibility for versions prior to 2020-05-25, this can be overridden in newer versions to get the default behavior and be consistent with FTEQW engine
734                         Cbuf_InsertText(cmd, "\n"
735 "csqc_polygons_defaultmaterial_nocullface 1\n"
736 "con_chatsound_team_mask 13\n"
737 "sv_qcstats 1\n"
738 "mod_q1bsp_zero_hullsize_cutoff 8.03125\n"
739                                 );
740                         break;
741                 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
742                 case GAME_STEELSTORM:
743                         Cbuf_InsertText(cmd, "\n"
744 "sv_gameplayfix_blowupfallenzombies 1\n"
745 "sv_gameplayfix_findradiusdistancetobox 1\n"
746 "sv_gameplayfix_grenadebouncedownslopes 1\n"
747 "sv_gameplayfix_slidemoveprojectiles 1\n"
748 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
749 "sv_gameplayfix_setmodelrealbox 1\n"
750 "sv_gameplayfix_droptofloorstartsolid 1\n"
751 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
752 "sv_gameplayfix_noairborncorpse 1\n"
753 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
754 "sv_gameplayfix_easierwaterjump 1\n"
755 "sv_gameplayfix_delayprojectiles 1\n"
756 "sv_gameplayfix_multiplethinksperframe 1\n"
757 "sv_gameplayfix_fixedcheckwatertransition 1\n"
758 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
759 "sv_gameplayfix_swiminbmodels 1\n"
760 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
761 "sys_ticrate 0.01388889\n"
762 "cl_csqc_generatemousemoveevents 0\n"
763 "csqc_polygons_defaultmaterial_nocullface 1\n"
764                                 );
765                         break;
766                 default:
767                         Cbuf_InsertText(cmd, "\n"
768 "sv_gameplayfix_blowupfallenzombies 1\n"
769 "sv_gameplayfix_findradiusdistancetobox 1\n"
770 "sv_gameplayfix_grenadebouncedownslopes 1\n"
771 "sv_gameplayfix_slidemoveprojectiles 1\n"
772 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
773 "sv_gameplayfix_setmodelrealbox 1\n"
774 "sv_gameplayfix_droptofloorstartsolid 1\n"
775 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
776 "sv_gameplayfix_noairborncorpse 1\n"
777 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
778 "sv_gameplayfix_easierwaterjump 1\n"
779 "sv_gameplayfix_delayprojectiles 1\n"
780 "sv_gameplayfix_multiplethinksperframe 1\n"
781 "sv_gameplayfix_fixedcheckwatertransition 1\n"
782 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
783 "sv_gameplayfix_swiminbmodels 1\n"
784 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
785 "sys_ticrate 0.01388889\n"
786 "csqc_polygons_defaultmaterial_nocullface 0\n"
787                                 );
788                         break;
789                 }
790         }
791 }
792
793 /*
794 ===============
795 Cmd_Exec_f
796 ===============
797 */
798 static void Cmd_Exec_f (cmd_state_t *cmd)
799 {
800         fssearch_t *s;
801         int i;
802
803         if (Cmd_Argc(cmd) != 2)
804         {
805                 Con_Print("exec <filename> : execute a script file\n");
806                 return;
807         }
808
809         s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
810         if(!s || !s->numfilenames)
811         {
812                 Con_Printf(CON_WARN "couldn't exec %s\n",Cmd_Argv(cmd, 1));
813                 return;
814         }
815
816         for(i = 0; i < s->numfilenames; ++i)
817                 Cmd_Exec(cmd, s->filenames[i]);
818
819         FS_FreeSearch(s);
820 }
821
822
823 /*
824 ===============
825 Cmd_Echo_f
826
827 Just prints the rest of the line to the console
828 ===============
829 */
830 static void Cmd_Echo_f (cmd_state_t *cmd)
831 {
832         int             i;
833
834         for (i=1 ; i<Cmd_Argc(cmd) ; i++)
835                 Con_Printf("%s ",Cmd_Argv(cmd, i));
836         Con_Print("\n");
837 }
838
839 // DRESK - 5/14/06
840 // Support Doom3-style Toggle Console Command
841 /*
842 ===============
843 Cmd_Toggle_f
844
845 Toggles a specified console variable amongst the values specified (default is 0 and 1)
846 ===============
847 */
848 static void Cmd_Toggle_f(cmd_state_t *cmd)
849 {
850         // Acquire Number of Arguments
851         int nNumArgs = Cmd_Argc(cmd);
852
853         if(nNumArgs == 1)
854                 // No Arguments Specified; Print Usage
855                 Con_Print("Toggle Console Variable - Usage\n  toggle <variable> - toggles between 0 and 1\n  toggle <variable> <value> - toggles between 0 and <value>\n  toggle <variable> [string 1] [string 2]...[string n] - cycles through all strings\n");
856         else
857         { // Correct Arguments Specified
858                 // Acquire Potential CVar
859                 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
860
861                 if(cvCVar != NULL)
862                 { // Valid CVar
863                         if(nNumArgs == 2)
864                         { // Default Usage
865                                 if(cvCVar->integer)
866                                         Cvar_SetValueQuick(cvCVar, 0);
867                                 else
868                                         Cvar_SetValueQuick(cvCVar, 1);
869                         }
870                         else
871                         if(nNumArgs == 3)
872                         { // 0 and Specified Usage
873                                 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
874                                         // CVar is Specified Value; // Reset to 0
875                                         Cvar_SetValueQuick(cvCVar, 0);
876                                 else
877                                 if(cvCVar->integer == 0)
878                                         // CVar is 0; Specify Value
879                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
880                                 else
881                                         // CVar does not match; Reset to 0
882                                         Cvar_SetValueQuick(cvCVar, 0);
883                         }
884                         else
885                         { // Variable Values Specified
886                                 int nCnt;
887                                 int bFound = 0;
888
889                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
890                                 { // Cycle through Values
891                                         if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
892                                         { // Current Value Located; Increment to Next
893                                                 if( (nCnt + 1) == nNumArgs)
894                                                         // Max Value Reached; Reset
895                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
896                                                 else
897                                                         // Next Value
898                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
899
900                                                 // End Loop
901                                                 nCnt = nNumArgs;
902                                                 // Assign Found
903                                                 bFound = 1;
904                                         }
905                                 }
906                                 if(!bFound)
907                                         // Value not Found; Reset to Original
908                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
909                         }
910
911                 }
912                 else
913                 { // Invalid CVar
914                         Con_Printf(CON_WARN "ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
915                 }
916         }
917 }
918
919 /*
920 ===============
921 Cmd_Alias_f
922
923 Creates a new command that executes a command string (possibly ; seperated)
924 ===============
925 */
926 static void Cmd_Alias_f (cmd_state_t *cmd)
927 {
928         cmd_alias_t     *a;
929         char            line[MAX_INPUTLINE];
930         int                     i, c;
931         const char              *s;
932         size_t          alloclen;
933
934         if (Cmd_Argc(cmd) == 1)
935         {
936                 Con_Print("Current alias commands:\n");
937                 for (a = cmd->userdefined->alias ; a ; a=a->next)
938                         Con_Printf("%s : %s", a->name, a->value);
939                 return;
940         }
941
942         s = Cmd_Argv(cmd, 1);
943         if (strlen(s) >= MAX_ALIAS_NAME)
944         {
945                 Con_Print(CON_WARN "Alias name is too long\n");
946                 return;
947         }
948
949         // if the alias already exists, reuse it
950         for (a = cmd->userdefined->alias ; a ; a=a->next)
951         {
952                 if (!strcmp(s, a->name))
953                 {
954                         Z_Free (a->value);
955                         break;
956                 }
957         }
958
959         if (!a)
960         {
961                 cmd_alias_t *prev, *current;
962
963                 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
964                 dp_strlcpy (a->name, s, sizeof (a->name));
965                 // insert it at the right alphanumeric position
966                 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
967                         ;
968                 if( prev ) {
969                         prev->next = a;
970                 } else {
971                         cmd->userdefined->alias = a;
972                 }
973                 a->next = current;
974         }
975
976
977 // copy the rest of the command line
978         line[0] = 0;            // start out with a null string
979         c = Cmd_Argc(cmd);
980         for (i=2 ; i < c ; i++)
981         {
982                 if (i != 2)
983                         dp_strlcat (line, " ", sizeof (line));
984                 dp_strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
985         }
986         dp_strlcat (line, "\n", sizeof (line));
987
988         alloclen = strlen (line) + 1;
989         if(alloclen >= 2)
990                 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
991         a->value = (char *)Z_Malloc (alloclen);
992         memcpy (a->value, line, alloclen);
993 }
994
995 /*
996 ===============
997 Cmd_UnAlias_f
998
999 Remove existing aliases.
1000 ===============
1001 */
1002 static void Cmd_UnAlias_f (cmd_state_t *cmd)
1003 {
1004         cmd_alias_t     *a, *p;
1005         int i;
1006         const char *s;
1007
1008         if(Cmd_Argc(cmd) == 1)
1009         {
1010                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1011                 return;
1012         }
1013
1014         for(i = 1; i < Cmd_Argc(cmd); ++i)
1015         {
1016                 s = Cmd_Argv(cmd, i);
1017                 p = NULL;
1018                 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1019                 {
1020                         if(!strcmp(s, a->name))
1021                         {
1022                                 if (a->initstate) // we can not remove init aliases
1023                                         continue;
1024                                 if(a == cmd->userdefined->alias)
1025                                         cmd->userdefined->alias = a->next;
1026                                 if(p)
1027                                         p->next = a->next;
1028                                 Z_Free(a->value);
1029                                 Z_Free(a);
1030                                 break;
1031                         }
1032                 }
1033                 if(!a)
1034                         Con_Printf("unalias: %s alias not found\n", s);
1035         }
1036 }
1037
1038 /*
1039 =============================================================================
1040
1041                                         COMMAND EXECUTION
1042
1043 =============================================================================
1044 */
1045
1046 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1047 {
1048         cvar_t *cvar;
1049         long argno;
1050         char *endptr;
1051         static char vabuf[1024]; // cmd_mutex
1052
1053         if(is_multiple)
1054                 *is_multiple = false;
1055
1056         if(!varname || !*varname)
1057                 return NULL;
1058
1059         if(alias)
1060         {
1061                 if(!strcmp(varname, "*"))
1062                 {
1063                         if(is_multiple)
1064                                 *is_multiple = true;
1065                         return Cmd_Args(cmd);
1066                 }
1067                 else if(!strcmp(varname, "#"))
1068                 {
1069                         return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1070                 }
1071                 else if(varname[strlen(varname) - 1] == '-')
1072                 {
1073                         argno = strtol(varname, &endptr, 10);
1074                         if(endptr == varname + strlen(varname) - 1)
1075                         {
1076                                 // whole string is a number, apart from the -
1077                                 const char *p = Cmd_Args(cmd);
1078                                 for(; argno > 1; --argno)
1079                                         if(!COM_ParseToken_Console(&p))
1080                                                 break;
1081                                 if(p)
1082                                 {
1083                                         if(is_multiple)
1084                                                 *is_multiple = true;
1085
1086                                         // kill pre-argument whitespace
1087                                         for (;*p && ISWHITESPACE(*p);p++)
1088                                                 ;
1089
1090                                         return p;
1091                                 }
1092                         }
1093                 }
1094                 else
1095                 {
1096                         argno = strtol(varname, &endptr, 10);
1097                         if(*endptr == 0)
1098                         {
1099                                 // whole string is a number
1100                                 // NOTE: we already made sure we don't have an empty cvar name!
1101                                 if(argno >= 0 && argno < Cmd_Argc(cmd))
1102                                         return Cmd_Argv(cmd, argno);
1103                         }
1104                 }
1105         }
1106
1107         if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1108                 return cvar->string;
1109
1110         return NULL;
1111 }
1112
1113 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1114 {
1115         qbool quote_quot = !!strchr(quoteset, '"');
1116         qbool quote_backslash = !!strchr(quoteset, '\\');
1117         qbool quote_dollar = !!strchr(quoteset, '$');
1118
1119         if(putquotes)
1120         {
1121                 if(outlen <= 2)
1122                 {
1123                         *out++ = 0;
1124                         return false;
1125                 }
1126                 *out++ = '"'; --outlen;
1127                 --outlen;
1128         }
1129
1130         while(*in)
1131         {
1132                 if(*in == '"' && quote_quot)
1133                 {
1134                         if(outlen <= 2)
1135                                 goto fail;
1136                         *out++ = '\\'; --outlen;
1137                         *out++ = '"'; --outlen;
1138                 }
1139                 else if(*in == '\\' && quote_backslash)
1140                 {
1141                         if(outlen <= 2)
1142                                 goto fail;
1143                         *out++ = '\\'; --outlen;
1144                         *out++ = '\\'; --outlen;
1145                 }
1146                 else if(*in == '$' && quote_dollar)
1147                 {
1148                         if(outlen <= 2)
1149                                 goto fail;
1150                         *out++ = '$'; --outlen;
1151                         *out++ = '$'; --outlen;
1152                 }
1153                 else
1154                 {
1155                         if(outlen <= 1)
1156                                 goto fail;
1157                         *out++ = *in; --outlen;
1158                 }
1159                 ++in;
1160         }
1161         if(putquotes)
1162                 *out++ = '"';
1163         *out++ = 0;
1164         return true;
1165 fail:
1166         if(putquotes)
1167                 *out++ = '"';
1168         *out++ = 0;
1169         return false;
1170 }
1171
1172 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1173 {
1174         static char varname[MAX_INPUTLINE]; // cmd_mutex
1175         static char varval[MAX_INPUTLINE]; // cmd_mutex
1176         const char *varstr = NULL;
1177         char *varfunc;
1178         qbool required = false;
1179         qbool optional = false;
1180         static char asis[] = "asis"; // just to suppress const char warnings
1181
1182         if(varlen >= MAX_INPUTLINE)
1183                 varlen = MAX_INPUTLINE - 1;
1184         memcpy(varname, var, varlen);
1185         varname[varlen] = 0;
1186         varfunc = strchr(varname, ' ');
1187
1188         if(varfunc)
1189         {
1190                 *varfunc = 0;
1191                 ++varfunc;
1192         }
1193
1194         if(*var == 0)
1195         {
1196                 // empty cvar name?
1197                 if(alias)
1198                         Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1199                 else
1200                         Con_Printf(CON_WARN "Warning: Could not expand $\n");
1201                 return "$";
1202         }
1203
1204         if(varfunc)
1205         {
1206                 char *p;
1207                 // ? means optional
1208                 while((p = strchr(varfunc, '?')))
1209                 {
1210                         optional = true;
1211                         memmove(p, p+1, strlen(p)); // with final NUL
1212                 }
1213                 // ! means required
1214                 while((p = strchr(varfunc, '!')))
1215                 {
1216                         required = true;
1217                         memmove(p, p+1, strlen(p)); // with final NUL
1218                 }
1219                 // kill spaces
1220                 while((p = strchr(varfunc, ' ')))
1221                 {
1222                         memmove(p, p+1, strlen(p)); // with final NUL
1223                 }
1224                 // if no function is left, NULL it
1225                 if(!*varfunc)
1226                         varfunc = NULL;
1227         }
1228
1229         if(varname[0] == '$')
1230                 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1231         else
1232         {
1233                 qbool is_multiple = false;
1234                 // Exception: $* and $n- don't use the quoted form by default
1235                 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1236                 if(is_multiple)
1237                         if(!varfunc)
1238                                 varfunc = asis;
1239         }
1240
1241         if(!varstr)
1242         {
1243                 if(required)
1244                 {
1245                         if(alias)
1246                                 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1247                         else
1248                                 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1249                         return NULL;
1250                 }
1251                 else if(optional)
1252                 {
1253                         return "";
1254                 }
1255                 else
1256                 {
1257                         if(alias)
1258                                 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1259                         else
1260                                 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1261                         dpsnprintf(varval, sizeof(varval), "$%s", varname);
1262                         return varval;
1263                 }
1264         }
1265
1266         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1267         {
1268                 // quote it so it can be used inside double quotes
1269                 // we just need to replace " by \", and of course, double backslashes
1270                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1271                 return varval;
1272         }
1273         else if(!strcmp(varfunc, "asis"))
1274         {
1275                 return varstr;
1276         }
1277         else
1278                 Con_Printf("Unknown variable function %s\n", varfunc);
1279
1280         return varstr;
1281 }
1282
1283 /*
1284 Cmd_PreprocessString
1285
1286 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1287 */
1288 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias ) {
1289         const char *in;
1290         size_t eat, varlen;
1291         unsigned outlen;
1292         const char *val;
1293
1294         // don't crash if there's no room in the outtext buffer
1295         if( maxoutlen == 0 ) {
1296                 return false;
1297         }
1298         maxoutlen--; // because of \0
1299
1300         in = intext;
1301         outlen = 0;
1302
1303         while( *in && outlen < maxoutlen ) {
1304                 if( *in == '$' ) {
1305                         // this is some kind of expansion, see what comes after the $
1306                         in++;
1307
1308                         // The console does the following preprocessing:
1309                         //
1310                         // - $$ is transformed to a single dollar sign.
1311                         // - $var or ${var} are expanded to the contents of the named cvar,
1312                         //   with quotation marks and backslashes quoted so it can safely
1313                         //   be used inside quotation marks (and it should always be used
1314                         //   that way)
1315                         // - ${var asis} inserts the cvar value as is, without doing this
1316                         //   quoting
1317                         // - ${var ?} silently expands to the empty string if
1318                         //   $var does not exist
1319                         // - ${var !} fails expansion and executes nothing if
1320                         //   $var does not exist
1321                         // - prefix the cvar name with a dollar sign to do indirection;
1322                         //   for example, if $x has the value timelimit, ${$x} will return
1323                         //   the value of $timelimit
1324                         // - when expanding an alias, the special variable name $* refers
1325                         //   to all alias parameters, and a number refers to that numbered
1326                         //   alias parameter, where the name of the alias is $0, the first
1327                         //   parameter is $1 and so on; as a special case, $* inserts all
1328                         //   parameters, without extra quoting, so one can use $* to just
1329                         //   pass all parameters around. All parameters starting from $n
1330                         //   can be referred to as $n- (so $* is equivalent to $1-).
1331                         // - ${* q} and ${n- q} force quoting anyway
1332                         //
1333                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1334                         // as alias expansion so that alias parameters or cvar values containing
1335                         // dollar signs have no unwanted bad side effects. However, this needs to
1336                         // be accounted for when writing complex aliases. For example,
1337                         //   alias foo "set x NEW; echo $x"
1338                         // actually expands to
1339                         //   "set x NEW; echo OLD"
1340                         // and will print OLD! To work around this, use a second alias:
1341                         //   alias foo "set x NEW; foo2"
1342                         //   alias foo2 "echo $x"
1343                         //
1344                         // Also note: lines starting with alias are exempt from cvar expansion.
1345                         // If you want cvar expansion, write "alias" instead:
1346                         //
1347                         //   set x 1
1348                         //   alias foo "echo $x"
1349                         //   "alias" bar "echo $x"
1350                         //   set x 2
1351                         //
1352                         // foo will print 2, because the variable $x will be expanded when the alias
1353                         // gets expanded. bar will print 1, because the variable $x was expanded
1354                         // at definition time. foo can be equivalently defined as
1355                         //
1356                         //   "alias" foo "echo $$x"
1357                         //
1358                         // because at definition time, $$ will get replaced to a single $.
1359
1360                         if( *in == '$' ) {
1361                                 val = "$";
1362                                 eat = 1;
1363                         } else if(*in == '{') {
1364                                 varlen = strcspn(in + 1, "}");
1365                                 if(in[varlen + 1] == '}')
1366                                 {
1367                                         val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1368                                         if(!val)
1369                                                 return false;
1370                                         eat = varlen + 2;
1371                                 }
1372                                 else
1373                                 {
1374                                         // ran out of data?
1375                                         val = NULL;
1376                                         eat = varlen + 1;
1377                                 }
1378                         } else {
1379                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1380                                 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1381                                 if(!val)
1382                                         return false;
1383                                 eat = varlen;
1384                         }
1385                         if(val)
1386                         {
1387                                 // insert the cvar value
1388                                 while(*val && outlen < maxoutlen)
1389                                         outtext[outlen++] = *val++;
1390                                 in += eat;
1391                         }
1392                         else
1393                         {
1394                                 // copy the unexpanded text
1395                                 outtext[outlen++] = '$';
1396                                 while(eat && outlen < maxoutlen)
1397                                 {
1398                                         outtext[outlen++] = *in++;
1399                                         --eat;
1400                                 }
1401                         }
1402                 }
1403                 else 
1404                         outtext[outlen++] = *in++;
1405         }
1406         outtext[outlen] = 0;
1407         return true;
1408 }
1409
1410 /*
1411 ============
1412 Cmd_ExecuteAlias
1413
1414 Called for aliases and fills in the alias into the cbuffer
1415 ============
1416 */
1417 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1418 {
1419         static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1420         static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1421         qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1422         if(!ret)
1423                 return;
1424         // insert at start of command buffer, so that aliases execute in order
1425         // (fixes bug introduced by Black on 20050705)
1426
1427         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1428         // have to make sure that no second variable expansion takes place, otherwise
1429         // alias parameters containing dollar signs can have bad effects.
1430         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1431         Cbuf_InsertText(cmd, buffer2);
1432 }
1433
1434 /*
1435 ========
1436 Cmd_List
1437
1438         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1439         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1440
1441 ========
1442 */
1443 static void Cmd_List_f (cmd_state_t *cmd)
1444 {
1445         cmd_function_t *func;
1446         const char *partial;
1447         size_t len;
1448         int count;
1449         qbool ispattern;
1450
1451         if (Cmd_Argc(cmd) > 1)
1452         {
1453                 partial = Cmd_Argv(cmd, 1);
1454                 len = strlen(partial);
1455                 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1456         }
1457         else
1458         {
1459                 partial = NULL;
1460                 len = 0;
1461                 ispattern = false;
1462         }
1463
1464         count = 0;
1465         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1466         {
1467                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1468                         continue;
1469                 Con_Printf("%s : %s\n", func->name, func->description);
1470                 count++;
1471         }
1472         for (func = cmd->engine_functions; func; func = func->next)
1473         {
1474                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1475                         continue;
1476                 Con_Printf("%s : %s\n", func->name, func->description);
1477                 count++;
1478         }
1479
1480         if (len)
1481         {
1482                 if(ispattern)
1483                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1484                 else
1485                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1486         }
1487         else
1488                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1489 }
1490
1491 static void Cmd_Apropos_f(cmd_state_t *cmd)
1492 {
1493         cmd_function_t *func;
1494         cvar_t *cvar;
1495         cmd_alias_t *alias;
1496         const char *partial;
1497         int count;
1498         qbool ispattern;
1499         char vabuf[1024];
1500
1501         if (Cmd_Argc(cmd) > 1)
1502                 partial = Cmd_Args(cmd);
1503         else
1504         {
1505                 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1506                 return;
1507         }
1508
1509         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1510         if(!ispattern)
1511                 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1512
1513         count = 0;
1514         for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1515         {
1516                 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1517                     matchpattern_with_separator(cvar->description, partial, true, "", false))
1518                 {
1519                         Con_Printf ("cvar ");
1520                         Cvar_PrintHelp(cvar, cvar->name, true);
1521                         count++;
1522                 }
1523                 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1524                 {
1525                         if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1526                         {
1527                                 Con_Printf ("cvar ");
1528                                 Cvar_PrintHelp(cvar, *cvar_alias, true);
1529                                 count++;
1530                         }
1531                 }
1532         }
1533         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1534         {
1535                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1536                         if (!matchpattern_with_separator(func->description, partial, true, "", false))
1537                                 continue;
1538                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1539                 count++;
1540         }
1541         for (func = cmd->engine_functions; func; func = func->next)
1542         {
1543                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1544                 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1545                         continue;
1546                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1547                 count++;
1548         }
1549         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1550         {
1551                 // procede here a bit differently as an alias value always got a final \n
1552                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1553                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1554                         continue;
1555                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1556                 count++;
1557         }
1558         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1559 }
1560
1561 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, unsigned cvars_flagsmask, unsigned cmds_flagsmask, cmd_userdefined_t *userdefined)
1562 {
1563         cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1564         
1565         cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1566         // space for commands and script files
1567         cmd->cbuf = cbuf;
1568         cmd->null_string = "";
1569
1570         cmd->cvars = cvars;
1571         cmd->cvars_flagsmask = cvars_flagsmask;
1572         cmd->cmd_flagsmask = cmds_flagsmask;
1573         cmd->userdefined = userdefined;
1574
1575         return cmd;
1576 }
1577
1578 /*
1579 ============
1580 Cmd_Init
1581 ============
1582 */
1583 void Cmd_Init(void)
1584 {
1585         cmd_buf_t *cbuf;
1586         unsigned cvars_flagsmask, cmds_flagsmask;
1587
1588         cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1589         cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1590         cbuf->maxsize = CMDBUFSIZE;
1591         cbuf->lock = Thread_CreateMutex();
1592         cbuf->wait = false;
1593         host.cbuf = cbuf;
1594
1595         cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1596         cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1597         cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1598
1599         // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1600         cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1601
1602         // local console
1603         if (cls.state == ca_dedicated)
1604         {
1605                 cvars_flagsmask = CF_SERVER;
1606                 cmds_flagsmask = CF_SERVER | CF_SERVER_FROM_CLIENT;
1607         }
1608         else
1609         {
1610                 cvars_flagsmask = CF_CLIENT | CF_SERVER;
1611                 cmds_flagsmask = CF_CLIENT | CF_SERVER | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT;
1612         }
1613         cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, cvars_flagsmask, cmds_flagsmask, &cmd_userdefined_all);
1614         cmd_local->Handle = Cmd_CL_Callback;
1615
1616         // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1617         cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1618         cmd_serverfromclient->Handle = Cmd_SV_Callback;
1619
1620         cmd_iter_all[2].cmd = NULL;
1621 //
1622 // register our commands
1623 //
1624         // client-only commands
1625         Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1626
1627         // maintenance commands used for upkeep of cvars and saved configs
1628         Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1629         Cmd_AddCommand(CF_SHARED, "cvar_lockdefaults", Cvar_LockDefaults_f, "stores the current values of all cvars into their default values, only used once during startup after parsing default.cfg");
1630         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1631         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_nosaveonly", Cvar_ResetToDefaults_NoSaveOnly_f, "sets all non-saved cvars to their locked default values (variables that will not be saved to config.cfg)");
1632         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1633
1634         // general console commands used in multiple environments
1635         Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1636         Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1637         Cmd_AddCommand(CF_SHARED, "alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1638         Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1639         Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1640         Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1641         Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1642
1643 #ifdef FILLALLCVARSWITHRUBBISH
1644         Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1645 #endif /* FILLALLCVARSWITHRUBBISH */
1646
1647         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1648         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1649         Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1650         Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1651         Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1652         Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1653
1654         Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1655
1656         // DRESK - 5/14/06
1657         // Support Doom3-style Toggle Command
1658         Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1659 }
1660
1661 /*
1662 ============
1663 Cmd_Shutdown
1664 ============
1665 */
1666 void Cmd_Shutdown(void)
1667 {
1668         cmd_iter_t *cmd_iter;
1669         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1670         {
1671                 cmd_state_t *cmd = cmd_iter->cmd;
1672
1673                 if (cmd->cbuf->lock)
1674                 {
1675                         // we usually have this locked when we get here from Host_Quit_f
1676                         Cbuf_Unlock(cmd->cbuf);
1677                 }
1678
1679                 Mem_FreePool(&cmd->mempool);
1680         }
1681 }
1682
1683 /*
1684 ============
1685 Cmd_TokenizeString
1686
1687 Parses the given string into command line tokens.
1688 Takes a null terminated string.  Does not need to be /n terminated.
1689 ============
1690 */
1691 // AK: This function should only be called from ExecuteString because the current design is a bit of an hack
1692 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1693 {
1694         int l;
1695
1696         cmd->argc = 0;
1697         cmd->args = NULL;
1698         cmd->cmdline = NULL;
1699
1700         while (1)
1701         {
1702                 // skip whitespace up to a /n
1703                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1704                         text++;
1705
1706                 // line endings:
1707                 // UNIX: \n
1708                 // Mac: \r
1709                 // Windows: \r\n
1710                 if (*text == '\n' || *text == '\r')
1711                 {
1712                         // a newline separates commands in the buffer
1713                         if (*text == '\r' && text[1] == '\n')
1714                                 text++;
1715                         text++;
1716                         break;
1717                 }
1718
1719                 if (!*text)
1720                         return;
1721
1722                 if(!cmd->argc)
1723                         cmd->cmdline = text;
1724                 if (cmd->argc == 1)
1725                         cmd->args = text;
1726
1727                 if (!COM_ParseToken_Console(&text))
1728                         return;
1729
1730                 if (cmd->argc < MAX_ARGS)
1731                 {
1732                         l = (int)strlen(com_token) + 1;
1733                         if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1734                         {
1735                                 Con_Printf(CON_WARN "Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1736                                 break;
1737                         }
1738                         memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1739                         cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1740                         cmd->cbuf->tokenizebufferpos += l;
1741                         cmd->argc++;
1742                 }
1743         }
1744 }
1745
1746
1747 /*
1748 ============
1749 Cmd_AddCommand
1750 ============
1751 */
1752 void Cmd_AddCommand(unsigned flags, const char *cmd_name, xcommand_t function, const char *description)
1753 {
1754         cmd_function_t *func;
1755         cmd_function_t *prev, *current;
1756         cmd_state_t *cmd;
1757         int i;
1758
1759         for (i = 0; i < 2; i++)
1760         {
1761                 cmd = cmd_iter_all[i].cmd;
1762                 if (flags & cmd->cmd_flagsmask)
1763                 {
1764                         // fail if the command is a variable name
1765                         if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1766                         {
1767                                 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1768                                 return;
1769                         }
1770
1771                         if (function)
1772                         {
1773                                 // fail if the command already exists in this interpreter
1774                                 for (func = cmd->engine_functions; func; func = func->next)
1775                                 {
1776                                         if (!strcmp(cmd_name, func->name))
1777                                         {
1778                                                 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined\n", cmd_name);
1779                                                 continue;
1780                                         }
1781                                 }
1782
1783                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1784                                 func->flags = flags;
1785                                 func->name = cmd_name;
1786                                 func->function = function;
1787                                 func->description = description;
1788                                 func->next = cmd->engine_functions;
1789
1790                                 // insert it at the right alphanumeric position
1791                                 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1792                                         ;
1793                                 if (prev) {
1794                                         prev->next = func;
1795                                 }
1796                                 else {
1797                                         cmd->engine_functions = func;
1798                                 }
1799                                 func->next = current;
1800                         }
1801                         else
1802                         {
1803                                 // mark qcfunc if the function already exists in the qc_functions list
1804                                 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1805                                 {
1806                                         if (!strcmp(cmd_name, func->name))
1807                                         {
1808                                                 func->qcfunc = true; //[515]: csqc
1809                                                 continue;
1810                                         }
1811                                 }
1812
1813                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1814                                 func->flags = flags;
1815                                 func->name = cmd_name;
1816                                 func->function = function;
1817                                 func->description = description;
1818                                 func->qcfunc = true; //[515]: csqc
1819                                 func->next = cmd->userdefined->qc_functions;
1820
1821                                 // bones_was_here: if this QC command overrides an engine command, store its pointer
1822                                 // to avoid doing this search at invocation if QC declines to handle this command.
1823                                 for (cmd_function_t *f = cmd->engine_functions; f; f = f->next)
1824                                 {
1825                                         if (!strcmp(cmd_name, f->name))
1826                                         {
1827                                                 Con_DPrintf("Adding QC override of engine command %s\n", cmd_name);
1828                                                 func->overridden = f;
1829                                                 break;
1830                                         }
1831                                 }
1832
1833                                 // insert it at the right alphanumeric position
1834                                 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1835                                         ;
1836                                 if (prev) {
1837                                         prev->next = func;
1838                                 }
1839                                 else {
1840                                         cmd->userdefined->qc_functions = func;
1841                                 }
1842                                 func->next = current;
1843                         }
1844                 }
1845         }
1846 }
1847
1848 /*
1849 ============
1850 Cmd_Exists
1851 ============
1852 */
1853 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1854 {
1855         cmd_function_t  *func;
1856
1857         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1858                 if (!strcmp(cmd_name, func->name))
1859                         return true;
1860
1861         for (func=cmd->engine_functions ; func ; func=func->next)
1862                 if (!strcmp (cmd_name,func->name))
1863                         return true;
1864
1865         return false;
1866 }
1867
1868
1869 /*
1870 ============
1871 Cmd_CompleteCommand
1872 ============
1873 */
1874 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1875 {
1876         cmd_function_t *func;
1877         size_t len;
1878
1879         len = strlen(partial);
1880
1881         if (!len)
1882                 return NULL;
1883
1884 // check functions
1885         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1886                 if (!strncasecmp(partial, func->name, len))
1887                         return func->name;
1888
1889         for (func = cmd->engine_functions; func; func = func->next)
1890                 if (!strncasecmp(partial, func->name, len))
1891                         return func->name;
1892
1893         return NULL;
1894 }
1895
1896 /*
1897         Cmd_CompleteCountPossible
1898
1899         New function for tab-completion system
1900         Added by EvilTypeGuy
1901         Thanks to Fett erich@heintz.com
1902         Thanks to taniwha
1903
1904 */
1905 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1906 {
1907         cmd_function_t *func;
1908         size_t len;
1909         int h;
1910
1911         h = 0;
1912         len = strlen(partial);
1913
1914         if (!len)
1915                 return 0;
1916
1917         // Loop through the command list and count all partial matches
1918         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1919                 if (!strncasecmp(partial, func->name, len))
1920                         h++;
1921
1922         for (func = cmd->engine_functions; func; func = func->next)
1923                 if (!strncasecmp(partial, func->name, len))
1924                         h++;
1925
1926         return h;
1927 }
1928
1929 /*
1930         Cmd_CompleteBuildList
1931
1932         New function for tab-completion system
1933         Added by EvilTypeGuy
1934         Thanks to Fett erich@heintz.com
1935         Thanks to taniwha
1936
1937 */
1938 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1939 {
1940         cmd_function_t *func;
1941         size_t len = 0;
1942         size_t bpos = 0;
1943         size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1944         const char **buf;
1945
1946         len = strlen(partial);
1947         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1948         // Loop through the functions lists and print all matches
1949         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1950                 if (!strncasecmp(partial, func->name, len))
1951                         buf[bpos++] = func->name;
1952         for (func = cmd->engine_functions; func; func = func->next)
1953                 if (!strncasecmp(partial, func->name, len))
1954                         buf[bpos++] = func->name;
1955
1956         buf[bpos] = NULL;
1957         return buf;
1958 }
1959
1960 // written by LadyHavoc
1961 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
1962 {
1963         cmd_function_t *func;
1964         size_t len = strlen(partial);
1965         // Loop through the command list and print all matches
1966         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1967                 if (!strncasecmp(partial, func->name, len))
1968                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
1969         for (func = cmd->engine_functions; func; func = func->next)
1970                 if (!strncasecmp(partial, func->name, len))
1971                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
1972 }
1973
1974 /*
1975         Cmd_CompleteAlias
1976
1977         New function for tab-completion system
1978         Added by EvilTypeGuy
1979         Thanks to Fett erich@heintz.com
1980         Thanks to taniwha
1981
1982 */
1983 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
1984 {
1985         cmd_alias_t *alias;
1986         size_t len;
1987
1988         len = strlen(partial);
1989
1990         if (!len)
1991                 return NULL;
1992
1993         // Check functions
1994         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1995                 if (!strncasecmp(partial, alias->name, len))
1996                         return alias->name;
1997
1998         return NULL;
1999 }
2000
2001 // written by LadyHavoc
2002 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2003 {
2004         cmd_alias_t *alias;
2005         size_t len = strlen(partial);
2006         // Loop through the alias list and print all matches
2007         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2008                 if (!strncasecmp(partial, alias->name, len))
2009                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
2010 }
2011
2012
2013 /*
2014         Cmd_CompleteAliasCountPossible
2015
2016         New function for tab-completion system
2017         Added by EvilTypeGuy
2018         Thanks to Fett erich@heintz.com
2019         Thanks to taniwha
2020
2021 */
2022 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2023 {
2024         cmd_alias_t     *alias;
2025         size_t          len;
2026         int                     h;
2027
2028         h = 0;
2029
2030         len = strlen(partial);
2031
2032         if (!len)
2033                 return 0;
2034
2035         // Loop through the command list and count all partial matches
2036         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2037                 if (!strncasecmp(partial, alias->name, len))
2038                         h++;
2039
2040         return h;
2041 }
2042
2043 /*
2044         Cmd_CompleteAliasBuildList
2045
2046         New function for tab-completion system
2047         Added by EvilTypeGuy
2048         Thanks to Fett erich@heintz.com
2049         Thanks to taniwha
2050
2051 */
2052 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2053 {
2054         cmd_alias_t *alias;
2055         size_t len = 0;
2056         size_t bpos = 0;
2057         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2058         const char **buf;
2059
2060         len = strlen(partial);
2061         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2062         // Loop through the alias list and print all matches
2063         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2064                 if (!strncasecmp(partial, alias->name, len))
2065                         buf[bpos++] = alias->name;
2066
2067         buf[bpos] = NULL;
2068         return buf;
2069 }
2070
2071 // TODO: Make this more generic?
2072 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2073 {
2074         cmd_function_t *func;
2075         cmd_function_t **next = &cmd->userdefined->qc_functions;
2076         
2077         while(*next)
2078         {
2079                 func = *next;
2080                 *next = func->next;
2081                 Z_Free(func);
2082         }
2083 }
2084
2085 extern cvar_t sv_cheats;
2086
2087 /*
2088  * Cloudwalk FIXME: This idea sounded great in my head but...
2089  * How do we handle commands that can be received by the client,
2090  * but which the server can also execute locally?
2091  * 
2092  * If we create a callback where the engine will forward to server
2093  * but try to execute the command locally if it's dedicated,
2094  * we're back to intermixing client and server code which I'm
2095  * trying to avoid. There's no other way I can think of to
2096  * implement that behavior that doesn't involve an #ifdef, or
2097  * making a mess of hooks.
2098  */
2099 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2100 {
2101         if (func->function)
2102                 func->function(cmd);
2103         else
2104                 Con_Printf(CON_WARN "Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2105         return true;
2106 }
2107
2108 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2109 {
2110         // TODO: Assign these functions to QC commands directly?
2111         if(func->qcfunc)
2112         {
2113                 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text)) ||
2114                    ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text)))
2115                         return true;
2116
2117                 if (func->overridden) // If this QC command overrides an engine command,
2118                         func = func->overridden; // fall back to that command.
2119         }
2120         if (func->flags & CF_SERVER_FROM_CLIENT)
2121         {
2122                 if(host_isclient.integer)
2123                 {
2124                         CL_ForwardToServer_f(cmd);
2125                         return true;
2126                 }
2127                 else if(!(func->flags & CF_SERVER))
2128                 {
2129                         Con_Printf(CON_WARN "Cannot execute client commands from a dedicated server console.\n");
2130                         return true;
2131                 }
2132         }
2133         return Cmd_Callback(cmd, func, text, src);
2134 }
2135
2136 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2137 {
2138         if(func->qcfunc && (func->flags & CF_SERVER))
2139                 return SV_VM_ConsoleCommand(text);
2140         else if (src == src_client)
2141         {
2142                 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2143                         SV_ClientPrintf(CON_WARN "No cheats allowed. The server must have sv_cheats set to 1\n");
2144                 else
2145                         func->function(cmd);
2146                 return true;
2147         }
2148         return false;
2149 }
2150
2151 /*
2152 ============
2153 Cmd_ExecuteString
2154
2155 A complete command line has been parsed, so try to execute it
2156 FIXME: lookupnoadd the token to speed search?
2157 ============
2158 */
2159 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qbool lockmutex)
2160 {
2161         int oldpos;
2162         cmd_function_t *func;
2163         cmd_alias_t *a;
2164
2165         if (lockmutex)
2166                 Cbuf_Lock(cmd->cbuf);
2167         oldpos = cmd->cbuf->tokenizebufferpos;
2168         cmd->source = src;
2169
2170         Cmd_TokenizeString (cmd, text);
2171
2172 // execute the command line
2173         if (!Cmd_Argc(cmd))
2174                 goto done; // no tokens
2175
2176 // check functions
2177         for (func = cmd->userdefined->qc_functions; func; func = func->next)
2178                 if (!strcasecmp(cmd->argv[0], func->name))
2179                         if(cmd->Handle(cmd, func, text, src))
2180                                 goto functions_done;
2181
2182         for (func = cmd->engine_functions; func; func=func->next)
2183                 if (!strcasecmp (cmd->argv[0], func->name))
2184                         if(cmd->Handle(cmd, func, text, src))
2185                                 goto functions_done;
2186
2187 functions_done:
2188         // If it's a client command and wasn't found and handled, say so.
2189         // Also don't let clients call server aliases.
2190         if (cmd->source == src_client)
2191         {
2192                 if (!func)
2193                         Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2194                 goto done;
2195         }
2196
2197 // check alias
2198         // Execute any alias with the same name as a command after the command.
2199         for (a=cmd->userdefined->alias ; a ; a=a->next)
2200         {
2201                 if (!strcasecmp (cmd->argv[0], a->name))
2202                 {
2203                         Cmd_ExecuteAlias(cmd, a);
2204                         goto done;
2205                 }
2206         }
2207
2208         // If the command was found and handled don't try to handle it as a cvar.
2209         if (func)
2210                 goto done;
2211
2212 // check cvars
2213         if (!Cvar_Command(cmd) && host.framecount > 0)
2214                 Con_Printf(CON_WARN "Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2215 done:
2216         cmd->cbuf->tokenizebufferpos = oldpos;
2217         if (lockmutex)
2218                 Cbuf_Unlock(cmd->cbuf);
2219 }
2220
2221 /*
2222 ================
2223 Cmd_CheckParm
2224
2225 Returns the position (1 to argc-1) in the command's argument list
2226 where the given parameter apears, or 0 if not present
2227 ================
2228 */
2229
2230 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2231 {
2232         int i;
2233
2234         if (!parm)
2235         {
2236                 Con_Printf(CON_WARN "Cmd_CheckParm: NULL");
2237                 return 0;
2238         }
2239
2240         for (i = 1; i < Cmd_Argc (cmd); i++)
2241                 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2242                         return i;
2243
2244         return 0;
2245 }
2246
2247
2248
2249 void Cmd_SaveInitState(void)
2250 {
2251         cmd_iter_t *cmd_iter;
2252         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2253         {
2254                 cmd_state_t *cmd = cmd_iter->cmd;
2255                 cmd_function_t *f;
2256                 cmd_alias_t *a;
2257                 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2258                         f->initstate = true;
2259                 for (f = cmd->engine_functions; f; f = f->next)
2260                         f->initstate = true;
2261                 for (a = cmd->userdefined->alias; a; a = a->next)
2262                 {
2263                         a->initstate = true;
2264                         a->initialvalue = Mem_strdup(zonemempool, a->value);
2265                 }
2266         }
2267         Cvar_SaveInitState(&cvars_all);
2268 }
2269
2270 void Cmd_RestoreInitState(void)
2271 {
2272         cmd_iter_t *cmd_iter;
2273         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2274         {
2275                 cmd_state_t *cmd = cmd_iter->cmd;
2276                 cmd_function_t *f, **fp;
2277                 cmd_alias_t *a, **ap;
2278                 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2279                 {
2280                         if (f->initstate)
2281                                 fp = &f->next;
2282                         else
2283                         {
2284                                 // destroy this command, it didn't exist at init
2285                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2286                                 *fp = f->next;
2287                                 Z_Free(f);
2288                         }
2289                 }
2290                 for (fp = &cmd->engine_functions; (f = *fp);)
2291                 {
2292                         if (f->initstate)
2293                                 fp = &f->next;
2294                         else
2295                         {
2296                                 // destroy this command, it didn't exist at init
2297                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2298                                 *fp = f->next;
2299                                 Z_Free(f);
2300                         }
2301                 }
2302                 for (ap = &cmd->userdefined->alias; (a = *ap);)
2303                 {
2304                         if (a->initstate)
2305                         {
2306                                 // restore this alias, it existed at init
2307                                 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2308                                 {
2309                                         Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2310                                         if (a->value)
2311                                                 Z_Free(a->value);
2312                                         a->value = Mem_strdup(zonemempool, a->initialvalue);
2313                                 }
2314                                 ap = &a->next;
2315                         }
2316                         else
2317                         {
2318                                 // free this alias, it didn't exist at init...
2319                                 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2320                                 *ap = a->next;
2321                                 if (a->value)
2322                                         Z_Free(a->value);
2323                                 Z_Free(a);
2324                         }
2325                 }
2326         }
2327         Cvar_RestoreInitState(&cvars_all);
2328 }
2329
2330 void Cmd_NoOperation_f(cmd_state_t *cmd)
2331 {
2332 }