OpenTTD Source 20261112-master-gbcbec5e63f
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
13#include "console_internal.h"
14#include "network/network.h"
17#include "debug.h"
18#include "console_func.h"
19#include "fileio_type.h"
20#include "string_func.h"
21
22#include "safeguards.h"
23
24static const uint ICON_MAX_RECURSE = 10;
25
26/* console parser */
27/* static */ IConsole::CommandList &IConsole::Commands()
28{
29 static IConsole::CommandList cmds;
30 return cmds;
31}
32
33/* static */ IConsole::AliasList &IConsole::Aliases()
34{
35 static IConsole::AliasList aliases;
36 return aliases;
37}
38
39std::optional<FileHandle> _iconsole_output_file;
40
41void IConsoleInit()
42{
43 _iconsole_output_file = std::nullopt;
45 _redirect_console_to_admin = AdminID::Invalid();
46
47 IConsoleGUIInit();
48
50}
51
52static void IConsoleWriteToLogFile(const std::string &string)
53{
54 if (_iconsole_output_file.has_value()) {
55 /* if there is an console output file ... also print it there */
56 try {
57 fmt::print(*_iconsole_output_file, "{}{}\n", GetLogPrefix(), string);
58 } catch (const std::system_error &) {
59 _iconsole_output_file.reset();
60 IConsolePrint(CC_ERROR, "Cannot write to console log file; closing the log file.");
61 }
62 }
63}
64
65bool CloseConsoleLogIfActive()
66{
67 if (_iconsole_output_file.has_value()) {
68 IConsolePrint(CC_INFO, "Console log file closed.");
69 _iconsole_output_file.reset();
70 return true;
71 }
72
73 return false;
74}
75
76void IConsoleFree()
77{
78 IConsoleGUIFree();
79 CloseConsoleLogIfActive();
80}
81
91void IConsolePrint(ExtendedTextColour colour_code, const std::string &string)
92{
93 assert(IsValidConsoleColour(colour_code));
94
96 /* Redirect the string to the client */
98 return;
99 }
100
101 if (_redirect_console_to_admin != AdminID::Invalid()) {
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, {});
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
127static std::string RemoveUnderscores(std::string name)
128{
129 name.erase(std::remove(name.begin(), name.end(), '_'), name.end());
130 return name;
131}
132
139/* static */ void IConsole::CmdRegister(const std::string &name, IConsoleCmdProc *proc, IConsoleHook *hook)
140{
141 IConsole::Commands().try_emplace(RemoveUnderscores(name), name, proc, hook);
142}
143
149/* static */ IConsoleCmd *IConsole::CmdGet(const std::string &name)
150{
151 auto item = IConsole::Commands().find(RemoveUnderscores(name));
152 if (item != IConsole::Commands().end()) return &item->second;
153 return nullptr;
154}
155
161/* static */ void IConsole::AliasRegister(const std::string &name, std::string_view cmd)
162{
163 auto result = IConsole::Aliases().try_emplace(RemoveUnderscores(name), name, cmd);
164 if (!result.second) IConsolePrint(CC_ERROR, "An alias with the name '{}' already exists.", name);
165}
166
172/* static */ IConsoleAlias *IConsole::AliasGet(const std::string &name)
173{
174 auto item = IConsole::Aliases().find(RemoveUnderscores(name));
175 if (item != IConsole::Aliases().end()) return &item->second;
176 return nullptr;
177}
178
186static void IConsoleAliasExec(const IConsoleAlias *alias, std::span<std::string> tokens, uint recurse_count)
187{
188 Debug(Facility::Console, Severity::Debug2, "Requested command is an alias; parsing...");
189
190 if (recurse_count > ICON_MAX_RECURSE) {
191 IConsolePrint(CC_ERROR, "Too many alias expansions, recursion limit reached.");
192 return;
193 }
194
195 std::string buffer;
196 StringBuilder builder{buffer};
197
198 StringConsumer consumer{alias->cmdline};
199 while (consumer.AnyBytesLeft()) {
200 auto c = consumer.TryReadUtf8();
201 if (!c.has_value()) {
202 IConsolePrint(CC_ERROR, "Alias '{}' ('{}') contains malformed characters.", alias->name, alias->cmdline);
203 return;
204 }
205
206 switch (*c) {
207 case '\'': // ' will double for ""
208 builder.PutChar('\"');
209 break;
210
211 case ';': // Cmd separator; execute previous and start new command
212 IConsoleCmdExec(builder.GetString(), recurse_count);
213
214 buffer.clear();
215 break;
216
217 case '%': // Some or all parameters
218 c = consumer.ReadUtf8();
219 switch (*c) {
220 case '+': { // All parameters separated: "[param 1]" "[param 2]"
221 for (size_t i = 0; i < tokens.size(); ++i) {
222 if (i != 0) builder.PutChar(' ');
223 builder.PutChar('\"');
224 builder += tokens[i];
225 builder.PutChar('\"');
226 }
227 break;
228 }
229
230 case '!': { // Merge the parameters to one: "[param 1] [param 2] [param 3...]"
231 builder.PutChar('\"');
232 for (size_t i = 0; i < tokens.size(); ++i) {
233 if (i != 0) builder.PutChar(' ');
234 builder += tokens[i];
235 }
236 builder.PutChar('\"');
237 break;
238 }
239
240 default: { // One specific parameter: %A = [param 1] %B = [param 2] ...
241 size_t param = *c - 'A';
242
243 if (param >= tokens.size()) {
244 IConsolePrint(CC_ERROR, "Too many or wrong amount of parameters passed to alias.");
245 IConsolePrint(CC_HELP, "Usage of alias '{}': '{}'.", alias->name, alias->cmdline);
246 return;
247 }
248
249 builder.PutChar('\"');
250 builder += tokens[param];
251 builder.PutChar('\"');
252 break;
253 }
254 }
255 break;
256
257 default:
258 builder.PutUtf8(*c);
259 break;
260 }
261 }
262
263 IConsoleCmdExec(builder.GetString(), recurse_count);
264}
265
272void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
273{
274 if (command_string[0] == '#') return; // comments
275
276 Debug(Facility::Console, Severity::Info, "Executing cmdline: '{}'", command_string);
277
278 std::string buffer;
279 StringBuilder builder{buffer};
280 StringConsumer consumer{command_string};
281
282 std::vector<std::string> tokens;
283 bool found_token = false;
284 bool in_quotes = false;
285
286 /* 1. Split up commandline into tokens, separated by spaces, commands
287 * enclosed in "" are taken as one token. We can only go as far as the amount
288 * of characters in our stream or the max amount of tokens we can handle */
289 while (consumer.AnyBytesLeft()) {
290 auto c = consumer.TryReadUtf8();
291 if (!c.has_value()) {
292 IConsolePrint(CC_ERROR, "Command '{}' contains malformed characters.", command_string);
293 return;
294 }
295
296 switch (*c) {
297 case ' ': // Token separator
298 if (!found_token) break;
299
300 if (in_quotes) {
301 builder.PutUtf8(*c);
302 break;
303 }
304
305 tokens.emplace_back(std::move(buffer));
306 buffer.clear();
307 found_token = false;
308 break;
309
310 case '"': // Tokens enclosed in "" are one token
311 in_quotes = !in_quotes;
312 found_token = true;
313 break;
314
315 case '\\': // Escape character for ""
316 if (consumer.ReadUtf8If('"')) {
317 builder.PutUtf8('"');
318 break;
319 }
320 [[fallthrough]];
321
322 default: // Normal character
323 builder.PutUtf8(*c);
324 found_token = true;
325 break;
326 }
327 }
328
329 if (found_token) {
330 tokens.emplace_back(std::move(buffer));
331 buffer.clear();
332 }
333
334 for (size_t i = 0; i < tokens.size(); i++) {
335 Debug(Facility::Console, Severity::Trace2, "Token {} is: '{}'", i, tokens[i]);
336 }
337
338 if (tokens.empty() || tokens[0].empty()) return; // don't execute empty commands
339 /* 2. Determine type of command (cmd or alias) and execute
340 * First try commands, then aliases. Execute
341 * the found action taking into account its hooking code
342 */
343 IConsoleCmd *cmd = IConsole::CmdGet(tokens[0]);
344 if (cmd != nullptr) {
345 ConsoleHookResult chr = (cmd->hook == nullptr ? ConsoleHookResult::Allow : cmd->hook(true));
346 switch (chr) {
348 std::vector<std::string_view> views;
349 for (auto &token : tokens) views.emplace_back(token);
350 if (!cmd->proc(views)) { // index started with 0
351 cmd->proc({}); // if command failed, give help
352 }
353 return;
354 }
355
356 case ConsoleHookResult::Disallow: return;
357 case ConsoleHookResult::Hide: break;
358 }
359 }
360
361 IConsoleAlias *alias = IConsole::AliasGet(tokens[0]);
362 if (alias != nullptr) {
363 IConsoleAliasExec(alias, std::span(tokens).subspan(1), recurse_count + 1);
364 return;
365 }
366
367 IConsolePrint(CC_ERROR, "Command '{}' not found.", tokens[0]);
368}
void PutUtf8(char32_t c)
Append UTF-8 char.
void PutChar(char c)
Append 8-bit char.
Compose data into a growing std::string.
std::string & GetString() noexcept
Get mutable already written data.
Parse data from a string / buffer.
char32_t ReadUtf8(char32_t def='?')
Read UTF-8 character, and advance reader.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
std::optional< char32_t > TryReadUtf8()
Try to read a UTF-8 character, and then advance reader.
bool ReadUtf8If(char32_t c)
Check whether the next UTF-8 char matches 'c', and skip it.
void IConsolePrint(ExtendedTextColour 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
static std::string RemoveUnderscores(std::string name)
Creates a copy of a string with underscores removed from it.
Definition console.cpp:127
void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
Definition console.cpp:272
static void IConsoleAliasExec(const IConsoleAlias *alias, std::span< std::string > tokens, uint recurse_count)
An alias is just another name for a command, or for more commands Execute it as well.
Definition console.cpp:186
static const uint ICON_MAX_RECURSE
Maximum number of recursion.
Definition console.cpp:24
void IConsoleStdLibRegister()
Console command registration.
Console functions used outside of the console code.
bool IsValidConsoleColour(ExtendedTextColour c)
Check whether the given TextColour is valid for console usage.
void IConsoleGUIPrint(ExtendedTextColour colour_code, const std::string &str)
Handle the printing of text entered into the console or redirected there by any other means.
Internally used functions for the console.
ConsoleHookResult(bool echo) IConsoleHook
Checks whether the command may be executed.
bool(std::span< std::string_view > argv) IConsoleCmdProc
Entrypoint of a console command.
ConsoleHookResult
Return values of console hooks (IConsoleHook).
@ Disallow
Disallow command execution.
@ Allow
Allow command execution.
@ Hide
Hide the existence of the command.
static const TextColour CC_HELP
Colour for help lines.
static const TextColour CC_INFO
Colour for information lines.
static const TextColour CC_ERROR
Colour for error lines.
std::string GetLogPrefix(bool force)
Get the prefix for logs.
Definition debug.cpp:190
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Console
Console message facility.
Definition debug_type.h:42
@ Debug2
Debug #2 - Low level debug messages.
Definition debug_type.h:21
@ Info
Info, information you might care about.
Definition debug_type.h:19
@ Trace2
Trace information #2.
Definition debug_type.h:23
Types for standard in/out file operations.
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition network.cpp:69
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:66
Basic functions/variables used all over the place.
void NetworkAdminConsole(std::string_view origin, std::string_view string)
Send console to the admin network (if they did opt in for the respective update).
void NetworkServerSendAdminRcon(AdminID admin_index, ExtendedTextColour colour_code, std::string_view string)
Pass the rcon reply to the admin.
AdminID _redirect_console_to_admin
Redirection of the (remote) console to the admin.
Server part of the admin network protocol.
Network functions used by other parts of OpenTTD.
void NetworkServerSendRcon(ClientID client_id, ExtendedTextColour colour_code, std::string_view string)
Send an rcon reply to the client.
@ Invalid
Client is not part of anything.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:118
Compose strings from textual and binary data.
Parse strings.
Functions related to low-level strings.
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
–Aliases– Aliases are like shortcuts for complex functions, variable assignments, etc.
std::string cmdline
command(s) that is/are being aliased
std::string name
name of the alias
–Commands– Commands are commands, or functions.
IConsoleCmdProc * proc
process executed when command is typed
IConsoleHook * hook
any special trigger action that needs executing
static void AliasRegister(const std::string &name, std::string_view cmd)
Register a an alias for an already existing command in the console.
Definition console.cpp:161
static IConsoleAlias * AliasGet(const std::string &name)
Find the alias pointed to by its string.
Definition console.cpp:172
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:139
static IConsoleCmd * CmdGet(const std::string &name)
Find the command pointed to by its string.
Definition console.cpp:149