Debian Codegraph @

code/qcommon/cmd.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22 // cmd.c -- Quake script command processing module
23
24 #include "q_shared.h"
25 #include "qcommon.h"
26
27 #define MAX_CMD_BUFFER 128*1024
28 #define MAX_CMD_LINE 1024
29
30 typedef struct {
31 byte *data;
32 int maxsize;
33 int cursize;
34 } cmd_t;
35
36 int cmd_wait;
37 cmd_t cmd_text;
38 byte cmd_text_buf[MAX_CMD_BUFFER];
39
40
41 //=============================================================================
42
43 /*
44 ============
45 Cmd_Wait_f
46
47 Causes execution of the remainder of the command buffer to be delayed until
48 next frame. This allows commands like:
49 bind g "cmd use rocket ; +attack ; wait ; -attack ; cmd use blaster"
50 ============
51 */
52 void Cmd_Wait_f( void ) {
53 if ( Cmd_Argc() == 2 ) {
54 cmd_wait = atoi( Cmd_Argv( 1 ) );
55 if ( cmd_wait < 0 )
56 cmd_wait = 1; // ignore the argument
57 } else {
58 cmd_wait = 1;
59 }
60 }
61
62
63 /*
64 =============================================================================
65
66 COMMAND BUFFER
67
68 =============================================================================
69 */
70
71 /*
72 ============
73 Cbuf_Init
74 ============
75 */
76 void Cbuf_Init (void)
77 {
78 cmd_text.data = cmd_text_buf;
79 cmd_text.maxsize = MAX_CMD_BUFFER;
80 cmd_text.cursize = 0;
81 }
82
83 /*
84 ============
85 Cbuf_AddText
86
87 Adds command text at the end of the buffer, does NOT add a final \n
88 ============
89 */
90 void Cbuf_AddText( const char *text ) {
91 int l;
92
93 l = strlen (text);
94
95 if (cmd_text.cursize + l >= cmd_text.maxsize)
96 {
97 Com_Printf ("Cbuf_AddText: overflow\n");
98 return;
99 }
100 Com_Memcpy(&cmd_text.data[cmd_text.cursize], text, l);
101 cmd_text.cursize += l;
102 }
103
104
105 /*
106 ============
107 Cbuf_InsertText
108
109 Adds command text immediately after the current command
110 Adds a \n to the text
111 ============
112 */
113 void Cbuf_InsertText( const char *text ) {
114 int len;
115 int i;
116
117 len = strlen( text ) + 1;
118 if ( len + cmd_text.cursize > cmd_text.maxsize ) {
119 Com_Printf( "Cbuf_InsertText overflowed\n" );
120 return;
121 }
122
123 // move the existing command text
124 for ( i = cmd_text.cursize - 1 ; i >= 0 ; i-- ) {
125 cmd_text.data[ i + len ] = cmd_text.data[ i ];
126 }
127
128 // copy the new text in
129 Com_Memcpy( cmd_text.data, text, len - 1 );
130
131 // add a \n
132 cmd_text.data[ len - 1 ] = '\n';
133
134 cmd_text.cursize += len;
135 }
136
137
138 /*
139 ============
140 Cbuf_ExecuteText
141 ============
142 */
143 void Cbuf_ExecuteText (int exec_when, const char *text)
144 {
145 switch (exec_when)
146 {
147 case EXEC_NOW:
148 if (text && strlen(text) > 0) {
149 Com_DPrintf(S_COLOR_YELLOW "EXEC_NOW %s\n", text);
150 Cmd_ExecuteString (text);
151 } else {
152 Cbuf_Execute();
153 Com_DPrintf(S_COLOR_YELLOW "EXEC_NOW %s\n", cmd_text.data);
154 }
155 break;
156 case EXEC_INSERT:
157 Cbuf_InsertText (text);
158 break;
159 case EXEC_APPEND:
160 Cbuf_AddText (text);
161 break;
162 default:
163 Com_Error (ERR_FATAL, "Cbuf_ExecuteText: bad exec_when");
164 }
165 }
166
167 /*
168 ============
169 Cbuf_Execute
170 ============
171 */
172 void Cbuf_Execute (void)
173 {
174 int i;
175 char *text;
176 char line[MAX_CMD_LINE];
177 int quotes;
178
179 // This will keep // style comments all on one line by not breaking on
180 // a semicolon. It will keep /* ... */ style comments all on one line by not
181 // breaking it for semicolon or newline.
182 qboolean in_star_comment = qfalse;
183 qboolean in_slash_comment = qfalse;
184 while (cmd_text.cursize)
185 {
186 if ( cmd_wait > 0 ) {
187 // skip out while text still remains in buffer, leaving it
188 // for next frame
189 cmd_wait--;
190 break;
191 }
192
193 // find a \n or ; line break or comment: // or /* */
194 text = (char *)cmd_text.data;
195
196 quotes = 0;
197 for (i=0 ; i< cmd_text.cursize ; i++)
198 {
199 if (text[i] == '"')
200 quotes++;
201
202 if ( !(quotes&1)) {
203 if (i < cmd_text.cursize - 1) {
204 if (! in_star_comment && text[i] == '/' && text[i+1] == '/')
205 in_slash_comment = qtrue;
206 else if (! in_slash_comment && text[i] == '/' && text[i+1] == '*')
207 in_star_comment = qtrue;
208 else if (in_star_comment && text[i] == '*' && text[i+1] == '/') {
209 in_star_comment = qfalse;
210 // If we are in a star comment, then the part after it is valid
211 // Note: This will cause it to NUL out the terminating '/'
212 // but ExecuteString doesn't require it anyway.
213 i++;
214 break;
215 }
216 }
217 if (! in_slash_comment && ! in_star_comment && text[i] == ';')
218 break;
219 }
220 if (! in_star_comment && (text[i] == '\n' || text[i] == '\r')) {
221 in_slash_comment = qfalse;
222 break;
223 }
224 }
225
226 if( i >= (MAX_CMD_LINE - 1)) {
227 i = MAX_CMD_LINE - 1;
228 }
229
230 Com_Memcpy (line, text, i);
231 line[i] = 0;
232
233 // delete the text from the command buffer and move remaining commands down
234 // this is necessary because commands (exec) can insert data at the
235 // beginning of the text buffer
236
237 if (i == cmd_text.cursize)
238 cmd_text.cursize = 0;
239 else
240 {
241 i++;
242 cmd_text.cursize -= i;
243 memmove (text, text+i, cmd_text.cursize);
244 }
245
246 // execute the command line
247
248 Cmd_ExecuteString (line);
249 }
250 }
251
252
253 /*
254 ==============================================================================
255
256 SCRIPT COMMANDS
257
258 ==============================================================================
259 */
260
261
262 /*
263 ===============
264 Cmd_Exec_f
265 ===============
266 */
267 void Cmd_Exec_f( void ) {
268 qboolean quiet;
269 union {
270 char *c;
271 void *v;
272 } f;
273 char filename[MAX_QPATH];
274
275 quiet = !Q_stricmp(Cmd_Argv(0), "execq");
276
277 if (Cmd_Argc () != 2) {
278 Com_Printf ("exec%s <filename> : execute a script file%s\n",
279 quiet ? "q" : "", quiet ? " without notification" : "");
280 return;
281 }
282
283 Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
284 COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
285 FS_ReadFile( filename, &f.v);
286 if (!f.c) {
287 Com_Printf ("couldn't exec %s\n", filename);
288 return;
289 }
290 if (!quiet)
291 Com_Printf ("execing %s\n", filename);
292
293 Cbuf_InsertText (f.c);
294
295 FS_FreeFile (f.v);
296 }
297
298
299 /*
300 ===============
301 Cmd_Vstr_f
302
303 Inserts the current value of a variable as command text
304 ===============
305 */
306 void Cmd_Vstr_f( void ) {
307 char *v;
308
309 if (Cmd_Argc () != 2) {
310 Com_Printf ("vstr <variablename> : execute a variable command\n");
311 return;
312 }
313
314 v = Cvar_VariableString( Cmd_Argv( 1 ) );
315 Cbuf_InsertText( va("%s\n", v ) );
316 }
317
318
319 /*
320 ===============
321 Cmd_Echo_f
322
323 Just prints the rest of the line to the console
324 ===============
325 */
326 void Cmd_Echo_f (void)
327 {
328 Com_Printf ("%s\n", Cmd_Args());
329 }
330
331
332 /*
333 =============================================================================
334
335 COMMAND EXECUTION
336
337 =============================================================================
338 */
339
340 typedef struct cmd_function_s
341 {
342 struct cmd_function_s *next;
343 char *name;
344 xcommand_t function;
345 completionFunc_t complete;
346 } cmd_function_t;
347
348
349 static int cmd_argc;
350 static char *cmd_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized
351 static char cmd_tokenized[BIG_INFO_STRING+MAX_STRING_TOKENS]; // will have 0 bytes inserted
352 static char cmd_cmd[BIG_INFO_STRING]; // the original command we received (no token processing)
353
354 static cmd_function_t *cmd_functions; // possible commands to execute
355
356 /*
357 ============
358 Cmd_Argc
359 ============
360 */
361 int Cmd_Argc( void ) {
362 return cmd_argc;
363 }
364
365 /*
366 ============
367 Cmd_Argv
368 ============
369 */
370 char *Cmd_Argv( int arg ) {
371 if ( (unsigned)arg >= cmd_argc ) {
372 return "";
373 }
374 return cmd_argv[arg];
375 }
376
377 /*
378 ============
379 Cmd_ArgvBuffer
380
381 The interpreted versions use this because
382 they can't have pointers returned to them
383 ============
384 */
385 void Cmd_ArgvBuffer( int arg, char *buffer, int bufferLength ) {
386 Q_strncpyz( buffer, Cmd_Argv( arg ), bufferLength );
387 }
388
389
390 /*
391 ============
392 Cmd_Args
393
394 Returns a single string containing argv(1) to argv(argc()-1)
395 ============
396 */
397 char *Cmd_Args( void ) {
398 static char cmd_args[MAX_STRING_CHARS];
399 int i;
400
401 cmd_args[0] = 0;
402 for ( i = 1 ; i < cmd_argc ; i++ ) {
403 strcat( cmd_args, cmd_argv[i] );
404 if ( i != cmd_argc-1 ) {
405 strcat( cmd_args, " " );
406 }
407 }
408
409 return cmd_args;
410 }
411
412 /*
413 ============
414 Cmd_Args
415
416 Returns a single string containing argv(arg) to argv(argc()-1)
417 ============
418 */
419 char *Cmd_ArgsFrom( int arg ) {
420 static char cmd_args[BIG_INFO_STRING];
421 int i;
422
423 cmd_args[0] = 0;
424 if (arg < 0)
425 arg = 0;
426 for ( i = arg ; i < cmd_argc ; i++ ) {
427 strcat( cmd_args, cmd_argv[i] );
428 if ( i != cmd_argc-1 ) {
429 strcat( cmd_args, " " );
430 }
431 }
432
433 return cmd_args;
434 }
435
436 /*
437 ============
438 Cmd_ArgsBuffer
439
440 The interpreted versions use this because
441 they can't have pointers returned to them
442 ============
443 */
444 void Cmd_ArgsBuffer( char *buffer, int bufferLength ) {
445 Q_strncpyz( buffer, Cmd_Args(), bufferLength );
446 }
447
448 /*
449 ============
450 Cmd_Cmd
451
452 Retrieve the unmodified command string
453 For rcon use when you want to transmit without altering quoting
454 https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
455 ============
456 */
457 char *Cmd_Cmd(void)
458 {
459 return cmd_cmd;
460 }
461
462 /*
463 Replace command separators with space to prevent interpretation
464 This is a hack to protect buggy qvms
465 https://bugzilla.icculus.org/show_bug.cgi?id=3593
466 https://bugzilla.icculus.org/show_bug.cgi?id=4769
467 */
468
469 void Cmd_Args_Sanitize(void)
470 {
471 int i;
472
473 for(i = 1; i < cmd_argc; i++)
474 {
475 char *c = cmd_argv[i];
476
477 if(strlen(c) > MAX_CVAR_VALUE_STRING - 1)
478 c[MAX_CVAR_VALUE_STRING - 1] = '\0';
479
480 while ((c = strpbrk(c, "\n\r;"))) {
481 *c = ' ';
482 ++c;
483 }
484 }
485 }
486
487 /*
488 ============
489 Cmd_TokenizeString
490
491 Parses the given string into command line tokens.
492 The text is copied to a separate buffer and 0 characters
493 are inserted in the appropriate place, The argv array
494 will point into this temporary buffer.
495 ============
496 */
497 // NOTE TTimo define that to track tokenization issues
498 //#define TKN_DBG
499 static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) {
500 const char *text;
501 char *textOut;
502
503 #ifdef TKN_DBG
504 // FIXME TTimo blunt hook to try to find the tokenization of userinfo
505 Com_DPrintf("Cmd_TokenizeString: %s\n", text_in);
506 #endif
507
508 // clear previous args
509 cmd_argc = 0;
510
511 if ( !text_in ) {
512 return;
513 }
514
515 Q_strncpyz( cmd_cmd, text_in, sizeof(cmd_cmd) );
516
517 text = text_in;
518 textOut = cmd_tokenized;
519
520 while ( 1 ) {
521 if ( cmd_argc == MAX_STRING_TOKENS ) {
522 return; // this is usually something malicious
523 }
524
525 while ( 1 ) {
526 // skip whitespace
527 while ( *text && *text <= ' ' ) {
528 text++;
529 }
530 if ( !*text ) {
531 return; // all tokens parsed
532 }
533
534 // skip // comments
535 if ( text[0] == '/' && text[1] == '/' ) {
536 return; // all tokens parsed
537 }
538
539 // skip /* */ comments
540 if ( text[0] == '/' && text[1] =='*' ) {
541 while ( *text && ( text[0] != '*' || text[1] != '/' ) ) {
542 text++;
543 }
544 if ( !*text ) {
545 return; // all tokens parsed
546 }
547 text += 2;
548 } else {
549 break; // we are ready to parse a token
550 }
551 }
552
553 // handle quoted strings
554 // NOTE TTimo this doesn't handle \" escaping
555 if ( !ignoreQuotes && *text == '"' ) {
556 cmd_argv[cmd_argc] = textOut;
557 cmd_argc++;
558 text++;
559 while ( *text && *text != '"' ) {
560 *textOut++ = *text++;
561 }
562 *textOut++ = 0;
563 if ( !*text ) {
564 return; // all tokens parsed
565 }
566 text++;
567 continue;
568 }
569
570 // regular token
571 cmd_argv[cmd_argc] = textOut;
572 cmd_argc++;
573
574 // skip until whitespace, quote, or command
575 while ( *text > ' ' ) {
576 if ( !ignoreQuotes && text[0] == '"' ) {
577 break;
578 }
579
580 if ( text[0] == '/' && text[1] == '/' ) {
581 break;
582 }
583
584 // skip /* */ comments
585 if ( text[0] == '/' && text[1] =='*' ) {
586 break;
587 }
588
589 *textOut++ = *text++;
590 }
591
592 *textOut++ = 0;
593
594 if ( !*text ) {
595 return; // all tokens parsed
596 }
597 }
598
599 }
600
601 /*
602 ============
603 Cmd_TokenizeString
604 ============
605 */
606 void Cmd_TokenizeString( const char *text_in ) {
607 Cmd_TokenizeString2( text_in, qfalse );
608 }
609
610 /*
611 ============
612 Cmd_TokenizeStringIgnoreQuotes
613 ============
614 */
615 void Cmd_TokenizeStringIgnoreQuotes( const char *text_in ) {
616 Cmd_TokenizeString2( text_in, qtrue );
617 }
618
619 /*
620 ============
621 Cmd_FindCommand
622 ============
623 */
624 cmd_function_t *Cmd_FindCommand( const char *cmd_name )
625 {
626 cmd_function_t *cmd;
627 for( cmd = cmd_functions; cmd; cmd = cmd->next )
628 if( !Q_stricmp( cmd_name, cmd->name ) )
629 return cmd;
630 return NULL;
631 }
632
633 /*
634 ============
635 Cmd_AddCommand
636 ============
637 */
638 void Cmd_AddCommand( const char *cmd_name, xcommand_t function ) {
639 cmd_function_t *cmd;
640
641 // fail if the command already exists
642 if( Cmd_FindCommand( cmd_name ) )
643 {
644 // allow completion-only commands to be silently doubled
645 if( function != NULL )
646 Com_Printf( "Cmd_AddCommand: %s already defined\n", cmd_name );
647 return;
648 }
649
650 // use a small malloc to avoid zone fragmentation
651 cmd = S_Malloc (sizeof(cmd_function_t));
652 cmd->name = CopyString( cmd_name );
653 cmd->function = function;
654 cmd->complete = NULL;
655 cmd->next = cmd_functions;
656 cmd_functions = cmd;
657 }
658
659 /*
660 ============
661 Cmd_SetCommandCompletionFunc
662 ============
663 */
664 void Cmd_SetCommandCompletionFunc( const char *command, completionFunc_t complete ) {
665 cmd_function_t *cmd;
666
667 for( cmd = cmd_functions; cmd; cmd = cmd->next ) {
668 if( !Q_stricmp( command, cmd->name ) ) {
669 cmd->complete = complete;
670 return;
671 }
672 }
673 }
674
675 /*
676 ============
677 Cmd_RemoveCommand
678 ============
679 */
680 void Cmd_RemoveCommand( const char *cmd_name ) {
681 cmd_function_t *cmd, **back;
682
683 back = &cmd_functions;
684 while( 1 ) {
685 cmd = *back;
686 if ( !cmd ) {
687 // command wasn't active
688 return;
689 }
690 if ( !strcmp( cmd_name, cmd->name ) ) {
691 *back = cmd->next;
692 Z_Free (cmd->name);
693 Z_Free (cmd);
694 return;
695 }
696 back = &cmd->next;
697 }
698 }
699
700 /*
701 ============
702 Cmd_RemoveCommandSafe
703
704 Only remove commands with no associated function
705 ============
706 */
707 void Cmd_RemoveCommandSafe( const char *cmd_name )
708 {
709 cmd_function_t *cmd = Cmd_FindCommand( cmd_name );
710
711 if( !cmd )
712 return;
713 if( cmd->function )
714 {
715 Com_Error( ERR_DROP, "Restricted source tried to remove "
716 "system command \"%s\"", cmd_name );
717 return;
718 }
719
720 Cmd_RemoveCommand( cmd_name );
721 }
722
723 /*
724 ============
725 Cmd_CommandCompletion
726 ============
727 */
728 void Cmd_CommandCompletion( void(*callback)(const char *s) ) {
729 cmd_function_t *cmd;
730
731 for (cmd=cmd_functions ; cmd ; cmd=cmd->next) {
732 callback( cmd->name );
733 }
734 }
735
736 /*
737 ============
738 Cmd_CompleteArgument
739 ============
740 */
741 void Cmd_CompleteArgument( const char *command, char *args, int argNum ) {
742 cmd_function_t *cmd;
743
744 for( cmd = cmd_functions; cmd; cmd = cmd->next ) {
745 if( !Q_stricmp( command, cmd->name ) ) {
746 if ( cmd->complete ) {
747 cmd->complete( args, argNum );
748 }
749 return;
750 }
751 }
752 }
753
754
755 /*
756 ============
757 Cmd_ExecuteString
758
759 A complete command line has been parsed, so try to execute it
760 ============
761 */
762 void Cmd_ExecuteString( const char *text ) {
763 cmd_function_t *cmd, **prev;
764
765 // execute the command line
766 Cmd_TokenizeString( text );
767 if ( !Cmd_Argc() ) {
768 return; // no tokens
769 }
770
771 // check registered command functions
772 for ( prev = &cmd_functions ; *prev ; prev = &cmd->next ) {
773 cmd = *prev;
774 if ( !Q_stricmp( cmd_argv[0],cmd->name ) ) {
775 // rearrange the links so that the command will be
776 // near the head of the list next time it is used
777 *prev = cmd->next;
778 cmd->next = cmd_functions;
779 cmd_functions = cmd;
780
781 // perform the action
782 if ( !cmd->function ) {
783 // let the cgame or game handle it
784 break;
785 } else {
786 cmd->function ();
787 }
788 return;
789 }
790 }
791
792 // check cvars
793 if ( Cvar_Command() ) {
794 return;
795 }
796
797 // check client game commands
798 if ( com_cl_running && com_cl_running->integer && CL_GameCommand() ) {
799 return;
800 }
801
802 // check server game commands
803 if ( com_sv_running && com_sv_running->integer && SV_GameCommand() ) {
804 return;
805 }
806
807 // check ui commands
808 if ( com_cl_running && com_cl_running->integer && UI_GameCommand() ) {
809 return;
810 }
811
812 // send it as a server command if we are connected
813 // this will usually result in a chat message
814 CL_ForwardCommandToServer ( text );
815 }
816
817 /*
818 ============
819 Cmd_List_f
820 ============
821 */
822 void Cmd_List_f (void)
823 {
824 cmd_function_t *cmd;
825 int i;
826 char *match;
827
828 if ( Cmd_Argc() > 1 ) {
829 match = Cmd_Argv( 1 );
830 } else {
831 match = NULL;
832 }
833
834 i = 0;
835 for (cmd=cmd_functions ; cmd ; cmd=cmd->next) {
836 if (match && !Com_Filter(match, cmd->name, qfalse)) continue;
837
838 Com_Printf ("%s\n", cmd->name);
839 i++;
840 }
841 Com_Printf ("%i commands\n", i);
842 }
843
844 /*
845 ==================
846 Cmd_CompleteCfgName
847 ==================
848 */
849 void Cmd_CompleteCfgName( char *args, int argNum ) {
850 if( argNum == 2 ) {
851 Field_CompleteFilename( "", "cfg", NULL, qfalse, qtrue );
852 }
853 }
854
855 /*
856 ============
857 Cmd_Init
858 ============
859 */
860 void Cmd_Init (void) {
861 Cmd_AddCommand ("cmdlist",Cmd_List_f);
862 Cmd_AddCommand ("exec",Cmd_Exec_f);
863 Cmd_AddCommand ("execq",Cmd_Exec_f);
864 Cmd_SetCommandCompletionFunc( "exec", Cmd_CompleteCfgName );
865 Cmd_SetCommandCompletionFunc( "execq", Cmd_CompleteCfgName );
866 Cmd_AddCommand ("vstr",Cmd_Vstr_f);
867 Cmd_SetCommandCompletionFunc( "vstr", Cvar_CompleteCvarName );
868 Cmd_AddCommand ("echo",Cmd_Echo_f);
869 Cmd_AddCommand ("wait", Cmd_Wait_f);
870 }
871