Codechange: Use null pointer literal instead of the NULL macro
[openttd-github.git] / src / console.cpp
blobeedf604bab38deaada5174ac0ce680bc9e601fe7
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file console.cpp Handling of the in-game console. */
12 #include "stdafx.h"
13 #include "console_internal.h"
14 #include "network/network.h"
15 #include "network/network_func.h"
16 #include "network/network_admin.h"
17 #include "debug.h"
18 #include "console_func.h"
19 #include "settings_type.h"
21 #include <stdarg.h>
23 #include "safeguards.h"
25 static const uint ICON_TOKEN_COUNT = 20; ///< Maximum number of tokens in one command
27 /* console parser */
28 IConsoleCmd *_iconsole_cmds; ///< list of registered commands
29 IConsoleAlias *_iconsole_aliases; ///< list of registered aliases
31 FILE *_iconsole_output_file;
33 void IConsoleInit()
35 _iconsole_output_file = nullptr;
36 _redirect_console_to_client = INVALID_CLIENT_ID;
37 _redirect_console_to_admin = INVALID_ADMIN_ID;
39 IConsoleGUIInit();
41 IConsoleStdLibRegister();
44 static void IConsoleWriteToLogFile(const char *string)
46 if (_iconsole_output_file != nullptr) {
47 /* if there is an console output file ... also print it there */
48 const char *header = GetLogPrefix();
49 if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) ||
50 fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
51 fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
52 fclose(_iconsole_output_file);
53 _iconsole_output_file = nullptr;
54 IConsolePrintF(CC_DEFAULT, "cannot write to log file");
59 bool CloseConsoleLogIfActive()
61 if (_iconsole_output_file != nullptr) {
62 IConsolePrintF(CC_DEFAULT, "file output complete");
63 fclose(_iconsole_output_file);
64 _iconsole_output_file = nullptr;
65 return true;
68 return false;
71 void IConsoleFree()
73 IConsoleGUIFree();
74 CloseConsoleLogIfActive();
77 /**
78 * Handle the printing of text entered into the console or redirected there
79 * by any other means. Text can be redirected to other clients in a network game
80 * as well as to a logfile. If the network server is a dedicated server, all activities
81 * are also logged. All lines to print are added to a temporary buffer which can be
82 * used as a history to print them onscreen
83 * @param colour_code the colour of the command. Red in case of errors, etc.
84 * @param string the message entered or output on the console (notice, error, etc.)
86 void IConsolePrint(TextColour colour_code, const char *string)
88 assert(IsValidConsoleColour(colour_code));
90 char *str;
91 if (_redirect_console_to_client != INVALID_CLIENT_ID) {
92 /* Redirect the string to the client */
93 NetworkServerSendRcon(_redirect_console_to_client, colour_code, string);
94 return;
97 if (_redirect_console_to_admin != INVALID_ADMIN_ID) {
98 NetworkServerSendAdminRcon(_redirect_console_to_admin, colour_code, string);
99 return;
102 /* Create a copy of the string, strip if of colours and invalid
103 * characters and (when applicable) assign it to the console buffer */
104 str = stredup(string);
105 str_strip_colours(str);
106 str_validate(str, str + strlen(str));
108 if (_network_dedicated) {
109 NetworkAdminConsole("console", str);
110 fprintf(stdout, "%s%s\n", GetLogPrefix(), str);
111 fflush(stdout);
112 IConsoleWriteToLogFile(str);
113 free(str); // free duplicated string since it's not used anymore
114 return;
117 IConsoleWriteToLogFile(str);
118 IConsoleGUIPrint(colour_code, str);
122 * Handle the printing of text entered into the console or redirected there
123 * by any other means. Uses printf() style format, for more information look
124 * at IConsolePrint()
126 void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...)
128 assert(IsValidConsoleColour(colour_code));
130 va_list va;
131 char buf[ICON_MAX_STREAMSIZE];
133 va_start(va, format);
134 vseprintf(buf, lastof(buf), format, va);
135 va_end(va);
137 IConsolePrint(colour_code, buf);
141 * It is possible to print debugging information to the console,
142 * which is achieved by using this function. Can only be used by
143 * debug() in debug.cpp. You need at least a level 2 (developer) for debugging
144 * messages to show up
145 * @param dbg debugging category
146 * @param string debugging message
148 void IConsoleDebug(const char *dbg, const char *string)
150 if (_settings_client.gui.developer <= 1) return;
151 IConsolePrintF(CC_DEBUG, "dbg: [%s] %s", dbg, string);
155 * It is possible to print warnings to the console. These are mostly
156 * errors or mishaps, but non-fatal. You need at least a level 1 (developer) for
157 * debugging messages to show up
159 void IConsoleWarning(const char *string)
161 if (_settings_client.gui.developer == 0) return;
162 IConsolePrintF(CC_WARNING, "WARNING: %s", string);
166 * It is possible to print error information to the console. This can include
167 * game errors, or errors in general you would want the user to notice
169 void IConsoleError(const char *string)
171 IConsolePrintF(CC_ERROR, "ERROR: %s", string);
175 * Change a string into its number representation. Supports
176 * decimal and hexadecimal numbers as well as 'on'/'off' 'true'/'false'
177 * @param *value the variable a successful conversion will be put in
178 * @param *arg the string to be converted
179 * @return Return true on success or false on failure
181 bool GetArgumentInteger(uint32 *value, const char *arg)
183 char *endptr;
185 if (strcmp(arg, "on") == 0 || strcmp(arg, "true") == 0) {
186 *value = 1;
187 return true;
189 if (strcmp(arg, "off") == 0 || strcmp(arg, "false") == 0) {
190 *value = 0;
191 return true;
194 *value = strtoul(arg, &endptr, 0);
195 return arg != endptr;
199 * Add an item to an alphabetically sorted list.
200 * @param base first item of the list
201 * @param item_new the item to add
203 template<class T>
204 void IConsoleAddSorted(T **base, T *item_new)
206 if (*base == nullptr) {
207 *base = item_new;
208 return;
211 T *item_before = nullptr;
212 T *item = *base;
213 /* The list is alphabetically sorted, insert the new item at the correct location */
214 while (item != nullptr) {
215 if (strcmp(item->name, item_new->name) > 0) break; // insert here
217 item_before = item;
218 item = item->next;
221 if (item_before == nullptr) {
222 *base = item_new;
223 } else {
224 item_before->next = item_new;
227 item_new->next = item;
231 * Remove underscores from a string; the string will be modified!
232 * @param[in,out] name String to remove the underscores from.
233 * @return \a name, with its contents modified.
235 char *RemoveUnderscores(char *name)
237 char *q = name;
238 for (const char *p = name; *p != '\0'; p++) {
239 if (*p != '_') *q++ = *p;
241 *q = '\0';
242 return name;
246 * Register a new command to be used in the console
247 * @param name name of the command that will be used
248 * @param proc function that will be called upon execution of command
250 void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook)
252 IConsoleCmd *item_new = MallocT<IConsoleCmd>(1);
253 item_new->name = RemoveUnderscores(stredup(name));
254 item_new->next = nullptr;
255 item_new->proc = proc;
256 item_new->hook = hook;
258 IConsoleAddSorted(&_iconsole_cmds, item_new);
262 * Find the command pointed to by its string
263 * @param name command to be found
264 * @return return Cmdstruct of the found command, or nullptr on failure
266 IConsoleCmd *IConsoleCmdGet(const char *name)
268 IConsoleCmd *item;
270 for (item = _iconsole_cmds; item != nullptr; item = item->next) {
271 if (strcmp(item->name, name) == 0) return item;
273 return nullptr;
277 * Register a an alias for an already existing command in the console
278 * @param name name of the alias that will be used
279 * @param cmd name of the command that 'name' will be alias of
281 void IConsoleAliasRegister(const char *name, const char *cmd)
283 if (IConsoleAliasGet(name) != nullptr) {
284 IConsoleError("an alias with this name already exists; insertion aborted");
285 return;
288 char *new_alias = RemoveUnderscores(stredup(name));
289 char *cmd_aliased = stredup(cmd);
290 IConsoleAlias *item_new = MallocT<IConsoleAlias>(1);
292 item_new->next = nullptr;
293 item_new->cmdline = cmd_aliased;
294 item_new->name = new_alias;
296 IConsoleAddSorted(&_iconsole_aliases, item_new);
300 * Find the alias pointed to by its string
301 * @param name alias to be found
302 * @return return Aliasstruct of the found alias, or nullptr on failure
304 IConsoleAlias *IConsoleAliasGet(const char *name)
306 IConsoleAlias *item;
308 for (item = _iconsole_aliases; item != nullptr; item = item->next) {
309 if (strcmp(item->name, name) == 0) return item;
312 return nullptr;
315 * An alias is just another name for a command, or for more commands
316 * Execute it as well.
317 * @param *alias is the alias of the command
318 * @param tokencount the number of parameters passed
319 * @param *tokens are the parameters given to the original command (0 is the first param)
321 static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT])
323 char alias_buffer[ICON_MAX_STREAMSIZE] = { '\0' };
324 char *alias_stream = alias_buffer;
326 DEBUG(console, 6, "Requested command is an alias; parsing...");
328 for (const char *cmdptr = alias->cmdline; *cmdptr != '\0'; cmdptr++) {
329 switch (*cmdptr) {
330 case '\'': // ' will double for ""
331 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
332 break;
334 case ';': // Cmd separator; execute previous and start new command
335 IConsoleCmdExec(alias_buffer);
337 alias_stream = alias_buffer;
338 *alias_stream = '\0'; // Make sure the new command is terminated.
340 cmdptr++;
341 break;
343 case '%': // Some or all parameters
344 cmdptr++;
345 switch (*cmdptr) {
346 case '+': { // All parameters separated: "[param 1]" "[param 2]"
347 for (uint i = 0; i != tokencount; i++) {
348 if (i != 0) alias_stream = strecpy(alias_stream, " ", lastof(alias_buffer));
349 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
350 alias_stream = strecpy(alias_stream, tokens[i], lastof(alias_buffer));
351 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
353 break;
356 case '!': { // Merge the parameters to one: "[param 1] [param 2] [param 3...]"
357 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
358 for (uint i = 0; i != tokencount; i++) {
359 if (i != 0) alias_stream = strecpy(alias_stream, " ", lastof(alias_buffer));
360 alias_stream = strecpy(alias_stream, tokens[i], lastof(alias_buffer));
362 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
363 break;
366 default: { // One specific parameter: %A = [param 1] %B = [param 2] ...
367 int param = *cmdptr - 'A';
369 if (param < 0 || param >= tokencount) {
370 IConsoleError("too many or wrong amount of parameters passed to alias, aborting");
371 IConsolePrintF(CC_WARNING, "Usage of alias '%s': %s", alias->name, alias->cmdline);
372 return;
375 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
376 alias_stream = strecpy(alias_stream, tokens[param], lastof(alias_buffer));
377 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
378 break;
381 break;
383 default:
384 *alias_stream++ = *cmdptr;
385 *alias_stream = '\0';
386 break;
389 if (alias_stream >= lastof(alias_buffer) - 1) {
390 IConsoleError("Requested alias execution would overflow execution buffer");
391 return;
395 IConsoleCmdExec(alias_buffer);
399 * Execute a given command passed to us. First chop it up into
400 * individual tokens (separated by spaces), then execute it if possible
401 * @param cmdstr string to be parsed and executed
403 void IConsoleCmdExec(const char *cmdstr)
405 const char *cmdptr;
406 char *tokens[ICON_TOKEN_COUNT], tokenstream[ICON_MAX_STREAMSIZE];
407 uint t_index, tstream_i;
409 bool longtoken = false;
410 bool foundtoken = false;
412 if (cmdstr[0] == '#') return; // comments
414 for (cmdptr = cmdstr; *cmdptr != '\0'; cmdptr++) {
415 if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
416 IConsoleError("command contains malformed characters, aborting");
417 IConsolePrintF(CC_ERROR, "ERROR: command was: '%s'", cmdstr);
418 return;
422 DEBUG(console, 4, "Executing cmdline: '%s'", cmdstr);
424 memset(&tokens, 0, sizeof(tokens));
425 memset(&tokenstream, 0, sizeof(tokenstream));
427 /* 1. Split up commandline into tokens, separated by spaces, commands
428 * enclosed in "" are taken as one token. We can only go as far as the amount
429 * of characters in our stream or the max amount of tokens we can handle */
430 for (cmdptr = cmdstr, t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
431 if (tstream_i >= lengthof(tokenstream)) {
432 IConsoleError("command line too long");
433 return;
436 switch (*cmdptr) {
437 case ' ': // Token separator
438 if (!foundtoken) break;
440 if (longtoken) {
441 tokenstream[tstream_i] = *cmdptr;
442 } else {
443 tokenstream[tstream_i] = '\0';
444 foundtoken = false;
447 tstream_i++;
448 break;
449 case '"': // Tokens enclosed in "" are one token
450 longtoken = !longtoken;
451 if (!foundtoken) {
452 if (t_index >= lengthof(tokens)) {
453 IConsoleError("command line too long");
454 return;
456 tokens[t_index++] = &tokenstream[tstream_i];
457 foundtoken = true;
459 break;
460 case '\\': // Escape character for ""
461 if (cmdptr[1] == '"' && tstream_i + 1 < lengthof(tokenstream)) {
462 tokenstream[tstream_i++] = *++cmdptr;
463 break;
465 FALLTHROUGH;
466 default: // Normal character
467 tokenstream[tstream_i++] = *cmdptr;
469 if (!foundtoken) {
470 if (t_index >= lengthof(tokens)) {
471 IConsoleError("command line too long");
472 return;
474 tokens[t_index++] = &tokenstream[tstream_i - 1];
475 foundtoken = true;
477 break;
481 for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) {
482 DEBUG(console, 8, "Token %d is: '%s'", i, tokens[i]);
485 if (StrEmpty(tokens[0])) return; // don't execute empty commands
486 /* 2. Determine type of command (cmd or alias) and execute
487 * First try commands, then aliases. Execute
488 * the found action taking into account its hooking code
490 RemoveUnderscores(tokens[0]);
491 IConsoleCmd *cmd = IConsoleCmdGet(tokens[0]);
492 if (cmd != nullptr) {
493 ConsoleHookResult chr = (cmd->hook == nullptr ? CHR_ALLOW : cmd->hook(true));
494 switch (chr) {
495 case CHR_ALLOW:
496 if (!cmd->proc(t_index, tokens)) { // index started with 0
497 cmd->proc(0, nullptr); // if command failed, give help
499 return;
501 case CHR_DISALLOW: return;
502 case CHR_HIDE: break;
506 t_index--;
507 IConsoleAlias *alias = IConsoleAliasGet(tokens[0]);
508 if (alias != nullptr) {
509 IConsoleAliasExec(alias, t_index, &tokens[1]);
510 return;
513 IConsoleError("command not found");