OpenTTD Source  14.0-beta3
console.cpp
Go to the documentation of this file.
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  */
7 
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"
18 
19 #include "safeguards.h"
20 
21 static const uint ICON_TOKEN_COUNT = 20;
22 static const uint ICON_MAX_RECURSE = 10;
23 
24 /* console parser */
25 /* static */ IConsole::CommandList &IConsole::Commands()
26 {
27  static IConsole::CommandList cmds;
28  return cmds;
29 }
30 
31 /* static */ IConsole::AliasList &IConsole::Aliases()
32 {
33  static IConsole::AliasList aliases;
34  return aliases;
35 }
36 
37 FILE *_iconsole_output_file;
38 
39 void IConsoleInit()
40 {
41  _iconsole_output_file = nullptr;
44 
45  IConsoleGUIInit();
46 
47  IConsoleStdLibRegister();
48 }
49 
50 static void IConsoleWriteToLogFile(const std::string &string)
51 {
52  if (_iconsole_output_file != nullptr) {
53  /* if there is an console output file ... also print it there */
54  try {
55  fmt::print(_iconsole_output_file, "{}{}\n", GetLogPrefix(), string);
56  } catch (const std::system_error &) {
57  fclose(_iconsole_output_file);
58  _iconsole_output_file = nullptr;
59  IConsolePrint(CC_ERROR, "Cannot write to console log file; closing the log file.");
60  }
61  }
62 }
63 
64 bool CloseConsoleLogIfActive()
65 {
66  if (_iconsole_output_file != nullptr) {
67  IConsolePrint(CC_INFO, "Console log file closed.");
68  fclose(_iconsole_output_file);
69  _iconsole_output_file = nullptr;
70  return true;
71  }
72 
73  return false;
74 }
75 
76 void IConsoleFree()
77 {
78  IConsoleGUIFree();
79  CloseConsoleLogIfActive();
80 }
81 
91 void IConsolePrint(TextColour colour_code, const std::string &string)
92 {
93  assert(IsValidConsoleColour(colour_code));
94 
96  /* Redirect the string to the client */
98  return;
99  }
100 
103  return;
104  }
105 
106  /* Create a copy of the string, strip it of colours and invalid
107  * characters and (when applicable) assign it to the console buffer */
108  std::string str = StrMakeValid(string, SVS_NONE);
109 
110  if (_network_dedicated) {
111  NetworkAdminConsole("console", str);
112  fmt::print("{}{}\n", GetLogPrefix(), str);
113  fflush(stdout);
114  IConsoleWriteToLogFile(str);
115  return;
116  }
117 
118  IConsoleWriteToLogFile(str);
119  IConsoleGUIPrint(colour_code, str);
120 }
121 
129 bool GetArgumentInteger(uint32_t *value, const char *arg)
130 {
131  char *endptr;
132 
133  if (strcmp(arg, "on") == 0 || strcmp(arg, "true") == 0) {
134  *value = 1;
135  return true;
136  }
137  if (strcmp(arg, "off") == 0 || strcmp(arg, "false") == 0) {
138  *value = 0;
139  return true;
140  }
141 
142  *value = std::strtoul(arg, &endptr, 0);
143  return arg != endptr;
144 }
145 
151 static std::string RemoveUnderscores(std::string name)
152 {
153  name.erase(std::remove(name.begin(), name.end(), '_'), name.end());
154  return name;
155 }
156 
162 /* static */ void IConsole::CmdRegister(const std::string &name, IConsoleCmdProc *proc, IConsoleHook *hook)
163 {
164  IConsole::Commands().try_emplace(RemoveUnderscores(name), name, proc, hook);
165 }
166 
172 /* static */ IConsoleCmd *IConsole::CmdGet(const std::string &name)
173 {
174  auto item = IConsole::Commands().find(RemoveUnderscores(name));
175  if (item != IConsole::Commands().end()) return &item->second;
176  return nullptr;
177 }
178 
184 /* static */ void IConsole::AliasRegister(const std::string &name, const std::string &cmd)
185 {
186  auto result = IConsole::Aliases().try_emplace(RemoveUnderscores(name), name, cmd);
187  if (!result.second) IConsolePrint(CC_ERROR, "An alias with the name '{}' already exists.", name);
188 }
189 
195 /* static */ IConsoleAlias *IConsole::AliasGet(const std::string &name)
196 {
197  auto item = IConsole::Aliases().find(RemoveUnderscores(name));
198  if (item != IConsole::Aliases().end()) return &item->second;
199  return nullptr;
200 }
201 
209 static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT], const uint recurse_count)
210 {
211  std::string alias_buffer;
212 
213  Debug(console, 6, "Requested command is an alias; parsing...");
214 
215  if (recurse_count > ICON_MAX_RECURSE) {
216  IConsolePrint(CC_ERROR, "Too many alias expansions, recursion limit reached.");
217  return;
218  }
219 
220  for (const char *cmdptr = alias->cmdline.c_str(); *cmdptr != '\0'; cmdptr++) {
221  switch (*cmdptr) {
222  case '\'': // ' will double for ""
223  alias_buffer += '\"';
224  break;
225 
226  case ';': // Cmd separator; execute previous and start new command
227  IConsoleCmdExec(alias_buffer, recurse_count);
228 
229  alias_buffer.clear();
230 
231  cmdptr++;
232  break;
233 
234  case '%': // Some or all parameters
235  cmdptr++;
236  switch (*cmdptr) {
237  case '+': { // All parameters separated: "[param 1]" "[param 2]"
238  for (uint i = 0; i != tokencount; i++) {
239  if (i != 0) alias_buffer += ' ';
240  alias_buffer += '\"';
241  alias_buffer += tokens[i];
242  alias_buffer += '\"';
243  }
244  break;
245  }
246 
247  case '!': { // Merge the parameters to one: "[param 1] [param 2] [param 3...]"
248  alias_buffer += '\"';
249  for (uint i = 0; i != tokencount; i++) {
250  if (i != 0) alias_buffer += " ";
251  alias_buffer += tokens[i];
252  }
253  alias_buffer += '\"';
254  break;
255  }
256 
257  default: { // One specific parameter: %A = [param 1] %B = [param 2] ...
258  int param = *cmdptr - 'A';
259 
260  if (param < 0 || param >= tokencount) {
261  IConsolePrint(CC_ERROR, "Too many or wrong amount of parameters passed to alias.");
262  IConsolePrint(CC_HELP, "Usage of alias '{}': '{}'.", alias->name, alias->cmdline);
263  return;
264  }
265 
266  alias_buffer += '\"';
267  alias_buffer += tokens[param];
268  alias_buffer += '\"';
269  break;
270  }
271  }
272  break;
273 
274  default:
275  alias_buffer += *cmdptr;
276  break;
277  }
278 
279  if (alias_buffer.size() >= ICON_MAX_STREAMSIZE - 1) {
280  IConsolePrint(CC_ERROR, "Requested alias execution would overflow execution buffer.");
281  return;
282  }
283  }
284 
285  IConsoleCmdExec(alias_buffer, recurse_count);
286 }
287 
293 void IConsoleCmdExec(const std::string &command_string, const uint recurse_count)
294 {
295  const char *cmdptr;
296  char *tokens[ICON_TOKEN_COUNT], tokenstream[ICON_MAX_STREAMSIZE];
297  uint t_index, tstream_i;
298 
299  bool longtoken = false;
300  bool foundtoken = false;
301 
302  if (command_string[0] == '#') return; // comments
303 
304  for (cmdptr = command_string.c_str(); *cmdptr != '\0'; cmdptr++) {
305  if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
306  IConsolePrint(CC_ERROR, "Command '{}' contains malformed characters.", command_string);
307  return;
308  }
309  }
310 
311  Debug(console, 4, "Executing cmdline: '{}'", command_string);
312 
313  memset(&tokens, 0, sizeof(tokens));
314  memset(&tokenstream, 0, sizeof(tokenstream));
315 
316  /* 1. Split up commandline into tokens, separated by spaces, commands
317  * enclosed in "" are taken as one token. We can only go as far as the amount
318  * of characters in our stream or the max amount of tokens we can handle */
319  for (cmdptr = command_string.c_str(), t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
320  if (tstream_i >= lengthof(tokenstream)) {
321  IConsolePrint(CC_ERROR, "Command line too long.");
322  return;
323  }
324 
325  switch (*cmdptr) {
326  case ' ': // Token separator
327  if (!foundtoken) break;
328 
329  if (longtoken) {
330  tokenstream[tstream_i] = *cmdptr;
331  } else {
332  tokenstream[tstream_i] = '\0';
333  foundtoken = false;
334  }
335 
336  tstream_i++;
337  break;
338  case '"': // Tokens enclosed in "" are one token
339  longtoken = !longtoken;
340  if (!foundtoken) {
341  if (t_index >= lengthof(tokens)) {
342  IConsolePrint(CC_ERROR, "Command line too long.");
343  return;
344  }
345  tokens[t_index++] = &tokenstream[tstream_i];
346  foundtoken = true;
347  }
348  break;
349  case '\\': // Escape character for ""
350  if (cmdptr[1] == '"' && tstream_i + 1 < lengthof(tokenstream)) {
351  tokenstream[tstream_i++] = *++cmdptr;
352  break;
353  }
354  [[fallthrough]];
355  default: // Normal character
356  tokenstream[tstream_i++] = *cmdptr;
357 
358  if (!foundtoken) {
359  if (t_index >= lengthof(tokens)) {
360  IConsolePrint(CC_ERROR, "Command line too long.");
361  return;
362  }
363  tokens[t_index++] = &tokenstream[tstream_i - 1];
364  foundtoken = true;
365  }
366  break;
367  }
368  }
369 
370  for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) {
371  Debug(console, 8, "Token {} is: '{}'", i, tokens[i]);
372  }
373 
374  if (StrEmpty(tokens[0])) return; // don't execute empty commands
375  /* 2. Determine type of command (cmd or alias) and execute
376  * First try commands, then aliases. Execute
377  * the found action taking into account its hooking code
378  */
379  IConsoleCmd *cmd = IConsole::CmdGet(tokens[0]);
380  if (cmd != nullptr) {
381  ConsoleHookResult chr = (cmd->hook == nullptr ? CHR_ALLOW : cmd->hook(true));
382  switch (chr) {
383  case CHR_ALLOW:
384  if (!cmd->proc(t_index, tokens)) { // index started with 0
385  cmd->proc(0, nullptr); // if command failed, give help
386  }
387  return;
388 
389  case CHR_DISALLOW: return;
390  case CHR_HIDE: break;
391  }
392  }
393 
394  t_index--;
395  IConsoleAlias *alias = IConsole::AliasGet(tokens[0]);
396  if (alias != nullptr) {
397  IConsoleAliasExec(alias, t_index, &tokens[1], recurse_count + 1);
398  return;
399  }
400 
401  IConsolePrint(CC_ERROR, "Command '{}' not found.", tokens[0]);
402 }
CC_INFO
static const TextColour CC_INFO
Colour for information lines.
Definition: console_type.h:27
IConsoleCmd::proc
IConsoleCmdProc * proc
process executed when command is typed
Definition: console_internal.h:39
StrMakeValid
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition: string.cpp:114
IConsole::AliasGet
static IConsoleAlias * AliasGet(const std::string &name)
Find the alias pointed to by its string.
Definition: console.cpp:195
GetArgumentInteger
bool GetArgumentInteger(uint32_t *value, const char *arg)
Change a string into its number representation.
Definition: console.cpp:129
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:253
_redirect_console_to_client
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition: network.cpp:66
StrEmpty
bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:56
IConsoleAlias::cmdline
std::string cmdline
command(s) that is/are being aliased
Definition: console_internal.h:59
INVALID_ADMIN_ID
static const AdminIndex INVALID_ADMIN_ID
An invalid admin marker.
Definition: network_type.h:64
_redirect_console_to_admin
AdminIndex _redirect_console_to_admin
Redirection of the (remote) console to the admin.
Definition: network_admin.cpp:32
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
IConsoleCmd::hook
IConsoleHook * hook
any special trigger action that needs executing
Definition: console_internal.h:40
NetworkAdminConsole
void NetworkAdminConsole(const std::string_view origin, const std::string_view string)
Send console to the admin network (if they did opt in for the respective update).
Definition: network_admin.cpp:935
ICON_TOKEN_COUNT
static const uint ICON_TOKEN_COUNT
Maximum number of tokens in one command.
Definition: console.cpp:21
IConsole::CmdRegister
static void CmdRegister(const std::string &name, IConsoleCmdProc *proc, IConsoleHook *hook=nullptr)
Register a new command to be used in the console.
Definition: console.cpp:162
ICON_MAX_STREAMSIZE
static const uint ICON_MAX_STREAMSIZE
maximum length of a totally expanded command
Definition: console_internal.h:16
CC_HELP
static const TextColour CC_HELP
Colour for help lines.
Definition: console_type.h:26
console_internal.h
IConsoleCmdExec
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:293
IConsoleCmd
Definition: console_internal.h:35
CHR_ALLOW
@ CHR_ALLOW
Allow command execution.
Definition: console_internal.h:20
safeguards.h
IsValidConsoleColour
bool IsValidConsoleColour(TextColour c)
Check whether the given TextColour is valid for console usage.
Definition: console_gui.cpp:488
IConsoleGUIPrint
void IConsoleGUIPrint(TextColour colour_code, const std::string &str)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console_gui.cpp:448
settings_type.h
ICON_MAX_RECURSE
static const uint ICON_MAX_RECURSE
Maximum number of recursion.
Definition: console.cpp:22
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:62
stdafx.h
CS_ALPHANUMERAL
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition: string_type.h:25
GetLogPrefix
std::string GetLogPrefix(bool force)
Get the prefix for logs.
Definition: debug.cpp:228
IConsoleAlias::name
std::string name
name of the alias
Definition: console_internal.h:58
IsValidChar
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
Definition: string.cpp:415
RemoveUnderscores
static std::string RemoveUnderscores(std::string name)
Creates a copy of a string with underscores removed from it.
Definition: console.cpp:151
IConsoleAliasExec
static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT], const uint recurse_count)
An alias is just another name for a command, or for more commands Execute it as well.
Definition: console.cpp:209
IConsole::AliasRegister
static void AliasRegister(const std::string &name, const std::string &cmd)
Register a an alias for an already existing command in the console.
Definition: console.cpp:184
NetworkServerSendRcon
void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string)
Send an rcon reply to the client.
Definition: network_server.cpp:2066
IConsoleAlias
–Aliases– Aliases are like shortcuts for complex functions, variable assignments, etc.
Definition: console_internal.h:55
INVALID_CLIENT_ID
@ INVALID_CLIENT_ID
Client is not part of anything.
Definition: network_type.h:50
CC_ERROR
static const TextColour CC_ERROR
Colour for error lines.
Definition: console_type.h:24
SVS_NONE
@ SVS_NONE
Allow nothing and replace nothing.
Definition: string_type.h:45
CHR_DISALLOW
@ CHR_DISALLOW
Disallow command execution.
Definition: console_internal.h:21
network.h
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:300
CHR_HIDE
@ CHR_HIDE
Hide the existence of the command.
Definition: console_internal.h:22
IConsoleCmdProc
bool IConsoleCmdProc(byte argc, char *argv[])
–Commands– Commands are commands, or functions.
Definition: console_internal.h:33
network_admin.h
console_func.h
network_func.h
ConsoleHookResult
ConsoleHookResult
Return values of console hooks (#IConsoleHook).
Definition: console_internal.h:19
IConsole::CmdGet
static IConsoleCmd * CmdGet(const std::string &name)
Find the command pointed to by its string.
Definition: console.cpp:172
debug.h
NetworkServerSendAdminRcon
void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const std::string_view string)
Pass the rcon reply to the admin.
Definition: network_admin.cpp:925
IConsolePrint
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console.cpp:91