OpenTTD
console.cpp
Go to the documentation of this file.
1 /* $Id: console.cpp 27893 2017-08-13 18:38:42Z frosch $ */
2 
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  */
9 
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"
20 
21 #include <stdarg.h>
22 
23 #include "safeguards.h"
24 
25 static const uint ICON_TOKEN_COUNT = 20;
26 
27 /* console parser */
30 
31 FILE *_iconsole_output_file;
32 
33 void IConsoleInit()
34 {
35  _iconsole_output_file = NULL;
36 #ifdef ENABLE_NETWORK /* Initialize network only variables */
39 #endif
40 
41  IConsoleGUIInit();
42 
43  IConsoleStdLibRegister();
44 }
45 
46 static void IConsoleWriteToLogFile(const char *string)
47 {
48  if (_iconsole_output_file != NULL) {
49  /* if there is an console output file ... also print it there */
50  const char *header = GetLogPrefix();
51  if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) ||
52  fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
53  fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
54  fclose(_iconsole_output_file);
55  _iconsole_output_file = NULL;
56  IConsolePrintF(CC_DEFAULT, "cannot write to log file");
57  }
58  }
59 }
60 
61 bool CloseConsoleLogIfActive()
62 {
63  if (_iconsole_output_file != NULL) {
64  IConsolePrintF(CC_DEFAULT, "file output complete");
65  fclose(_iconsole_output_file);
66  _iconsole_output_file = NULL;
67  return true;
68  }
69 
70  return false;
71 }
72 
73 void IConsoleFree()
74 {
75  IConsoleGUIFree();
76  CloseConsoleLogIfActive();
77 }
78 
88 void IConsolePrint(TextColour colour_code, const char *string)
89 {
90  assert(IsValidConsoleColour(colour_code));
91 
92  char *str;
93 #ifdef ENABLE_NETWORK
95  /* Redirect the string to the client */
97  return;
98  }
99 
102  return;
103  }
104 #endif
105 
106  /* Create a copy of the string, strip if of colours and invalid
107  * characters and (when applicable) assign it to the console buffer */
108  str = stredup(string);
109  str_strip_colours(str);
110  str_validate(str, str + strlen(str));
111 
112  if (_network_dedicated) {
113 #ifdef ENABLE_NETWORK
114  NetworkAdminConsole("console", str);
115 #endif /* ENABLE_NETWORK */
116  fprintf(stdout, "%s%s\n", GetLogPrefix(), str);
117  fflush(stdout);
118  IConsoleWriteToLogFile(str);
119  free(str); // free duplicated string since it's not used anymore
120  return;
121  }
122 
123  IConsoleWriteToLogFile(str);
124  IConsoleGUIPrint(colour_code, str);
125 }
126 
132 void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...)
133 {
134  assert(IsValidConsoleColour(colour_code));
135 
136  va_list va;
137  char buf[ICON_MAX_STREAMSIZE];
138 
139  va_start(va, format);
140  vseprintf(buf, lastof(buf), format, va);
141  va_end(va);
142 
143  IConsolePrint(colour_code, buf);
144 }
145 
154 void IConsoleDebug(const char *dbg, const char *string)
155 {
156  if (_settings_client.gui.developer <= 1) return;
157  IConsolePrintF(CC_DEBUG, "dbg: [%s] %s", dbg, string);
158 }
159 
165 void IConsoleWarning(const char *string)
166 {
167  if (_settings_client.gui.developer == 0) return;
168  IConsolePrintF(CC_WARNING, "WARNING: %s", string);
169 }
170 
175 void IConsoleError(const char *string)
176 {
177  IConsolePrintF(CC_ERROR, "ERROR: %s", string);
178 }
179 
187 bool GetArgumentInteger(uint32 *value, const char *arg)
188 {
189  char *endptr;
190 
191  if (strcmp(arg, "on") == 0 || strcmp(arg, "true") == 0) {
192  *value = 1;
193  return true;
194  }
195  if (strcmp(arg, "off") == 0 || strcmp(arg, "false") == 0) {
196  *value = 0;
197  return true;
198  }
199 
200  *value = strtoul(arg, &endptr, 0);
201  return arg != endptr;
202 }
203 
209 template<class T>
210 void IConsoleAddSorted(T **base, T *item_new)
211 {
212  if (*base == NULL) {
213  *base = item_new;
214  return;
215  }
216 
217  T *item_before = NULL;
218  T *item = *base;
219  /* The list is alphabetically sorted, insert the new item at the correct location */
220  while (item != NULL) {
221  if (strcmp(item->name, item_new->name) > 0) break; // insert here
222 
223  item_before = item;
224  item = item->next;
225  }
226 
227  if (item_before == NULL) {
228  *base = item_new;
229  } else {
230  item_before->next = item_new;
231  }
232 
233  item_new->next = item;
234 }
235 
242 {
243  char *q = name;
244  for (const char *p = name; *p != '\0'; p++) {
245  if (*p != '_') *q++ = *p;
246  }
247  *q = '\0';
248  return name;
249 }
250 
256 void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook)
257 {
258  IConsoleCmd *item_new = MallocT<IConsoleCmd>(1);
259  item_new->name = RemoveUnderscores(stredup(name));
260  item_new->next = NULL;
261  item_new->proc = proc;
262  item_new->hook = hook;
263 
264  IConsoleAddSorted(&_iconsole_cmds, item_new);
265 }
266 
273 {
274  IConsoleCmd *item;
275 
276  for (item = _iconsole_cmds; item != NULL; item = item->next) {
277  if (strcmp(item->name, name) == 0) return item;
278  }
279  return NULL;
280 }
281 
287 void IConsoleAliasRegister(const char *name, const char *cmd)
288 {
289  if (IConsoleAliasGet(name) != NULL) {
290  IConsoleError("an alias with this name already exists; insertion aborted");
291  return;
292  }
293 
294  char *new_alias = RemoveUnderscores(stredup(name));
295  char *cmd_aliased = stredup(cmd);
296  IConsoleAlias *item_new = MallocT<IConsoleAlias>(1);
297 
298  item_new->next = NULL;
299  item_new->cmdline = cmd_aliased;
300  item_new->name = new_alias;
301 
302  IConsoleAddSorted(&_iconsole_aliases, item_new);
303 }
304 
311 {
312  IConsoleAlias *item;
313 
314  for (item = _iconsole_aliases; item != NULL; item = item->next) {
315  if (strcmp(item->name, name) == 0) return item;
316  }
317 
318  return NULL;
319 }
327 static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT])
328 {
329  char alias_buffer[ICON_MAX_STREAMSIZE] = { '\0' };
330  char *alias_stream = alias_buffer;
331 
332  DEBUG(console, 6, "Requested command is an alias; parsing...");
333 
334  for (const char *cmdptr = alias->cmdline; *cmdptr != '\0'; cmdptr++) {
335  switch (*cmdptr) {
336  case '\'': // ' will double for ""
337  alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
338  break;
339 
340  case ';': // Cmd separator; execute previous and start new command
341  IConsoleCmdExec(alias_buffer);
342 
343  alias_stream = alias_buffer;
344  *alias_stream = '\0'; // Make sure the new command is terminated.
345 
346  cmdptr++;
347  break;
348 
349  case '%': // Some or all parameters
350  cmdptr++;
351  switch (*cmdptr) {
352  case '+': { // All parameters separated: "[param 1]" "[param 2]"
353  for (uint i = 0; i != tokencount; i++) {
354  if (i != 0) alias_stream = strecpy(alias_stream, " ", lastof(alias_buffer));
355  alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
356  alias_stream = strecpy(alias_stream, tokens[i], lastof(alias_buffer));
357  alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
358  }
359  break;
360  }
361 
362  case '!': { // Merge the parameters to one: "[param 1] [param 2] [param 3...]"
363  alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
364  for (uint i = 0; i != tokencount; i++) {
365  if (i != 0) alias_stream = strecpy(alias_stream, " ", lastof(alias_buffer));
366  alias_stream = strecpy(alias_stream, tokens[i], lastof(alias_buffer));
367  }
368  alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
369  break;
370  }
371 
372  default: { // One specific parameter: %A = [param 1] %B = [param 2] ...
373  int param = *cmdptr - 'A';
374 
375  if (param < 0 || param >= tokencount) {
376  IConsoleError("too many or wrong amount of parameters passed to alias, aborting");
377  IConsolePrintF(CC_WARNING, "Usage of alias '%s': %s", alias->name, alias->cmdline);
378  return;
379  }
380 
381  alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
382  alias_stream = strecpy(alias_stream, tokens[param], lastof(alias_buffer));
383  alias_stream = strecpy(alias_stream, "\"", lastof(alias_buffer));
384  break;
385  }
386  }
387  break;
388 
389  default:
390  *alias_stream++ = *cmdptr;
391  *alias_stream = '\0';
392  break;
393  }
394 
395  if (alias_stream >= lastof(alias_buffer) - 1) {
396  IConsoleError("Requested alias execution would overflow execution buffer");
397  return;
398  }
399  }
400 
401  IConsoleCmdExec(alias_buffer);
402 }
403 
409 void IConsoleCmdExec(const char *cmdstr)
410 {
411  const char *cmdptr;
412  char *tokens[ICON_TOKEN_COUNT], tokenstream[ICON_MAX_STREAMSIZE];
413  uint t_index, tstream_i;
414 
415  bool longtoken = false;
416  bool foundtoken = false;
417 
418  if (cmdstr[0] == '#') return; // comments
419 
420  for (cmdptr = cmdstr; *cmdptr != '\0'; cmdptr++) {
421  if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
422  IConsoleError("command contains malformed characters, aborting");
423  IConsolePrintF(CC_ERROR, "ERROR: command was: '%s'", cmdstr);
424  return;
425  }
426  }
427 
428  DEBUG(console, 4, "Executing cmdline: '%s'", cmdstr);
429 
430  memset(&tokens, 0, sizeof(tokens));
431  memset(&tokenstream, 0, sizeof(tokenstream));
432 
433  /* 1. Split up commandline into tokens, separated by spaces, commands
434  * enclosed in "" are taken as one token. We can only go as far as the amount
435  * of characters in our stream or the max amount of tokens we can handle */
436  for (cmdptr = cmdstr, t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
437  if (tstream_i >= lengthof(tokenstream)) {
438  IConsoleError("command line too long");
439  return;
440  }
441 
442  switch (*cmdptr) {
443  case ' ': // Token separator
444  if (!foundtoken) break;
445 
446  if (longtoken) {
447  tokenstream[tstream_i] = *cmdptr;
448  } else {
449  tokenstream[tstream_i] = '\0';
450  foundtoken = false;
451  }
452 
453  tstream_i++;
454  break;
455  case '"': // Tokens enclosed in "" are one token
456  longtoken = !longtoken;
457  if (!foundtoken) {
458  if (t_index >= lengthof(tokens)) {
459  IConsoleError("command line too long");
460  return;
461  }
462  tokens[t_index++] = &tokenstream[tstream_i];
463  foundtoken = true;
464  }
465  break;
466  case '\\': // Escape character for ""
467  if (cmdptr[1] == '"' && tstream_i + 1 < lengthof(tokenstream)) {
468  tokenstream[tstream_i++] = *++cmdptr;
469  break;
470  }
471  FALLTHROUGH;
472  default: // Normal character
473  tokenstream[tstream_i++] = *cmdptr;
474 
475  if (!foundtoken) {
476  if (t_index >= lengthof(tokens)) {
477  IConsoleError("command line too long");
478  return;
479  }
480  tokens[t_index++] = &tokenstream[tstream_i - 1];
481  foundtoken = true;
482  }
483  break;
484  }
485  }
486 
487  for (uint i = 0; i < lengthof(tokens) && tokens[i] != NULL; i++) {
488  DEBUG(console, 8, "Token %d is: '%s'", i, tokens[i]);
489  }
490 
491  if (StrEmpty(tokens[0])) return; // don't execute empty commands
492  /* 2. Determine type of command (cmd or alias) and execute
493  * First try commands, then aliases. Execute
494  * the found action taking into account its hooking code
495  */
496  RemoveUnderscores(tokens[0]);
497  IConsoleCmd *cmd = IConsoleCmdGet(tokens[0]);
498  if (cmd != NULL) {
499  ConsoleHookResult chr = (cmd->hook == NULL ? CHR_ALLOW : cmd->hook(true));
500  switch (chr) {
501  case CHR_ALLOW:
502  if (!cmd->proc(t_index, tokens)) { // index started with 0
503  cmd->proc(0, NULL); // if command failed, give help
504  }
505  return;
506 
507  case CHR_DISALLOW: return;
508  case CHR_HIDE: break;
509  }
510  }
511 
512  t_index--;
513  IConsoleAlias *alias = IConsoleAliasGet(tokens[0]);
514  if (alias != NULL) {
515  IConsoleAliasExec(alias, t_index, &tokens[1]);
516  return;
517  }
518 
519  IConsoleError("command not found");
520 }
IConsoleCmd * next
next command in list
void IConsoleWarning(const char *string)
It is possible to print warnings to the console.
Definition: console.cpp:165
IConsoleCmd * _iconsole_cmds
list of registered commands
Definition: console.cpp:28
char * name
Name of the company if the user changed it.
Definition: company_base.h:56
char * name
name of the alias
uint8 developer
print non-fatal warnings in console (>= 1), copy debug output to console (== 2)
Functions related to debugging.
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:50
static const uint ICON_TOKEN_COUNT
Maximum number of tokens in one command.
Definition: console.cpp:25
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition: network.cpp:64
static const AdminIndex INVALID_ADMIN_ID
An invalid admin marker.
Definition: network_type.h:58
IConsoleCmdProc * proc
process executed when command is typed
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
char * name
name of command
static const TextColour CC_DEFAULT
Default colour of the console.
Definition: console_type.h:25
IConsoleAlias * _iconsole_aliases
list of registered aliases
Definition: console.cpp:29
bool IsValidConsoleColour(TextColour c)
Check whether the given TextColour is valid for console usage.
AdminIndex _redirect_console_to_admin
Redirection of the (remote) console to the admin.
void IConsoleGUIPrint(TextColour colour_code, char *str)
Handle the printing of text entered into the console or redirected there by any other means...
Hide the existence of the command.
void IConsoleDebug(const char *dbg, const char *string)
It is possible to print debugging information to the console, which is achieved by using this functio...
Definition: console.cpp:154
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:59
const char * GetLogPrefix()
Get the prefix for logs; if show_date_in_logs is enabled it returns the date, otherwise it returns no...
Definition: debug.cpp:256
void NetworkAdminConsole(const char *origin, const char *string)
Send console to the admin network (if they did opt in for the respective update). ...
bool IConsoleCmdProc(byte argc, char *argv[])
–Commands– Commands are commands, or functions.
bool IsValidChar(WChar key, CharSetFilter afilter)
Only allow certain keys.
Definition: string.cpp:338
Internally used functions for the console.
IConsoleAlias * next
next alias in list
void str_validate(char *str, const char *last, StringValidationSettings settings)
Scans the string for valid characters and if it finds invalid ones, replaces them with a question mar...
Definition: string.cpp:184
static const uint ICON_MAX_STREAMSIZE
maximum length of a totally expanded command
void IConsolePrint(TextColour colour_code, const char *string)
Handle the printing of text entered into the console or redirected there by any other means...
Definition: console.cpp:88
IConsoleCmd * IConsoleCmdGet(const char *name)
Find the command pointed to by its string.
Definition: console.cpp:272
void IConsoleCmdExec(const char *cmdstr)
Execute a given command passed to us.
Definition: console.cpp:409
Allow command execution.
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:76
Types related to global configuration settings.
void CDECL IConsolePrintF(TextColour colour_code, const char *format,...)
Handle the printing of text entered into the console or redirected there by any other means...
Definition: console.cpp:132
Definition of base types and functions in a cross-platform compatible way.
static const TextColour CC_DEBUG
Colour for debug output.
Definition: console_type.h:29
ConsoleHookResult
Return values of console hooks (#IConsoleHook).
A number of safeguards to prevent using unsafe methods.
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:247
static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT])
An alias is just another name for a command, or for more commands Execute it as well.
Definition: console.cpp:327
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:126
Console functions used outside of the console code.
void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string)
Send an rcon reply to the client.
Basic functions/variables used all over the place.
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
void str_strip_colours(char *str)
Scans the string for colour codes and strips them.
Definition: string.cpp:272
void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const char *string)
Pass the rcon reply to the admin.
IConsoleAlias * IConsoleAliasGet(const char *name)
Find the alias pointed to by its string.
Definition: console.cpp:310
char * RemoveUnderscores(char *name)
Remove underscores from a string; the string will be modified!
Definition: console.cpp:241
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:39
Both numeric and alphabetic and spaces and stuff.
Definition: string_type.h:27
GUISettings gui
settings related to the GUI
–Aliases– Aliases are like shortcuts for complex functions, variable assignments, etc.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
void IConsoleAliasRegister(const char *name, const char *cmd)
Register a an alias for an already existing command in the console.
Definition: console.cpp:287
Client is not part of anything.
Definition: network_type.h:44
char * cmdline
command(s) that is/are being aliased
IConsoleHook * hook
any special trigger action that needs executing
void IConsoleError(const char *string)
It is possible to print error information to the console.
Definition: console.cpp:175
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:68
Network functions used by other parts of OpenTTD.
static const TextColour CC_ERROR
Colour for error lines.
Definition: console_type.h:26
void IConsoleAddSorted(T **base, T *item_new)
Add an item to an alphabetically sorted list.
Definition: console.cpp:210
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:114
Disallow command execution.
static const TextColour CC_WARNING
Colour for warning lines.
Definition: console_type.h:27
bool GetArgumentInteger(uint32 *value, const char *arg)
Change a string into its number representation.
Definition: console.cpp:187
void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook)
Register a new command to be used in the console.
Definition: console.cpp:256
Server part of the admin network protocol.