]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
fix segfault with long aliases
[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
24 #define MAX_ALIAS_NAME  32
25 // this is the largest script file that can be executed in one step
26 // LordHavoc: inreased this from 8192 to 32768
27 // div0: increased this from 32k to 128k
28 #define CMDBUFSIZE 131072
29 // maximum number of parameters to a command
30 #define MAX_ARGS 80
31 // maximum tokenizable commandline length (counting NUL terminations)
32 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + MAX_ARGS)
33
34 typedef struct cmdalias_s
35 {
36         struct cmdalias_s *next;
37         char name[MAX_ALIAS_NAME];
38         char *value;
39 } cmdalias_t;
40
41 static cmdalias_t *cmd_alias;
42
43 static qboolean cmd_wait;
44
45 static mempool_t *cmd_mempool;
46
47 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
48 static int cmd_tokenizebufferpos = 0;
49
50 //=============================================================================
51
52 /*
53 ============
54 Cmd_Wait_f
55
56 Causes execution of the remainder of the command buffer to be delayed until
57 next frame.  This allows commands like:
58 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
59 ============
60 */
61 static void Cmd_Wait_f (void)
62 {
63         cmd_wait = true;
64 }
65
66 /*
67 =============================================================================
68
69                                                 COMMAND BUFFER
70
71 =============================================================================
72 */
73
74 static sizebuf_t        cmd_text;
75 static unsigned char            cmd_text_buf[CMDBUFSIZE];
76
77 /*
78 ============
79 Cbuf_AddText
80
81 Adds command text at the end of the buffer
82 ============
83 */
84 void Cbuf_AddText (const char *text)
85 {
86         int             l;
87
88         l = (int)strlen (text);
89
90         if (cmd_text.cursize + l >= cmd_text.maxsize)
91         {
92                 Con_Print("Cbuf_AddText: overflow\n");
93                 return;
94         }
95
96         SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
97 }
98
99
100 /*
101 ============
102 Cbuf_InsertText
103
104 Adds command text immediately after the current command
105 Adds a \n to the text
106 FIXME: actually change the command buffer to do less copying
107 ============
108 */
109 void Cbuf_InsertText (const char *text)
110 {
111         char    *temp;
112         int             templen;
113
114         // copy off any commands still remaining in the exec buffer
115         templen = cmd_text.cursize;
116         if (templen)
117         {
118                 temp = (char *)Mem_Alloc (tempmempool, templen);
119                 memcpy (temp, cmd_text.data, templen);
120                 SZ_Clear (&cmd_text);
121         }
122         else
123                 temp = NULL;
124
125         // add the entire text of the file
126         Cbuf_AddText (text);
127
128         // add the copied off data
129         if (temp != NULL)
130         {
131                 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
132                 Mem_Free (temp);
133         }
134 }
135
136 /*
137 ============
138 Cbuf_Execute
139 ============
140 */
141 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
142 void Cbuf_Execute (void)
143 {
144         int i;
145         char *text;
146         char line[MAX_INPUTLINE];
147         char preprocessed[MAX_INPUTLINE];
148         char *firstchar;
149         int quotes;
150
151         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
152         cmd_tokenizebufferpos = 0;
153
154         while (cmd_text.cursize)
155         {
156 // find a \n or ; line break
157                 text = (char *)cmd_text.data;
158
159                 quotes = 0;
160                 for (i=0 ; i< cmd_text.cursize ; i++)
161                 {
162                         if (text[i] == '"')
163                                 quotes ^= 1;
164                         if (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\'))
165                                 i++;
166                         if ( !quotes &&  text[i] == ';')
167                                 break;  // don't break if inside a quoted string
168                         if (text[i] == '\r' || text[i] == '\n')
169                                 break;
170                 }
171
172                 /* should never happen
173                 if(i >= MAX_INPUTLINE)
174                         i = MAX_INPUTLINE - 1;
175                 */
176
177                 memcpy (line, text, i);
178                 line[i] = 0;
179
180 // delete the text from the command buffer and move remaining commands down
181 // this is necessary because commands (exec, alias) can insert data at the
182 // beginning of the text buffer
183
184                 if (i == cmd_text.cursize)
185                         cmd_text.cursize = 0;
186                 else
187                 {
188                         i++;
189                         cmd_text.cursize -= i;
190                         memmove (cmd_text.data, text+i, cmd_text.cursize);
191                 }
192
193 // execute the command line
194                 firstchar = line + strspn(line, " \t");
195                 if(
196                         (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
197                         &&
198                         (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
199                         &&
200                         (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
201                 )
202                 {
203                         Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
204                         Cmd_ExecuteString (preprocessed, src_command);
205                 }
206                 else
207                 {
208                         Cmd_ExecuteString (line, src_command);
209                 }
210
211                 if (cmd_wait)
212                 {       // skip out while text still remains in buffer, leaving it
213                         // for next frame
214                         cmd_wait = false;
215                         break;
216                 }
217         }
218 }
219
220 /*
221 ==============================================================================
222
223                                                 SCRIPT COMMANDS
224
225 ==============================================================================
226 */
227
228 /*
229 ===============
230 Cmd_StuffCmds_f
231
232 Adds command line parameters as script statements
233 Commands lead with a +, and continue until a - or another +
234 quake +prog jctest.qp +cmd amlev1
235 quake -nosound +cmd amlev1
236 ===============
237 */
238 qboolean host_stuffcmdsrun = false;
239 void Cmd_StuffCmds_f (void)
240 {
241         int             i, j, l;
242         // this is for all commandline options combined (and is bounds checked)
243         char    build[MAX_INPUTLINE];
244
245         if (Cmd_Argc () != 1)
246         {
247                 Con_Print("stuffcmds : execute command line parameters\n");
248                 return;
249         }
250
251         // no reason to run the commandline arguments twice
252         if (host_stuffcmdsrun)
253                 return;
254
255         host_stuffcmdsrun = true;
256         build[0] = 0;
257         l = 0;
258         for (i = 0;i < com_argc;i++)
259         {
260                 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9') && l + strlen(com_argv[i]) - 1 <= sizeof(build) - 1)
261                 {
262                         j = 1;
263                         while (com_argv[i][j])
264                                 build[l++] = com_argv[i][j++];
265                         i++;
266                         for (;i < com_argc;i++)
267                         {
268                                 if (!com_argv[i])
269                                         continue;
270                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
271                                         break;
272                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
273                                         break;
274                                 build[l++] = ' ';
275                                 if (strchr(com_argv[i], ' '))
276                                         build[l++] = '\"';
277                                 for (j = 0;com_argv[i][j];j++)
278                                         build[l++] = com_argv[i][j];
279                                 if (strchr(com_argv[i], ' '))
280                                         build[l++] = '\"';
281                         }
282                         build[l++] = '\n';
283                         i--;
284                 }
285         }
286         // now terminate the combined string and prepend it to the command buffer
287         // we already reserved space for the terminator
288         build[l++] = 0;
289         Cbuf_InsertText (build);
290 }
291
292
293 /*
294 ===============
295 Cmd_Exec_f
296 ===============
297 */
298 static void Cmd_Exec_f (void)
299 {
300         char *f;
301
302         if (Cmd_Argc () != 2)
303         {
304                 Con_Print("exec <filename> : execute a script file\n");
305                 return;
306         }
307
308         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
309         if (!f)
310         {
311                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
312                 return;
313         }
314         Con_Printf("execing %s\n",Cmd_Argv(1));
315
316         // if executing default.cfg for the first time, lock the cvar defaults
317         // it may seem backwards to insert this text BEFORE the default.cfg
318         // but Cbuf_InsertText inserts before, so this actually ends up after it.
319         if (!strcmp(Cmd_Argv(1), "default.cfg"))
320                 Cbuf_InsertText("\ncvar_lockdefaults\n");
321
322         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
323         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
324         Cbuf_InsertText ("\n");
325         Cbuf_InsertText (f);
326         Mem_Free(f);
327 }
328
329
330 /*
331 ===============
332 Cmd_Echo_f
333
334 Just prints the rest of the line to the console
335 ===============
336 */
337 static void Cmd_Echo_f (void)
338 {
339         int             i;
340
341         for (i=1 ; i<Cmd_Argc() ; i++)
342                 Con_Printf("%s ",Cmd_Argv(i));
343         Con_Print("\n");
344 }
345
346 // DRESK - 5/14/06
347 // Support Doom3-style Toggle Console Command
348 /*
349 ===============
350 Cmd_Toggle_f
351
352 Toggles a specified console variable amongst the values specified (default is 0 and 1)
353 ===============
354 */
355 static void Cmd_Toggle_f(void)
356 {
357         // Acquire Number of Arguments
358         int nNumArgs = Cmd_Argc();
359
360         if(nNumArgs == 1)
361                 // No Arguments Specified; Print Usage
362                 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");
363         else
364         { // Correct Arguments Specified
365                 // Acquire Potential CVar
366                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
367
368                 if(cvCVar != NULL)
369                 { // Valid CVar
370                         if(nNumArgs == 2)
371                         { // Default Usage
372                                 if(cvCVar->integer)
373                                         Cvar_SetValueQuick(cvCVar, 0);
374                                 else
375                                         Cvar_SetValueQuick(cvCVar, 1);
376                         }
377                         else
378                         if(nNumArgs == 3)
379                         { // 0 and Specified Usage
380                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
381                                         // CVar is Specified Value; // Reset to 0
382                                         Cvar_SetValueQuick(cvCVar, 0);
383                                 else
384                                 if(cvCVar->integer == 0)
385                                         // CVar is 0; Specify Value
386                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
387                                 else
388                                         // CVar does not match; Reset to 0
389                                         Cvar_SetValueQuick(cvCVar, 0);
390                         }
391                         else
392                         { // Variable Values Specified
393                                 int nCnt;
394                                 int bFound = 0;
395
396                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
397                                 { // Cycle through Values
398                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
399                                         { // Current Value Located; Increment to Next
400                                                 if( (nCnt + 1) == nNumArgs)
401                                                         // Max Value Reached; Reset
402                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
403                                                 else
404                                                         // Next Value
405                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
406
407                                                 // End Loop
408                                                 nCnt = nNumArgs;
409                                                 // Assign Found
410                                                 bFound = 1;
411                                         }
412                                 }
413                                 if(!bFound)
414                                         // Value not Found; Reset to Original
415                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
416                         }
417
418                 }
419                 else
420                 { // Invalid CVar
421                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
422                 }
423         }
424 }
425
426 /*
427 ===============
428 Cmd_Alias_f
429
430 Creates a new command that executes a command string (possibly ; seperated)
431 ===============
432 */
433 static void Cmd_Alias_f (void)
434 {
435         cmdalias_t      *a;
436         char            cmd[MAX_INPUTLINE];
437         int                     i, c;
438         const char              *s;
439         size_t          alloclen;
440
441         if (Cmd_Argc() == 1)
442         {
443                 Con_Print("Current alias commands:\n");
444                 for (a = cmd_alias ; a ; a=a->next)
445                         Con_Printf("%s : %s\n", a->name, a->value);
446                 return;
447         }
448
449         s = Cmd_Argv(1);
450         if (strlen(s) >= MAX_ALIAS_NAME)
451         {
452                 Con_Print("Alias name is too long\n");
453                 return;
454         }
455
456         // if the alias already exists, reuse it
457         for (a = cmd_alias ; a ; a=a->next)
458         {
459                 if (!strcmp(s, a->name))
460                 {
461                         Z_Free (a->value);
462                         break;
463                 }
464         }
465
466         if (!a)
467         {
468                 cmdalias_t *prev, *current;
469
470                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
471                 strlcpy (a->name, s, sizeof (a->name));
472                 // insert it at the right alphanumeric position
473                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
474                         ;
475                 if( prev ) {
476                         prev->next = a;
477                 } else {
478                         cmd_alias = a;
479                 }
480                 a->next = current;
481         }
482
483
484 // copy the rest of the command line
485         cmd[0] = 0;             // start out with a null string
486         c = Cmd_Argc();
487         for (i=2 ; i< c ; i++)
488         {
489                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
490                 if (i != c)
491                         strlcat (cmd, " ", sizeof (cmd));
492         }
493         strlcat (cmd, "\n", sizeof (cmd));
494
495         alloclen = strlen (cmd) + 1;
496         a->value = (char *)Z_Malloc (alloclen);
497         memcpy (a->value, cmd, alloclen);
498 }
499
500 /*
501 =============================================================================
502
503                                         COMMAND EXECUTION
504
505 =============================================================================
506 */
507
508 typedef struct cmd_function_s
509 {
510         struct cmd_function_s *next;
511         const char *name;
512         const char *description;
513         xcommand_t consolefunction;
514         xcommand_t clientfunction;
515         qboolean csqcfunc;
516 } cmd_function_t;
517
518 static int cmd_argc;
519 static const char *cmd_argv[MAX_ARGS];
520 static const char *cmd_null_string = "";
521 static const char *cmd_args;
522 cmd_source_t cmd_source;
523
524
525 static cmd_function_t *cmd_functions;           // possible commands to execute
526
527 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
528 {
529         cvar_t *cvar;
530         long argno;
531         char *endptr;
532
533         if(is_multiple)
534                 *is_multiple = false;
535
536         if(!varname || !*varname)
537                 return NULL;
538
539         if(alias)
540         {
541                 if(!strcmp(varname, "*"))
542                 {
543                         if(is_multiple)
544                                 *is_multiple = true;
545                         return Cmd_Args();
546                 }
547                 else if(varname[strlen(varname) - 1] == '-')
548                 {
549                         argno = strtol(varname, &endptr, 10);
550                         if(endptr == varname + strlen(varname) - 1)
551                         {
552                                 // whole string is a number, apart from the -
553                                 const char *p = Cmd_Args();
554                                 for(; argno > 1; --argno)
555                                         if(!COM_ParseToken_Console(&p))
556                                                 break;
557                                 if(p)
558                                 {
559                                         if(is_multiple)
560                                                 *is_multiple = true;
561
562                                         // kill pre-argument whitespace
563                                         for (;*p && *p <= ' ';p++)
564                                                 ;
565
566                                         return p;
567                                 }
568                         }
569                 }
570                 else
571                 {
572                         argno = strtol(varname, &endptr, 10);
573                         if(*endptr == 0)
574                         {
575                                 // whole string is a number
576                                 // NOTE: we already made sure we don't have an empty cvar name!
577                                 if(argno >= 0 && argno < Cmd_Argc())
578                                         return Cmd_Argv(argno);
579                         }
580                 }
581         }
582
583         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
584                 return cvar->string;
585
586         return NULL;
587 }
588
589 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
590 {
591         qboolean quote_quot = !!strchr(quoteset, '"');
592         qboolean quote_backslash = !!strchr(quoteset, '\\');
593         qboolean quote_dollar = !!strchr(quoteset, '$');
594
595         while(*in)
596         {
597                 if(*in == '"' && quote_quot)
598                 {
599                         if(outlen <= 2)
600                         {
601                                 *out++ = 0;
602                                 return false;
603                         }
604                         *out++ = '\\'; --outlen;
605                         *out++ = '"'; --outlen;
606                 }
607                 else if(*in == '\\' && quote_backslash)
608                 {
609                         if(outlen <= 2)
610                         {
611                                 *out++ = 0;
612                                 return false;
613                         }
614                         *out++ = '\\'; --outlen;
615                         *out++ = '\\'; --outlen;
616                 }
617                 else if(*in == '$' && quote_dollar)
618                 {
619                         if(outlen <= 2)
620                         {
621                                 *out++ = 0;
622                                 return false;
623                         }
624                         *out++ = '$'; --outlen;
625                         *out++ = '$'; --outlen;
626                 }
627                 else
628                 {
629                         if(outlen <= 1)
630                         {
631                                 *out++ = 0;
632                                 return false;
633                         }
634                         *out++ = *in; --outlen;
635                 }
636                 ++in;
637         }
638         *out++ = 0;
639         return true;
640 }
641
642 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
643 {
644         static char varname[MAX_INPUTLINE];
645         static char varval[MAX_INPUTLINE];
646         const char *varstr;
647         char *varfunc;
648
649         if(varlen >= MAX_INPUTLINE)
650                 varlen = MAX_INPUTLINE - 1;
651         memcpy(varname, var, varlen);
652         varname[varlen] = 0;
653         varfunc = strchr(varname, ' ');
654
655         if(varfunc)
656         {
657                 *varfunc = 0;
658                 ++varfunc;
659         }
660
661         if(*var == 0)
662         {
663                 // empty cvar name?
664                 return NULL;
665         }
666
667         varstr = NULL;
668
669         if(varname[0] == '$')
670                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
671         else
672         {
673                 qboolean is_multiple = false;
674                 // Exception: $* and $n- don't use the quoted form by default
675                 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
676                 if(is_multiple)
677                         varfunc = "asis";
678         }
679
680         if(!varstr)
681         {
682                 if(alias)
683                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
684                 else
685                         Con_Printf("Warning: Could not expand $%s\n", varname);
686                 return NULL;
687         }
688
689         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
690         {
691                 // quote it so it can be used inside double quotes
692                 // we just need to replace " by \", and of course, double backslashes
693                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
694                 return varval;
695         }
696         else if(!strcmp(varfunc, "asis"))
697         {
698                 return varstr;
699         }
700         else
701                 Con_Printf("Unknown variable function %s\n", varfunc);
702
703         return varstr;
704 }
705
706 /*
707 Cmd_PreprocessString
708
709 Preprocesses strings and replaces $*, $param#, $cvar accordingly
710 */
711 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
712         const char *in;
713         size_t eat, varlen;
714         unsigned outlen;
715         const char *val;
716
717         // don't crash if there's no room in the outtext buffer
718         if( maxoutlen == 0 ) {
719                 return;
720         }
721         maxoutlen--; // because of \0
722
723         in = intext;
724         outlen = 0;
725
726         while( *in && outlen < maxoutlen ) {
727                 if( *in == '$' ) {
728                         // this is some kind of expansion, see what comes after the $
729                         in++;
730
731                         // The console does the following preprocessing:
732                         //
733                         // - $$ is transformed to a single dollar sign.
734                         // - $var or ${var} are expanded to the contents of the named cvar,
735                         //   with quotation marks and backslashes quoted so it can safely
736                         //   be used inside quotation marks (and it should always be used
737                         //   that way)
738                         // - ${var asis} inserts the cvar value as is, without doing this
739                         //   quoting
740                         // - prefix the cvar name with a dollar sign to do indirection;
741                         //   for example, if $x has the value timelimit, ${$x} will return
742                         //   the value of $timelimit
743                         // - when expanding an alias, the special variable name $* refers
744                         //   to all alias parameters, and a number refers to that numbered
745                         //   alias parameter, where the name of the alias is $0, the first
746                         //   parameter is $1 and so on; as a special case, $* inserts all
747                         //   parameters, without extra quoting, so one can use $* to just
748                         //   pass all parameters around. All parameters starting from $n
749                         //   can be referred to as $n- (so $* is equivalent to $1-).
750                         //
751                         // Note: when expanding an alias, cvar expansion is done in the SAME step
752                         // as alias expansion so that alias parameters or cvar values containing
753                         // dollar signs have no unwanted bad side effects. However, this needs to
754                         // be accounted for when writing complex aliases. For example,
755                         //   alias foo "set x NEW; echo $x"
756                         // actually expands to
757                         //   "set x NEW; echo OLD"
758                         // and will print OLD! To work around this, use a second alias:
759                         //   alias foo "set x NEW; foo2"
760                         //   alias foo2 "echo $x"
761                         //
762                         // Also note: lines starting with alias are exempt from cvar expansion.
763                         // If you want cvar expansion, write "alias" instead:
764                         //
765                         //   set x 1
766                         //   alias foo "echo $x"
767                         //   "alias" bar "echo $x"
768                         //   set x 2
769                         //
770                         // foo will print 2, because the variable $x will be expanded when the alias
771                         // gets expanded. bar will print 1, because the variable $x was expanded
772                         // at definition time. foo can be equivalently defined as
773                         //
774                         //   "alias" foo "echo $$x"
775                         //
776                         // because at definition time, $$ will get replaced to a single $.
777
778                         if( *in == '$' ) {
779                                 val = "$";
780                                 eat = 1;
781                         } else if(*in == '{') {
782                                 varlen = strcspn(in + 1, "}");
783                                 if(in[varlen + 1] == '}')
784                                 {
785                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
786                                         eat = varlen + 2;
787                                 }
788                                 else
789                                 {
790                                         // ran out of data?
791                                         val = NULL;
792                                         eat = varlen + 1;
793                                 }
794                         } else {
795                                 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
796                                 val = Cmd_GetCvarValue(in, varlen, alias);
797                                 eat = varlen;
798                         }
799                         if(val)
800                         {
801                                 // insert the cvar value
802                                 while(*val && outlen < maxoutlen)
803                                         outtext[outlen++] = *val++;
804                                 in += eat;
805                         }
806                         else
807                         {
808                                 // copy the unexpanded text
809                                 outtext[outlen++] = '$';
810                                 while(eat && outlen < maxoutlen)
811                                 {
812                                         outtext[outlen++] = *in++;
813                                         --eat;
814                                 }
815                         }
816                 } else {
817                         outtext[outlen++] = *in++;
818                 }
819         }
820         outtext[outlen] = 0;
821 }
822
823 /*
824 ============
825 Cmd_ExecuteAlias
826
827 Called for aliases and fills in the alias into the cbuffer
828 ============
829 */
830 static void Cmd_ExecuteAlias (cmdalias_t *alias)
831 {
832         static char buffer[ MAX_INPUTLINE ];
833         static char buffer2[ MAX_INPUTLINE ];
834         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
835         // insert at start of command buffer, so that aliases execute in order
836         // (fixes bug introduced by Black on 20050705)
837
838         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
839         // have to make sure that no second variable expansion takes place, otherwise
840         // alias parameters containing dollar signs can have bad effects.
841         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
842         Cbuf_InsertText( buffer2 );
843 }
844
845 /*
846 ========
847 Cmd_List
848
849         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
850         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
851
852 ========
853 */
854 static void Cmd_List_f (void)
855 {
856         cmd_function_t *cmd;
857         const char *partial;
858         int len, count;
859
860         if (Cmd_Argc() > 1)
861         {
862                 partial = Cmd_Argv (1);
863                 len = (int)strlen(partial);
864         }
865         else
866         {
867                 partial = NULL;
868                 len = 0;
869         }
870
871         count = 0;
872         for (cmd = cmd_functions; cmd; cmd = cmd->next)
873         {
874                 if (partial && strncmp(partial, cmd->name, len))
875                         continue;
876                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
877                 count++;
878         }
879
880         if (partial)
881                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
882         else
883                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
884 }
885
886 /*
887 ============
888 Cmd_Init
889 ============
890 */
891 void Cmd_Init (void)
892 {
893         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
894         // space for commands and script files
895         cmd_text.data = cmd_text_buf;
896         cmd_text.maxsize = sizeof(cmd_text_buf);
897         cmd_text.cursize = 0;
898 }
899
900 void Cmd_Init_Commands (void)
901 {
902 //
903 // register our commands
904 //
905         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
906         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
907         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
908         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
909         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
910         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
911         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
912         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
913
914         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
915         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
916         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
917         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
918
919         Cmd_AddCommand ("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");
920         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
921         Cmd_AddCommand ("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)");
922         Cmd_AddCommand ("cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
923
924         // DRESK - 5/14/06
925         // Support Doom3-style Toggle Command
926         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
927 }
928
929 /*
930 ============
931 Cmd_Shutdown
932 ============
933 */
934 void Cmd_Shutdown(void)
935 {
936         Mem_FreePool(&cmd_mempool);
937 }
938
939 /*
940 ============
941 Cmd_Argc
942 ============
943 */
944 int             Cmd_Argc (void)
945 {
946         return cmd_argc;
947 }
948
949 /*
950 ============
951 Cmd_Argv
952 ============
953 */
954 const char *Cmd_Argv (int arg)
955 {
956         if (arg >= cmd_argc )
957                 return cmd_null_string;
958         return cmd_argv[arg];
959 }
960
961 /*
962 ============
963 Cmd_Args
964 ============
965 */
966 const char *Cmd_Args (void)
967 {
968         return cmd_args;
969 }
970
971
972 /*
973 ============
974 Cmd_TokenizeString
975
976 Parses the given string into command line tokens.
977 ============
978 */
979 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
980 static void Cmd_TokenizeString (const char *text)
981 {
982         int l;
983
984         cmd_argc = 0;
985         cmd_args = NULL;
986
987         while (1)
988         {
989                 // skip whitespace up to a /n
990                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
991                         text++;
992
993                 // line endings:
994                 // UNIX: \n
995                 // Mac: \r
996                 // Windows: \r\n
997                 if (*text == '\n' || *text == '\r')
998                 {
999                         // a newline separates commands in the buffer
1000                         if (*text == '\r' && text[1] == '\n')
1001                                 text++;
1002                         text++;
1003                         break;
1004                 }
1005
1006                 if (!*text)
1007                         return;
1008
1009                 if (cmd_argc == 1)
1010                         cmd_args = text;
1011
1012                 if (!COM_ParseToken_Console(&text))
1013                         return;
1014
1015                 if (cmd_argc < MAX_ARGS)
1016                 {
1017                         l = (int)strlen(com_token) + 1;
1018                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1019                         {
1020                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1021                                 break;
1022                         }
1023                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1024                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1025                         cmd_tokenizebufferpos += l;
1026                         cmd_argc++;
1027                 }
1028         }
1029 }
1030
1031
1032 /*
1033 ============
1034 Cmd_AddCommand
1035 ============
1036 */
1037 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1038 {
1039         cmd_function_t *cmd;
1040         cmd_function_t *prev, *current;
1041
1042 // fail if the command is a variable name
1043         if (Cvar_FindVar( cmd_name ))
1044         {
1045                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1046                 return;
1047         }
1048
1049 // fail if the command already exists
1050         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1051         {
1052                 if (!strcmp (cmd_name, cmd->name))
1053                 {
1054                         if (consolefunction || clientfunction)
1055                         {
1056                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1057                                 return;
1058                         }
1059                         else    //[515]: csqc
1060                         {
1061                                 cmd->csqcfunc = true;
1062                                 return;
1063                         }
1064                 }
1065         }
1066
1067         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1068         cmd->name = cmd_name;
1069         cmd->consolefunction = consolefunction;
1070         cmd->clientfunction = clientfunction;
1071         cmd->description = description;
1072         if(!consolefunction && !clientfunction)                 //[515]: csqc
1073                 cmd->csqcfunc = true;
1074         cmd->next = cmd_functions;
1075
1076 // insert it at the right alphanumeric position
1077         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1078                 ;
1079         if( prev ) {
1080                 prev->next = cmd;
1081         } else {
1082                 cmd_functions = cmd;
1083         }
1084         cmd->next = current;
1085 }
1086
1087 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1088 {
1089         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1090 }
1091
1092 /*
1093 ============
1094 Cmd_Exists
1095 ============
1096 */
1097 qboolean Cmd_Exists (const char *cmd_name)
1098 {
1099         cmd_function_t  *cmd;
1100
1101         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1102                 if (!strcmp (cmd_name,cmd->name))
1103                         return true;
1104
1105         return false;
1106 }
1107
1108
1109 /*
1110 ============
1111 Cmd_CompleteCommand
1112 ============
1113 */
1114 const char *Cmd_CompleteCommand (const char *partial)
1115 {
1116         cmd_function_t *cmd;
1117         size_t len;
1118
1119         len = strlen(partial);
1120
1121         if (!len)
1122                 return NULL;
1123
1124 // check functions
1125         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1126                 if (!strncasecmp(partial, cmd->name, len))
1127                         return cmd->name;
1128
1129         return NULL;
1130 }
1131
1132 /*
1133         Cmd_CompleteCountPossible
1134
1135         New function for tab-completion system
1136         Added by EvilTypeGuy
1137         Thanks to Fett erich@heintz.com
1138         Thanks to taniwha
1139
1140 */
1141 int Cmd_CompleteCountPossible (const char *partial)
1142 {
1143         cmd_function_t *cmd;
1144         size_t len;
1145         int h;
1146
1147         h = 0;
1148         len = strlen(partial);
1149
1150         if (!len)
1151                 return 0;
1152
1153         // Loop through the command list and count all partial matches
1154         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1155                 if (!strncasecmp(partial, cmd->name, len))
1156                         h++;
1157
1158         return h;
1159 }
1160
1161 /*
1162         Cmd_CompleteBuildList
1163
1164         New function for tab-completion system
1165         Added by EvilTypeGuy
1166         Thanks to Fett erich@heintz.com
1167         Thanks to taniwha
1168
1169 */
1170 const char **Cmd_CompleteBuildList (const char *partial)
1171 {
1172         cmd_function_t *cmd;
1173         size_t len = 0;
1174         size_t bpos = 0;
1175         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1176         const char **buf;
1177
1178         len = strlen(partial);
1179         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1180         // Loop through the alias list and print all matches
1181         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1182                 if (!strncasecmp(partial, cmd->name, len))
1183                         buf[bpos++] = cmd->name;
1184
1185         buf[bpos] = NULL;
1186         return buf;
1187 }
1188
1189 // written by LordHavoc
1190 void Cmd_CompleteCommandPrint (const char *partial)
1191 {
1192         cmd_function_t *cmd;
1193         size_t len = strlen(partial);
1194         // Loop through the command list and print all matches
1195         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1196                 if (!strncasecmp(partial, cmd->name, len))
1197                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
1198 }
1199
1200 /*
1201         Cmd_CompleteAlias
1202
1203         New function for tab-completion system
1204         Added by EvilTypeGuy
1205         Thanks to Fett erich@heintz.com
1206         Thanks to taniwha
1207
1208 */
1209 const char *Cmd_CompleteAlias (const char *partial)
1210 {
1211         cmdalias_t *alias;
1212         size_t len;
1213
1214         len = strlen(partial);
1215
1216         if (!len)
1217                 return NULL;
1218
1219         // Check functions
1220         for (alias = cmd_alias; alias; alias = alias->next)
1221                 if (!strncasecmp(partial, alias->name, len))
1222                         return alias->name;
1223
1224         return NULL;
1225 }
1226
1227 // written by LordHavoc
1228 void Cmd_CompleteAliasPrint (const char *partial)
1229 {
1230         cmdalias_t *alias;
1231         size_t len = strlen(partial);
1232         // Loop through the alias list and print all matches
1233         for (alias = cmd_alias; alias; alias = alias->next)
1234                 if (!strncasecmp(partial, alias->name, len))
1235                         Con_Printf("%s : %s\n", alias->name, alias->value);
1236 }
1237
1238
1239 /*
1240         Cmd_CompleteAliasCountPossible
1241
1242         New function for tab-completion system
1243         Added by EvilTypeGuy
1244         Thanks to Fett erich@heintz.com
1245         Thanks to taniwha
1246
1247 */
1248 int Cmd_CompleteAliasCountPossible (const char *partial)
1249 {
1250         cmdalias_t      *alias;
1251         size_t          len;
1252         int                     h;
1253
1254         h = 0;
1255
1256         len = strlen(partial);
1257
1258         if (!len)
1259                 return 0;
1260
1261         // Loop through the command list and count all partial matches
1262         for (alias = cmd_alias; alias; alias = alias->next)
1263                 if (!strncasecmp(partial, alias->name, len))
1264                         h++;
1265
1266         return h;
1267 }
1268
1269 /*
1270         Cmd_CompleteAliasBuildList
1271
1272         New function for tab-completion system
1273         Added by EvilTypeGuy
1274         Thanks to Fett erich@heintz.com
1275         Thanks to taniwha
1276
1277 */
1278 const char **Cmd_CompleteAliasBuildList (const char *partial)
1279 {
1280         cmdalias_t *alias;
1281         size_t len = 0;
1282         size_t bpos = 0;
1283         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1284         const char **buf;
1285
1286         len = strlen(partial);
1287         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1288         // Loop through the alias list and print all matches
1289         for (alias = cmd_alias; alias; alias = alias->next)
1290                 if (!strncasecmp(partial, alias->name, len))
1291                         buf[bpos++] = alias->name;
1292
1293         buf[bpos] = NULL;
1294         return buf;
1295 }
1296
1297 void Cmd_ClearCsqcFuncs (void)
1298 {
1299         cmd_function_t *cmd;
1300         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1301                 cmd->csqcfunc = false;
1302 }
1303
1304 qboolean CL_VM_ConsoleCommand (const char *cmd);
1305 /*
1306 ============
1307 Cmd_ExecuteString
1308
1309 A complete command line has been parsed, so try to execute it
1310 FIXME: lookupnoadd the token to speed search?
1311 ============
1312 */
1313 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1314 {
1315         int oldpos;
1316         cmd_function_t *cmd;
1317         cmdalias_t *a;
1318
1319         oldpos = cmd_tokenizebufferpos;
1320         cmd_source = src;
1321
1322         Cmd_TokenizeString (text);
1323
1324 // execute the command line
1325         if (!Cmd_Argc())
1326         {
1327                 cmd_tokenizebufferpos = oldpos;
1328                 return;         // no tokens
1329         }
1330
1331 // check functions
1332         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1333         {
1334                 if (!strcasecmp (cmd_argv[0],cmd->name))
1335                 {
1336                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1337                                 return;
1338                         switch (src)
1339                         {
1340                         case src_command:
1341                                 if (cmd->consolefunction)
1342                                         cmd->consolefunction ();
1343                                 else if (cmd->clientfunction)
1344                                 {
1345                                         if (cls.state == ca_connected)
1346                                         {
1347                                                 // forward remote commands to the server for execution
1348                                                 Cmd_ForwardToServer();
1349                                         }
1350                                         else
1351                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1352                                 }
1353                                 else
1354                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1355                                 cmd_tokenizebufferpos = oldpos;
1356                                 return;
1357                         case src_client:
1358                                 if (cmd->clientfunction)
1359                                 {
1360                                         cmd->clientfunction ();
1361                                         cmd_tokenizebufferpos = oldpos;
1362                                         return;
1363                                 }
1364                                 break;
1365                         }
1366                         break;
1367                 }
1368         }
1369
1370         // if it's a client command and no command was found, say so.
1371         if (cmd_source == src_client)
1372         {
1373                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1374                 return;
1375         }
1376
1377 // check alias
1378         for (a=cmd_alias ; a ; a=a->next)
1379         {
1380                 if (!strcasecmp (cmd_argv[0], a->name))
1381                 {
1382                         Cmd_ExecuteAlias(a);
1383                         cmd_tokenizebufferpos = oldpos;
1384                         return;
1385                 }
1386         }
1387
1388 // check cvars
1389         if (!Cvar_Command () && host_framecount > 0)
1390                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1391
1392         cmd_tokenizebufferpos = oldpos;
1393 }
1394
1395
1396 /*
1397 ===================
1398 Cmd_ForwardStringToServer
1399
1400 Sends an entire command string over to the server, unprocessed
1401 ===================
1402 */
1403 void Cmd_ForwardStringToServer (const char *s)
1404 {
1405         char temp[128];
1406         if (cls.state != ca_connected)
1407         {
1408                 Con_Printf("Can't \"%s\", not connected\n", s);
1409                 return;
1410         }
1411
1412         if (!cls.netcon)
1413                 return;
1414
1415         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1416         // attention, it has been eradicated from here, its only (former) use in
1417         // all of darkplaces.
1418         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1419                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1420         else
1421                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1422         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1423         {
1424                 // say/say_team commands can replace % character codes with status info
1425                 while (*s)
1426                 {
1427                         if (*s == '%' && s[1])
1428                         {
1429                                 // handle proquake message macros
1430                                 temp[0] = 0;
1431                                 switch (s[1])
1432                                 {
1433                                 case 'l': // current location
1434                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1435                                         break;
1436                                 case 'h': // current health
1437                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1438                                         break;
1439                                 case 'a': // current armor
1440                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1441                                         break;
1442                                 case 'x': // current rockets
1443                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1444                                         break;
1445                                 case 'c': // current cells
1446                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1447                                         break;
1448                                 // silly proquake macros
1449                                 case 'd': // loc at last death
1450                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1451                                         break;
1452                                 case 't': // current time
1453                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1454                                         break;
1455                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1456                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1457                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1458                                         else if (!cl.stats[STAT_ROCKETS])
1459                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1460                                         else
1461                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1462                                         break;
1463                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1464                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1465                                         {
1466                                                 if (temp[0])
1467                                                         strlcat(temp, " ", sizeof(temp));
1468                                                 strlcat(temp, "quad", sizeof(temp));
1469                                         }
1470                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1471                                         {
1472                                                 if (temp[0])
1473                                                         strlcat(temp, " ", sizeof(temp));
1474                                                 strlcat(temp, "pent", sizeof(temp));
1475                                         }
1476                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1477                                         {
1478                                                 if (temp[0])
1479                                                         strlcat(temp, " ", sizeof(temp));
1480                                                 strlcat(temp, "eyes", sizeof(temp));
1481                                         }
1482                                         break;
1483                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1484                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1485                                                 strlcat(temp, "SSG", sizeof(temp));
1486                                         strlcat(temp, ":", sizeof(temp));
1487                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1488                                                 strlcat(temp, "NG", sizeof(temp));
1489                                         strlcat(temp, ":", sizeof(temp));
1490                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1491                                                 strlcat(temp, "SNG", sizeof(temp));
1492                                         strlcat(temp, ":", sizeof(temp));
1493                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1494                                                 strlcat(temp, "GL", sizeof(temp));
1495                                         strlcat(temp, ":", sizeof(temp));
1496                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1497                                                 strlcat(temp, "RL", sizeof(temp));
1498                                         strlcat(temp, ":", sizeof(temp));
1499                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1500                                                 strlcat(temp, "LG", sizeof(temp));
1501                                         break;
1502                                 default:
1503                                         // not a recognized macro, print it as-is...
1504                                         temp[0] = s[0];
1505                                         temp[1] = s[1];
1506                                         temp[2] = 0;
1507                                         break;
1508                                 }
1509                                 // write the resulting text
1510                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1511                                 s += 2;
1512                                 continue;
1513                         }
1514                         MSG_WriteByte(&cls.netcon->message, *s);
1515                         s++;
1516                 }
1517                 MSG_WriteByte(&cls.netcon->message, 0);
1518         }
1519         else // any other command is passed on as-is
1520                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1521 }
1522
1523 /*
1524 ===================
1525 Cmd_ForwardToServer
1526
1527 Sends the entire command line over to the server
1528 ===================
1529 */
1530 void Cmd_ForwardToServer (void)
1531 {
1532         const char *s;
1533         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1534         {
1535                 // we want to strip off "cmd", so just send the args
1536                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1537         }
1538         else
1539         {
1540                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1541                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1542         }
1543         // don't send an empty forward message if the user tries "cmd" by itself
1544         if (!s || !*s)
1545                 return;
1546         Cmd_ForwardStringToServer(s);
1547 }
1548
1549
1550 /*
1551 ================
1552 Cmd_CheckParm
1553
1554 Returns the position (1 to argc-1) in the command's argument list
1555 where the given parameter apears, or 0 if not present
1556 ================
1557 */
1558
1559 int Cmd_CheckParm (const char *parm)
1560 {
1561         int i;
1562
1563         if (!parm)
1564         {
1565                 Con_Printf ("Cmd_CheckParm: NULL");
1566                 return 0;
1567         }
1568
1569         for (i = 1; i < Cmd_Argc (); i++)
1570                 if (!strcasecmp (parm, Cmd_Argv (i)))
1571                         return i;
1572
1573         return 0;
1574 }
1575