Add: Towns can build tunnels (#8473)
[openttd-github.git] / src / console.cpp
blob3c782357d2749d1992c35dd5280b81afa6a67eec
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file console.cpp Handling of the in-game console. */
10 #include "stdafx.h"
11 #include "console_internal.h"
12 #include "network/network.h"
13 #include "network/network_func.h"
14 #include "network/network_admin.h"
15 #include "debug.h"
16 #include "console_func.h"
17 #include "settings_type.h"
19 #include <stdarg.h>
21 #include "safeguards.h"
23 static const uint ICON_TOKEN_COUNT = 20; ///< Maximum number of tokens in one command
24 static const uint ICON_MAX_RECURSE = 10; ///< Maximum number of recursion
26 /* console parser */
27 IConsoleCmd *_iconsole_cmds; ///< list of registered commands
28 IConsoleAlias *_iconsole_aliases; ///< list of registered aliases
30 FILE *_iconsole_output_file;
32 void IConsoleInit()
34 _iconsole_output_file = nullptr;
35 _redirect_console_to_client = INVALID_CLIENT_ID;
36 _redirect_console_to_admin = INVALID_ADMIN_ID;
38 IConsoleGUIInit();
40 IConsoleStdLibRegister();
43 static void IConsoleWriteToLogFile(const char *string)
45 if (_iconsole_output_file != nullptr) {
46 /* if there is an console output file ... also print it there */
47 const char *header = GetLogPrefix();
48 if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) ||
49 fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
50 fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
51 fclose(_iconsole_output_file);
52 _iconsole_output_file = nullptr;
53 IConsolePrintF(CC_DEFAULT, "cannot write to log file");
58 bool CloseConsoleLogIfActive()
60 if (_iconsole_output_file != nullptr) {
61 IConsolePrintF(CC_DEFAULT, "file output complete");
62 fclose(_iconsole_output_file);
63 _iconsole_output_file = nullptr;
64 return true;
67 return false;
70 void IConsoleFree()
72 IConsoleGUIFree();
73 CloseConsoleLogIfActive();
76 /**
77 * Handle the printing of text entered into the console or redirected there
78 * by any other means. Text can be redirected to other clients in a network game
79 * as well as to a logfile. If the network server is a dedicated server, all activities
80 * are also logged. All lines to print are added to a temporary buffer which can be
81 * used as a history to print them onscreen
82 * @param colour_code the colour of the command. Red in case of errors, etc.
83 * @param string the message entered or output on the console (notice, error, etc.)
85 void IConsolePrint(TextColour colour_code, const char *string)
87 assert(IsValidConsoleColour(colour_code));
89 char *str;
90 if (_redirect_console_to_client != INVALID_CLIENT_ID) {
91 /* Redirect the string to the client */
92 NetworkServerSendRcon(_redirect_console_to_client, colour_code, string);
93 return;
96 if (_redirect_console_to_admin != INVALID_ADMIN_ID) {
97 NetworkServerSendAdminRcon(_redirect_console_to_admin, colour_code, string);
98 return;
101 /* Create a copy of the string, strip if of colours and invalid
102 * characters and (when applicable) assign it to the console buffer */
103 str = stredup(string);
104 str_strip_colours(str);
105 str_validate(str, str + strlen(str));
107 if (_network_dedicated) {
108 NetworkAdminConsole("console", str);
109 fprintf(stdout, "%s%s\n", GetLogPrefix(), str);
110 fflush(stdout);
111 IConsoleWriteToLogFile(str);
112 free(str); // free duplicated string since it's not used anymore
113 return;
116 IConsoleWriteToLogFile(str);
117 IConsoleGUIPrint(colour_code, str);
121 * Handle the printing of text entered into the console or redirected there
122 * by any other means. Uses printf() style format, for more information look
123 * at IConsolePrint()
125 void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...)
127 assert(IsValidConsoleColour(colour_code));
129 va_list va;
130 char buf[ICON_MAX_STREAMSIZE];
132 va_start(va, format);
133 vseprintf(buf, lastof(buf), format, va);
134 va_end(va);
136 IConsolePrint(colour_code, buf);
140 * It is possible to print debugging information to the console,
141 * which is achieved by using this function. Can only be used by
142 * debug() in debug.cpp. You need at least a level 2 (developer) for debugging
143 * messages to show up
144 * @param dbg debugging category
145 * @param string debugging message
147 void IConsoleDebug(const char *dbg, const char *string)
149 if (_settings_client.gui.developer <= 1) return;
150 IConsolePrintF(CC_DEBUG, "dbg: [%s] %s", dbg, string);
154 * It is possible to print warnings to the console. These are mostly
155 * errors or mishaps, but non-fatal. You need at least a level 1 (developer) for
156 * debugging messages to show up
158 void IConsoleWarning(const char *string)
160 if (_settings_client.gui.developer == 0) return;
161 IConsolePrintF(CC_WARNING, "WARNING: %s", string);
165 * It is possible to print error information to the console. This can include
166 * game errors, or errors in general you would want the user to notice
168 void IConsoleError(const char *string)
170 IConsolePrintF(CC_ERROR, "ERROR: %s", string);
174 * Change a string into its number representation. Supports
175 * decimal and hexadecimal numbers as well as 'on'/'off' 'true'/'false'
176 * @param *value the variable a successful conversion will be put in
177 * @param *arg the string to be converted
178 * @return Return true on success or false on failure
180 bool GetArgumentInteger(uint32 *value, const char *arg)
182 char *endptr;
184 if (strcmp(arg, "on") == 0 || strcmp(arg, "true") == 0) {
185 *value = 1;
186 return true;
188 if (strcmp(arg, "off") == 0 || strcmp(arg, "false") == 0) {
189 *value = 0;
190 return true;
193 *value = strtoul(arg, &endptr, 0);
194 return arg != endptr;
198 * Add an item to an alphabetically sorted list.
199 * @param base first item of the list
200 * @param item_new the item to add
202 template<class T>
203 void IConsoleAddSorted(T **base, T *item_new)
205 if (*base == nullptr) {
206 *base = item_new;
207 return;
210 T *item_before = nullptr;
211 T *item = *base;
212 /* The list is alphabetically sorted, insert the new item at the correct location */
213 while (item != nullptr) {
214 if (strcmp(item->name, item_new->name) > 0) break; // insert here
216 item_before = item;
217 item = item->next;
220 if (item_before == nullptr) {
221 *base = item_new;
222 } else {
223 item_before->next = item_new;
226 item_new->next = item;
230 * Remove underscores from a string; the string will be modified!
231 * @param[in,out] name String to remove the underscores from.
232 * @return \a name, with its contents modified.
234 char *RemoveUnderscores(char *name)
236 char *q = name;
237 for (const char *p = name; *p != '\0'; p++) {
238 if (*p != '_') *q++ = *p;
240 *q = '\0';
241 return name;
245 * Register a new command to be used in the console
246 * @param name name of the command that will be used
247 * @param proc function that will be called upon execution of command
249 void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook)
251 IConsoleCmd *item_new = MallocT<IConsoleCmd>(1);
252 item_new->name = RemoveUnderscores(stredup(name));
253 item_new->next = nullptr;
254 item_new->proc = proc;
255 item_new->hook = hook;
257 IConsoleAddSorted(&_iconsole_cmds, item_new);
261 * Find the command pointed to by its string
262 * @param name command to be found
263 * @return return Cmdstruct of the found command, or nullptr on failure
265 IConsoleCmd *IConsoleCmdGet(const char *name)
267 IConsoleCmd *item;
269 for (item = _iconsole_cmds; item != nullptr; item = item->next) {
270 if (strcmp(item->name, name) == 0) return item;
272 return nullptr;
276 * Register a an alias for an already existing command in the console
277 * @param name name of the alias that will be used
278 * @param cmd name of the command that 'name' will be alias of
280 void IConsoleAliasRegister(const char *name, const char *cmd)
282 if (IConsoleAliasGet(name) != nullptr) {
283 IConsoleError("an alias with this name already exists; insertion aborted");
284 return;
287 char *new_alias = RemoveUnderscores(stredup(name));
288 char *cmd_aliased = stredup(cmd);
289 IConsoleAlias *item_new = MallocT<IConsoleAlias>(1);
291 item_new->next = nullptr;
292 item_new->cmdline = cmd_aliased;
293 item_new->name = new_alias;
295 IConsoleAddSorted(&_iconsole_aliases, item_new);
299 * Find the alias pointed to by its string
300 * @param name alias to be found
301 * @return return Aliasstruct of the found alias, or nullptr on failure
303 IConsoleAlias *IConsoleAliasGet(const char *name)
305 IConsoleAlias *item;
307 for (item = _iconsole_aliases; item != nullptr; item = item->next) {
308 if (strcmp(item->name, name) == 0) return item;
311 return nullptr;
314 * An alias is just another name for a command, or for more commands
315 * Execute it as well.
316 * @param *alias is the alias of the command
317 * @param tokencount the number of parameters passed
318 * @param *tokens are the parameters given to the original command (0 is the first param)
320 static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT], const uint recurse_count)
322 char alias_buffer[ICON_MAX_STREAMSIZE] = { '\0' };
323 char *alias_stream = alias_buffer;
325 DEBUG(console, 6, "Requested command is an alias; parsing...");
327 if (recurse_count > ICON_MAX_RECURSE) {
328 IConsoleError("Too many alias expansions, recursion limit reached. Aborting");
329 return;
332 for (const char *cmdptr = alias->cmdline; *cmdptr != '\0'; cmdptr++) {
333 switch (*cmdptr) {
334 case '\'': // ' will double for ""
335 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
336 break;
338 case ';': // Cmd separator; execute previous and start new command
339 IConsoleCmdExec(alias_buffer, recurse_count);
341 alias_stream = alias_buffer;
342 *alias_stream = '\0'; // Make sure the new command is terminated.
344 cmdptr++;
345 break;
347 case '%': // Some or all parameters
348 cmdptr++;
349 switch (*cmdptr) {
350 case '+': { // All parameters separated: "[param 1]" "[param 2]"
351 for (uint i = 0; i != tokencount; i++) {
352 if (i != 0) alias_stream = strecpy(alias_stream, " ", lastof(alias_buffer));
353 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
354 alias_stream = strecpy(alias_stream, tokens[i], lastof(alias_buffer));
355 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
357 break;
360 case '!': { // Merge the parameters to one: "[param 1] [param 2] [param 3...]"
361 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
362 for (uint i = 0; i != tokencount; i++) {
363 if (i != 0) alias_stream = strecpy(alias_stream, " ", lastof(alias_buffer));
364 alias_stream = strecpy(alias_stream, tokens[i], lastof(alias_buffer));
366 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
367 break;
370 default: { // One specific parameter: %A = [param 1] %B = [param 2] ...
371 int param = *cmdptr - 'A';
373 if (param < 0 || param >= tokencount) {
374 IConsoleError("too many or wrong amount of parameters passed to alias, aborting");
375 IConsolePrintF(CC_WARNING, "Usage of alias '%s': %s", alias->name, alias->cmdline);
376 return;
379 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
380 alias_stream = strecpy(alias_stream, tokens[param], lastof(alias_buffer));
381 alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
382 break;
385 break;
387 default:
388 *alias_stream++ = *cmdptr;
389 *alias_stream = '\0';
390 break;
393 if (alias_stream >= lastof(alias_buffer) - 1) {
394 IConsoleError("Requested alias execution would overflow execution buffer");
395 return;
399 IConsoleCmdExec(alias_buffer, recurse_count);
403 * Execute a given command passed to us. First chop it up into
404 * individual tokens (separated by spaces), then execute it if possible
405 * @param cmdstr string to be parsed and executed
407 void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
409 const char *cmdptr;
410 char *tokens[ICON_TOKEN_COUNT], tokenstream[ICON_MAX_STREAMSIZE];
411 uint t_index, tstream_i;
413 bool longtoken = false;
414 bool foundtoken = false;
416 if (cmdstr[0] == '#') return; // comments
418 for (cmdptr = cmdstr; *cmdptr != '\0'; cmdptr++) {
419 if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
420 IConsoleError("command contains malformed characters, aborting");
421 IConsolePrintF(CC_ERROR, "ERROR: command was: '%s'", cmdstr);
422 return;
426 DEBUG(console, 4, "Executing cmdline: '%s'", cmdstr);
428 memset(&tokens, 0, sizeof(tokens));
429 memset(&tokenstream, 0, sizeof(tokenstream));
431 /* 1. Split up commandline into tokens, separated by spaces, commands
432 * enclosed in "" are taken as one token. We can only go as far as the amount
433 * of characters in our stream or the max amount of tokens we can handle */
434 for (cmdptr = cmdstr, t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
435 if (tstream_i >= lengthof(tokenstream)) {
436 IConsoleError("command line too long");
437 return;
440 switch (*cmdptr) {
441 case ' ': // Token separator
442 if (!foundtoken) break;
444 if (longtoken) {
445 tokenstream[tstream_i] = *cmdptr;
446 } else {
447 tokenstream[tstream_i] = '\0';
448 foundtoken = false;
451 tstream_i++;
452 break;
453 case '"': // Tokens enclosed in "" are one token
454 longtoken = !longtoken;
455 if (!foundtoken) {
456 if (t_index >= lengthof(tokens)) {
457 IConsoleError("command line too long");
458 return;
460 tokens[t_index++] = &tokenstream[tstream_i];
461 foundtoken = true;
463 break;
464 case '\\': // Escape character for ""
465 if (cmdptr[1] == '"' && tstream_i + 1 < lengthof(tokenstream)) {
466 tokenstream[tstream_i++] = *++cmdptr;
467 break;
469 FALLTHROUGH;
470 default: // Normal character
471 tokenstream[tstream_i++] = *cmdptr;
473 if (!foundtoken) {
474 if (t_index >= lengthof(tokens)) {
475 IConsoleError("command line too long");
476 return;
478 tokens[t_index++] = &tokenstream[tstream_i - 1];
479 foundtoken = true;
481 break;
485 for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) {
486 DEBUG(console, 8, "Token %d is: '%s'", i, tokens[i]);
489 if (StrEmpty(tokens[0])) return; // don't execute empty commands
490 /* 2. Determine type of command (cmd or alias) and execute
491 * First try commands, then aliases. Execute
492 * the found action taking into account its hooking code
494 RemoveUnderscores(tokens[0]);
495 IConsoleCmd *cmd = IConsoleCmdGet(tokens[0]);
496 if (cmd != nullptr) {
497 ConsoleHookResult chr = (cmd->hook == nullptr ? CHR_ALLOW : cmd->hook(true));
498 switch (chr) {
499 case CHR_ALLOW:
500 if (!cmd->proc(t_index, tokens)) { // index started with 0
501 cmd->proc(0, nullptr); // if command failed, give help
503 return;
505 case CHR_DISALLOW: return;
506 case CHR_HIDE: break;
510 t_index--;
511 IConsoleAlias *alias = IConsoleAliasGet(tokens[0]);
512 if (alias != nullptr) {
513 IConsoleAliasExec(alias, t_index, &tokens[1], recurse_count + 1);
514 return;
517 IConsoleError("command not found");