/* $Id$ */ /* * This file is part of OpenTTD. * 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. * 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. * 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 . */ /** @file console_cmds.cpp Implementation of the console hooks. */ #include "stdafx.h" #include "console_internal.h" #include "debug.h" #include "engine_func.h" #include "landscape.h" #include "saveload/saveload.h" #include "network/network.h" #include "network/network_func.h" #include "network/network_base.h" #include "command_func.h" #include "settings_func.h" #include "fios.h" #include "fileio_func.h" #include "screenshot.h" #include "genworld.h" #include "strings_func.h" #include "viewport_func.h" #include "window_func.h" #include "date_func.h" #include "vehicle_func.h" #include "company_func.h" #include "company_base.h" #include "gamelog.h" #include "ai/ai.hpp" #include "ai/ai_config.hpp" #ifdef ENABLE_NETWORK #include "table/strings.h" #endif /* ENABLE_NETWORK */ /* scriptfile handling */ static FILE *_script_file; static bool _script_running; /* console command / variable defines */ #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[]) #define DEF_CONSOLE_HOOK(function) static bool function() /***************************** * variable and command hooks *****************************/ #ifdef ENABLE_NETWORK static inline bool NetworkAvailable() { if (!_network_available) { IConsoleError("You cannot use this command because there is no network available."); return false; } return true; } DEF_CONSOLE_HOOK(ConHookServerOnly) { if (!NetworkAvailable()) return false; if (!_network_server) { IConsoleError("This command/variable is only available to a network server."); return false; } return true; } DEF_CONSOLE_HOOK(ConHookClientOnly) { if (!NetworkAvailable()) return false; if (_network_server) { IConsoleError("This command/variable is not available to a network server."); return false; } return true; } DEF_CONSOLE_HOOK(ConHookNeedNetwork) { if (!NetworkAvailable()) return false; if (!_networking) { IConsoleError("Not connected. This command/variable is only available in multiplayer."); return false; } return true; } DEF_CONSOLE_HOOK(ConHookNoNetwork) { if (_networking) { IConsoleError("This command/variable is forbidden in multiplayer."); return false; } return true; } #endif /* ENABLE_NETWORK */ static void IConsoleHelp(const char *str) { IConsolePrintF(CC_WARNING, "- %s", str); } DEF_CONSOLE_CMD(ConResetEngines) { if (argc == 0) { IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'"); return true; } StartupEngines(); return true; } #ifdef _DEBUG DEF_CONSOLE_CMD(ConResetTile) { if (argc == 0) { IConsoleHelp("Reset a tile to bare land. Usage: 'resettile '"); IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)"); return true; } if (argc == 2) { uint32 result; if (GetArgumentInteger(&result, argv[1])) { DoClearSquare((TileIndex)result); return true; } } return false; } DEF_CONSOLE_CMD(ConStopAllVehicles) { if (argc == 0) { IConsoleHelp("Stops all vehicles in the game. For debugging only! Use at your own risk... Usage: 'stopall'"); return true; } StopAllVehicles(); return true; } #endif /* _DEBUG */ DEF_CONSOLE_CMD(ConScrollToTile) { switch (argc) { case 0: IConsoleHelp("Center the screen on a given tile."); IConsoleHelp("Usage: 'scrollto ' or 'scrollto '"); IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B)."); return true; case 2: { uint32 result; if (GetArgumentInteger(&result, argv[1])) { if (result >= MapSize()) { IConsolePrint(CC_ERROR, "Tile does not exist"); return true; } ScrollMainWindowToTile((TileIndex)result); return true; } break; } case 3: { uint32 x, y; if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) { if (x >= MapSizeX() || y >= MapSizeY()) { IConsolePrint(CC_ERROR, "Tile does not exist"); return true; } ScrollMainWindowToTile(TileXY(x, y)); return true; } break; } } return false; } extern void BuildFileList(); extern void SetFiosType(const byte fiostype); /* Save the map to a file */ DEF_CONSOLE_CMD(ConSave) { if (argc == 0) { IConsoleHelp("Save the current game. Usage: 'save '"); return true; } if (argc == 2) { char *filename = str_fmt("%s.sav", argv[1]); IConsolePrint(CC_DEFAULT, "Saving map..."); if (SaveOrLoad(filename, SL_SAVE, SAVE_DIR) != SL_OK) { IConsolePrint(CC_ERROR, "Saving map failed"); } else { IConsolePrintF(CC_DEFAULT, "Map sucessfully saved to %s", filename); } free(filename); return true; } return false; } /* Explicitly save the configuration */ DEF_CONSOLE_CMD(ConSaveConfig) { if (argc == 0) { IConsoleHelp("Saves the current config, typically to 'openttd.cfg'."); return true; } SaveToConfig(); IConsolePrint(CC_DEFAULT, "Saved config."); return true; } static const FiosItem *GetFiosItem(const char *file) { _saveload_mode = SLD_LOAD_GAME; BuildFileList(); for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) { if (strcmp(file, item->name) == 0) return item; if (strcmp(file, item->title) == 0) return item; } /* If no name matches, try to parse it as number */ char *endptr; int i = strtol(file, &endptr, 10); if (file == endptr || *endptr != '\0') i = -1; return IsInsideMM(i, 0, _fios_items.Length()) ? _fios_items.Get(i) : NULL; } DEF_CONSOLE_CMD(ConLoad) { if (argc == 0) { IConsoleHelp("Load a game by name or index. Usage: 'load '"); return true; } if (argc != 2) return false; const char *file = argv[1]; const FiosItem *item = GetFiosItem(file); if (item != NULL) { switch (item->type) { case FIOS_TYPE_FILE: case FIOS_TYPE_OLDFILE: { _switch_mode = SM_LOAD; SetFiosType(item->type); strecpy(_file_to_saveload.name, FiosBrowseTo(item), lastof(_file_to_saveload.name)); strecpy(_file_to_saveload.title, item->title, lastof(_file_to_saveload.title)); } break; default: IConsolePrintF(CC_ERROR, "%s: Not a savegame.", file); } } else { IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file); } FiosFreeSavegameList(); return true; } DEF_CONSOLE_CMD(ConRemove) { if (argc == 0) { IConsoleHelp("Remove a savegame by name or index. Usage: 'rm '"); return true; } if (argc != 2) return false; const char *file = argv[1]; const FiosItem *item = GetFiosItem(file); if (item != NULL) { if (!FiosDelete(item->name)) IConsolePrintF(CC_ERROR, "%s: Failed to delete file", file); } else { IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file); } FiosFreeSavegameList(); return true; } /* List all the files in the current dir via console */ DEF_CONSOLE_CMD(ConListFiles) { if (argc == 0) { IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'"); return true; } BuildFileList(); for (uint i = 0; i < _fios_items.Length(); i++) { IConsolePrintF(CC_DEFAULT, "%d) %s", i, _fios_items[i].title); } FiosFreeSavegameList(); return true; } /* Change the dir via console */ DEF_CONSOLE_CMD(ConChangeDirectory) { if (argc == 0) { IConsoleHelp("Change the dir via console. Usage: 'cd '"); return true; } if (argc != 2) return false; const char *file = argv[1]; const FiosItem *item = GetFiosItem(file); if (item != NULL) { switch (item->type) { case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT: FiosBrowseTo(item); break; default: IConsolePrintF(CC_ERROR, "%s: Not a directory.", file); } } else { IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file); } FiosFreeSavegameList(); return true; } DEF_CONSOLE_CMD(ConPrintWorkingDirectory) { const char *path; if (argc == 0) { IConsoleHelp("Print out the current working directory. Usage: 'pwd'"); return true; } /* XXX - Workaround for broken file handling */ FiosGetSavegameList(SLD_LOAD_GAME); FiosFreeSavegameList(); FiosGetDescText(&path, NULL); IConsolePrint(CC_DEFAULT, path); return true; } DEF_CONSOLE_CMD(ConClearBuffer) { if (argc == 0) { IConsoleHelp("Clear the console buffer. Usage: 'clear'"); return true; } IConsoleClearBuffer(); SetWindowDirty(WC_CONSOLE, 0); return true; } /********************************** * Network Core Console Commands **********************************/ #ifdef ENABLE_NETWORK DEF_CONSOLE_CMD(ConBan) { NetworkClientInfo *ci; const char *banip = NULL; ClientID client_id; if (argc == 0) { IConsoleHelp("Ban a client from a network game. Usage: 'ban '"); IConsoleHelp("For client-id's, see the command 'clients'"); IConsoleHelp("If the client is no longer online, you can still ban his/her IP"); return true; } if (argc != 2) return false; if (strchr(argv[1], '.') == NULL && strchr(argv[1], ':') == NULL) { // banning with ID client_id = (ClientID)atoi(argv[1]); ci = NetworkFindClientInfoFromClientID(client_id); } else { // banning IP ci = NetworkFindClientInfoFromIP(argv[1]); if (ci == NULL) { banip = argv[1]; client_id = (ClientID)-1; } else { client_id = ci->client_id; } } if (client_id == CLIENT_ID_SERVER) { IConsoleError("Silly boy, you can not ban yourself!"); return true; } if (client_id == INVALID_CLIENT_ID || (ci == NULL && client_id != (ClientID)-1)) { IConsoleError("Invalid client"); return true; } if (ci != NULL) { IConsolePrint(CC_DEFAULT, "Client banned"); banip = GetClientIP(ci); } else { IConsolePrint(CC_DEFAULT, "Client not online, banned IP"); } NetworkServerBanIP(banip); return true; } DEF_CONSOLE_CMD(ConUnBan) { if (argc == 0) { IConsoleHelp("Unban a client from a network game. Usage: 'unban '"); IConsoleHelp("For a list of banned IP's, see the command 'banlist'"); return true; } if (argc != 2) return false; uint index = (strchr(argv[1], '.') == NULL) ? atoi(argv[1]) : 0; index--; uint i = 0; for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) { if (strcmp(_network_ban_list[i], argv[1]) == 0 || index == i) { free(_network_ban_list[i]); _network_ban_list.Erase(iter); IConsolePrint(CC_DEFAULT, "IP unbanned."); return true; } } IConsolePrint(CC_DEFAULT, "IP not in ban-list."); return true; } DEF_CONSOLE_CMD(ConBanList) { if (argc == 0) { IConsoleHelp("List the IP's of banned clients: Usage 'banlist'"); return true; } IConsolePrint(CC_DEFAULT, "Banlist: "); uint i = 1; for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) { IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter); } return true; } DEF_CONSOLE_CMD(ConPauseGame) { if (argc == 0) { IConsoleHelp("Pause a network game. Usage: 'pause'"); return true; } if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) { DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE); if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused."); } else { IConsolePrint(CC_DEFAULT, "Game is already paused."); } return true; } DEF_CONSOLE_CMD(ConUnPauseGame) { if (argc == 0) { IConsoleHelp("Unpause a network game. Usage: 'unpause'"); return true; } if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) { DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE); if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused."); } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) { IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console."); } else if (_pause_mode != PM_UNPAUSED) { IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients."); } else { IConsolePrint(CC_DEFAULT, "Game is already unpaused."); } return true; } DEF_CONSOLE_CMD(ConRcon) { if (argc == 0) { IConsoleHelp("Remote control the server from another client. Usage: 'rcon '"); IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent"); return true; } if (argc < 3) return false; if (_network_server) { IConsoleCmdExec(argv[2]); } else { NetworkClientSendRcon(argv[1], argv[2]); } return true; } DEF_CONSOLE_CMD(ConStatus) { if (argc == 0) { IConsoleHelp("List the status of all clients connected to the server. Usage 'status'"); return true; } NetworkServerShowStatusToConsole(); return true; } DEF_CONSOLE_CMD(ConServerInfo) { if (argc == 0) { IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'"); IConsoleHelp("You can change these values by setting the variables 'max_clients', 'max_companies' and 'max_spectators'"); return true; } IConsolePrintF(CC_DEFAULT, "Current/maximum clients: %2d/%2d", _network_game_info.clients_on, _settings_client.network.max_clients); IConsolePrintF(CC_DEFAULT, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client.network.max_companies); IConsolePrintF(CC_DEFAULT, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client.network.max_spectators); return true; } DEF_CONSOLE_CMD(ConClientNickChange) { if (argc != 3) { IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name '"); IConsoleHelp("For client-id's, see the command 'clients'"); return true; } ClientID client_id = (ClientID)atoi(argv[1]); if (client_id == CLIENT_ID_SERVER) { IConsoleError("Please use the command 'name' to change your own name!"); return true; } if (NetworkFindClientInfoFromClientID(client_id) == NULL) { IConsoleError("Invalid client"); return true; } if (!NetworkServerChangeClientName(client_id, argv[2])) { IConsoleError("Cannot give a client a duplicate name"); } return true; } DEF_CONSOLE_CMD(ConKick) { NetworkClientInfo *ci; ClientID client_id; if (argc == 0) { IConsoleHelp("Kick a client from a network game. Usage: 'kick '"); IConsoleHelp("For client-id's, see the command 'clients'"); return true; } if (argc != 2) return false; if (strchr(argv[1], '.') == NULL) { client_id = (ClientID)atoi(argv[1]); ci = NetworkFindClientInfoFromClientID(client_id); } else { ci = NetworkFindClientInfoFromIP(argv[1]); client_id = (ci == NULL) ? INVALID_CLIENT_ID : ci->client_id; } if (client_id == CLIENT_ID_SERVER) { IConsoleError("Silly boy, you can not kick yourself!"); return true; } if (client_id == INVALID_CLIENT_ID) { IConsoleError("Invalid client"); return true; } if (ci != NULL) { NetworkServerKickClient(client_id); } else { IConsoleError("Client not found"); } return true; } DEF_CONSOLE_CMD(ConJoinCompany) { if (argc < 2) { IConsoleHelp("Request joining another company. Usage: join []"); IConsoleHelp("For valid company-id see company list, use 255 for spectator"); return true; } CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1])); /* Check we have a valid company id! */ if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) { IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES); return true; } if (NetworkFindClientInfoFromClientID(_network_own_client_id)->client_playas == company_id) { IConsoleError("You are already there!"); return true; } if (company_id == COMPANY_SPECTATOR && NetworkMaxSpectatorsReached()) { IConsoleError("Cannot join spectators, maximum number of spectators reached."); return true; } if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) { IConsoleError("Cannot join AI company."); return true; } /* Check if the company requires a password */ if (NetworkCompanyIsPassworded(company_id) && argc < 3) { IConsolePrintF(CC_ERROR, "Company %d requires a password to join.", company_id + 1); return true; } /* non-dedicated server may just do the move! */ if (_network_server) { NetworkServerDoMove(CLIENT_ID_SERVER, company_id); } else { NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : ""); } return true; } DEF_CONSOLE_CMD(ConMoveClient) { if (argc < 3) { IConsoleHelp("Move a client to another company. Usage: move "); IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators"); return true; } const NetworkClientInfo *ci = NetworkFindClientInfoFromClientID((ClientID)atoi(argv[1])); CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2])); /* check the client exists */ if (ci == NULL) { IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's."); return true; } if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) { IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES); return true; } if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) { IConsoleError("You cannot move clients to AI companies."); return true; } if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) { IConsoleError("Silly boy, you cannot move the server!"); return true; } if (ci->client_playas == company_id) { IConsoleError("You cannot move someone to where he/she already is!"); return true; } /* we are the server, so force the update */ NetworkServerDoMove(ci->client_id, company_id); return true; } DEF_CONSOLE_CMD(ConResetCompany) { if (argc == 0) { IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company '"); IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc."); return true; } if (argc != 2) return false; CompanyID index = (CompanyID)(atoi(argv[1]) - 1); /* Check valid range */ if (!Company::IsValidID(index)) { IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES); return true; } if (!Company::IsHumanID(index)) { IConsoleError("Company is owned by an AI."); return true; } if (NetworkCompanyHasClients(index)) { IConsoleError("Cannot remove company: a client is connected to that company."); return false; } const NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER); if (ci->client_playas == index) { IConsoleError("Cannot remove company: the server is connected to that company."); return true; } /* It is safe to remove this company */ DoCommandP(0, 2, index, CMD_COMPANY_CTRL); IConsolePrint(CC_DEFAULT, "Company deleted."); return true; } DEF_CONSOLE_CMD(ConNetworkClients) { if (argc == 0) { IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'"); return true; } NetworkPrintClients(); return true; } DEF_CONSOLE_CMD(ConNetworkReconnect) { if (argc == 0) { IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect []'"); IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company."); IConsoleHelp("All others are a certain company with Company 1 being #1"); return true; } CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR; switch (playas) { case 0: playas = COMPANY_NEW_COMPANY; break; case COMPANY_SPECTATOR: /* nothing to do */ break; default: /* From a user pov 0 is a new company, internally it's different and all * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */ playas--; if (playas < COMPANY_FIRST || playas >= MAX_COMPANIES) return false; break; } if (StrEmpty(_settings_client.network.last_host)) { IConsolePrint(CC_DEFAULT, "No server for reconnecting."); return true; } /* Don't resolve the address first, just print it directly as it comes from the config file. */ IConsolePrintF(CC_DEFAULT, "Reconnecting to %s:%d...", _settings_client.network.last_host, _settings_client.network.last_port); NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), playas); return true; }; DEF_CONSOLE_CMD(ConNetworkConnect) { if (argc == 0) { IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect '"); IConsoleHelp("IP can contain port and company: 'IP[[#Company]:Port]', eg: 'server.ottd.org#2:443'"); IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1"); return true; } if (argc < 2) return false; if (_networking) NetworkDisconnect(); // we are in network-mode, first close it! const char *port = NULL; const char *company = NULL; char *ip = argv[1]; /* Default settings: default port and new company */ uint16 rport = NETWORK_DEFAULT_PORT; CompanyID join_as = COMPANY_NEW_COMPANY; ParseConnectionString(&company, &port, ip); IConsolePrintF(CC_DEFAULT, "Connecting to %s...", ip); if (company != NULL) { join_as = (CompanyID)atoi(company); IConsolePrintF(CC_DEFAULT, " company-no: %d", join_as); /* From a user pov 0 is a new company, internally it's different and all * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */ if (join_as != COMPANY_SPECTATOR) { if (join_as > MAX_COMPANIES) return false; join_as--; } } if (port != NULL) { rport = atoi(port); IConsolePrintF(CC_DEFAULT, " port: %s", port); } NetworkClientConnectGame(NetworkAddress(ip, rport), join_as); return true; } #endif /* ENABLE_NETWORK */ /********************************* * script file console commands *********************************/ DEF_CONSOLE_CMD(ConExec) { char cmdline[ICON_CMDLN_SIZE]; char *cmdptr; if (argc == 0) { IConsoleHelp("Execute a local script file. Usage: 'exec