OpenTTD Source: src/script/script_scanner.cpp Source File

OpenTTD Source 13.1

script_scanner.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 "../debug.h"
12 #include "../string_func.h"
13 #include "../settings_type.h"
14
15 #include "../script/squirrel.hpp"
16 #include "script_scanner.hpp"
17 #include "script_info.hpp"
18 #include "script_fatalerror.hpp"
19
20 #include "../network/network_content.h"
21 #include "../3rdparty/md5/md5.h"
22 #include "../tar_type.h"
23
24 #include "../safeguards.h"
25
26 bool ScriptScanner::AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename)
27 {
28 this->main_script = filename;
29 this->tar_file = tar_filename;
30
31 auto p = this->main_script.rfind(PATHSEPCHAR);
32 this->main_script.erase(p != std::string::npos ? p + 1 : 0);
33 this->main_script += "main.nut";
34
35 if (!FioCheckFileExists(filename, this->subdir) || !FioCheckFileExists(this->main_script, this->subdir)) return false;
36
37 this->ResetEngine();
38 try {
39 this->engine->LoadScript(filename.c_str());
40 } catch (Script_FatalError &e) {
41 Debug(script, 0, "Fatal error '{}' when trying to load the script '{}'.", e.GetErrorMessage(), filename);
42 return false;
43 }
44 return true;
45 }
46
47 ScriptScanner::ScriptScanner() :
48 engine(nullptr)
49 {
50 }
51
52 void ScriptScanner::ResetEngine()
53 {
54 this->engine->Reset();
55 this->engine->SetGlobalPointer(this);
56 this->RegisterAPI(this->engine);
57 }
58
59 void ScriptScanner::Initialize(const char *name)
60 {
61 this->engine = new Squirrel(name);
62
63 this->RescanDir();
64
65 this->ResetEngine();
66 }
67
68 ScriptScanner::~ScriptScanner()
69 {
70 this->Reset();
71
72 delete this->engine;
73 }
74
75 void ScriptScanner::RescanDir()
76 {
77 /* Forget about older scans */
78 this->Reset();
79
80 /* Scan for scripts */
81 this->Scan(this->GetFileName(), this->GetDirectory());
82 }
83
84 void ScriptScanner::Reset()
85 {
86 for (const auto &item : this->info_list) {
87 free(item.first);
88 delete item.second;
89 }
90 for (const auto &item : this->info_single_list) {
91 free(item.first);
92 }
93
94 this->info_list.clear();
95 this->info_single_list.clear();
96 }
97
98 void ScriptScanner::RegisterScript(ScriptInfo *info)
99 {
100 char script_original_name[1024];
101 this->GetScriptName(info, script_original_name, lastof(script_original_name));
102 strtolower(script_original_name);
103
104 char script_name[1024];
105 seprintf(script_name, lastof(script_name), "%s.%d", script_original_name, info->GetVersion());
106
107 /* Check if GetShortName follows the rules */
108 if (strlen(info->GetShortName()) != 4) {
109 Debug(script, 0, "The script '{}' returned a string from GetShortName() which is not four characaters. Unable to load the script.", info->GetName());
110 delete info;
111 return;
112 }
113
114 if (this->info_list.find(script_name) != this->info_list.end()) {
115 /* This script was already registered */
116 #ifdef _WIN32
117 /* Windows doesn't care about the case */
118 if (strcasecmp(this->info_list[script_name]->GetMainScript(), info->GetMainScript()) == 0) {
119 #else
120 if (strcmp(this->info_list[script_name]->GetMainScript(), info->GetMainScript()) == 0) {
121 #endif
122 delete info;
123 return;
124 }
125
126 Debug(script, 1, "Registering two scripts with the same name and version");
127 Debug(script, 1, " 1: {}", this->info_list[script_name]->GetMainScript());
128 Debug(script, 1, " 2: {}", info->GetMainScript());
129 Debug(script, 1, "The first is taking precedence.");
130
131 delete info;
132 return;
133 }
134
135 this->info_list[stredup(script_name)] = info;
136
137 if (!info->IsDeveloperOnly() || _settings_client.gui.ai_developer_tools) {
138 /* Add the script to the 'unique' script list, where only the highest version
139 * of the script is registered. */
140 if (this->info_single_list.find(script_original_name) == this->info_single_list.end()) {
141 this->info_single_list[stredup(script_original_name)] = info;
142 } else if (this->info_single_list[script_original_name]->GetVersion() < info->GetVersion()) {
143 this->info_single_list[script_original_name] = info;
144 }
145 }
146 }
147
148 std::string ScriptScanner::GetConsoleList(bool newest_only) const
149 {
150 std::string p;
151 p += fmt::format("List of {}:\n", this->GetScannerName());
152 const ScriptInfoList &list = newest_only ? this->info_single_list : this->info_list;
153 for (const auto &item : list) {
154 ScriptInfo *i = item.second;
155 p += fmt::format("{:>10} (v{:d}): {}\n", i->GetName(), i->GetVersion(), i->GetDescription());
156 }
157 p += "\n";
158
159 return p;
160 }
161
163 struct ScriptFileChecksumCreator : FileScanner {
164 byte md5sum[16];
165 Subdirectory dir;
166
171 ScriptFileChecksumCreator(Subdirectory dir)
172 {
173 this->dir = dir;
174 memset(this->md5sum, 0, sizeof(this->md5sum));
175 }
176
177 /* Add the file and calculate the md5 sum. */
178 virtual bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename)
179 {
180 Md5 checksum;
181 uint8 buffer[1024];
182 size_t len, size;
183 byte tmp_md5sum[16];
184
185 /* Open the file ... */
186 FILE *f = FioFOpenFile(filename, "rb", this->dir, &size);
187 if (f == nullptr) return false;
188
189 /* ... calculate md5sum... */
190 while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
191 size -= len;
192 checksum.Append(buffer, len);
193 }
194 checksum.Finish(tmp_md5sum);
195
196 FioFCloseFile(f);
197
198 /* ... and xor it to the overall md5sum. */
199 for (uint i = 0; i < sizeof(md5sum); i++) this->md5sum[i] ^= tmp_md5sum[i];
200
201 return true;
202 }
203 };
204
213 static bool IsSameScript(const ContentInfo *ci, bool md5sum, ScriptInfo *info, Subdirectory dir)
214 {
215 uint32 id = 0;
216 const char *str = info->GetShortName();
217 for (int j = 0; j < 4 && *str != '\0'; j++, str++) id |= *str << (8 * j);
218
219 if (id != ci->unique_id) return false;
220 if (!md5sum) return true;
221
222 ScriptFileChecksumCreator checksum(dir);
223 auto tar_filename = info->GetTarFile();
224 TarList::iterator iter;
225 if (!tar_filename.empty() && (iter = _tar_list[dir].find(tar_filename)) != _tar_list[dir].end()) {
226 /* The main script is in a tar file, so find all files that
227 * are in the same tar and add them to the MD5 checksumming. */
228 for (const auto &tar : _tar_filelist[dir]) {
229 /* Not in the same tar. */
230 if (tar.second.tar_filename != iter->first) continue;
231
232 /* Check the extension. */
233 const char *ext = strrchr(tar.first.c_str(), '.');
234 if (ext == nullptr || strcasecmp(ext, ".nut") != 0) continue;
235
236 checksum.AddFile(tar.first, 0, tar_filename);
237 }
238 } else {
239 char path[MAX_PATH];
240 strecpy(path, info->GetMainScript(), lastof(path));
241 /* There'll always be at least 1 path separator character in a script
242 * main script name as the search algorithm requires the main script to
243 * be in a subdirectory of the script directory; so <dir>/<path>/main.nut. */
244 *strrchr(path, PATHSEPCHAR) = '\0';
245 checksum.Scan(".nut", path);
246 }
247
248 return memcmp(ci->md5sum, checksum.md5sum, sizeof(ci->md5sum)) == 0;
249 }
250
251 bool ScriptScanner::HasScript(const ContentInfo *ci, bool md5sum)
252 {
253 for (const auto &item : this->info_list) {
254 if (IsSameScript(ci, md5sum, item.second, this->GetDirectory())) return true;
255 }
256 return false;
257 }
258
259 const char *ScriptScanner::FindMainScript(const ContentInfo *ci, bool md5sum)
260 {
261 for (const auto &item : this->info_list) {
262 if (IsSameScript(ci, md5sum, item.second, this->GetDirectory())) return item.second->GetMainScript();
263 }
264 return nullptr;
265 }
ScriptScanner::GetScriptName
virtual void GetScriptName(ScriptInfo *info, char *name, const char *last)=0
Get the script name how to store the script in memory.
ScriptFileChecksumCreator::md5sum
byte md5sum[16]
The final md5sum.
Definition: script_scanner.cpp:164
ScriptInfo::GetMainScript
const char * GetMainScript() const
Get the filename of the main.nut script.
Definition: script_info.hpp:90
ScriptFileChecksumCreator
Helper for creating a MD5sum of all files within of a script.
Definition: script_scanner.cpp:163
ScriptScanner::GetConsoleList
std::string GetConsoleList(bool newest_only) const
Get the list of registered scripts to print on the console.
Definition: script_scanner.cpp:148
strtolower
bool strtolower(char *str)
Convert a given ASCII string to lowercase.
Definition: string.cpp:465
ScriptScanner::engine
class Squirrel * engine
The engine we're scanning with.
Definition: script_scanner.hpp:86
ScriptFileChecksumCreator::ScriptFileChecksumCreator
ScriptFileChecksumCreator(Subdirectory dir)
Initialise the md5sum to be all zeroes, so we can easily xor the data.
Definition: script_scanner.cpp:171
ScriptScanner::GetMainScript
std::string GetMainScript()
Get the current main script the ScanDir is currently tracking.
Definition: script_scanner.hpp:35
FileScanner::Scan
uint Scan(const char *extension, Subdirectory sd, bool tars=true, bool recursive=true)
Scan for files with the given extension in the given search path.
Definition: fileio.cpp:1216
ScriptScanner::RegisterAPI
virtual void RegisterAPI(class Squirrel *engine)=0
Register the API for this ScriptInfo.
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
ScriptScanner::tar_file
std::string tar_file
If, which tar file the script was in.
Definition: script_scanner.hpp:88
Squirrel::Reset
void Reset()
Completely reset the engine; start from scratch.
Definition: squirrel.cpp:787
Script_FatalError::GetErrorMessage
const std::string & GetErrorMessage() const
The error message associated with the fatal error.
Definition: script_fatalerror.hpp:30
ScriptInfo::GetTarFile
std::string GetTarFile() const
Get the filename of the tar the script is in.
Definition: script_info.hpp:95
ScriptInfo::GetDescription
const char * GetDescription() const
Get the description of the script.
Definition: script_info.hpp:65
ScriptInfo::IsDeveloperOnly
virtual bool IsDeveloperOnly() const
Can this script be selected by developers only?
Definition: script_info.hpp:145
ScriptScanner::RescanDir
void RescanDir()
Rescan the script dir.
Definition: script_scanner.cpp:75
ScriptScanner::ResetEngine
void ResetEngine()
Reset the engine to ensure a clean environment for further steps.
Definition: script_scanner.cpp:52
Squirrel
Definition: squirrel.hpp:23
Squirrel::LoadScript
bool LoadScript(const char *script)
Load a script.
Definition: squirrel.cpp:757
GUISettings::ai_developer_tools
bool ai_developer_tools
activate AI/GS developer tools
Definition: settings_type.h:193
ScriptInfoList
std::map< const char *, class ScriptInfo *, StringCompare > ScriptInfoList
A list that maps AI names to their AIInfo object.
Definition: ai.hpp:19
ScriptScanner::GetFileName
virtual const char * GetFileName() const =0
Get the filename to scan for this type of script.
FioFOpenFile
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:245
ContentInfo
Container for all important information about a piece of content.
Definition: tcp_content_type.h:50
ScriptScanner::AddFile
bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename) override
Add a file with the given filename.
Definition: script_scanner.cpp:26
Squirrel::SetGlobalPointer
void SetGlobalPointer(void *ptr)
Sets a pointer in the VM that is reachable from where ever you are in SQ.
Definition: squirrel.hpp:221
ScriptInfo::GetShortName
const char * GetShortName() const
Get the 4 character long short name of the script.
Definition: script_info.hpp:60
ContentInfo::md5sum
byte md5sum[16]
The MD5 checksum.
Definition: tcp_content_type.h:70
FileScanner::subdir
Subdirectory subdir
The current sub directory we are searching through.
Definition: fileio_func.h:41
ScriptFileChecksumCreator::AddFile
virtual bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename)
Add a file with the given filename.
Definition: script_scanner.cpp:178
ScriptScanner::main_script
std::string main_script
The full path of the script.
Definition: script_scanner.hpp:87
ScriptScanner::HasScript
bool HasScript(const struct ContentInfo *ci, bool md5sum)
Check whether we have a script with the exact characteristics as ci.
Definition: script_scanner.cpp:251
ScriptScanner::info_list
ScriptInfoList info_list
The list of all script.
Definition: script_scanner.hpp:90
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:108
ScriptScanner::GetScannerName
virtual const char * GetScannerName() const =0
Get the type of the script, in plural.
ScriptScanner::RegisterScript
void RegisterScript(class ScriptInfo *info)
Register a ScriptInfo to the scanner.
Definition: script_scanner.cpp:98
ScriptInfo::GetVersion
int GetVersion() const
Get the version of the script.
Definition: script_info.hpp:70
ScriptScanner::Reset
void Reset()
Reset all allocated lists.
Definition: script_scanner.cpp:84
script_info.hpp
ScriptScanner::GetDirectory
virtual Subdirectory GetDirectory() const =0
Get the directory to scan in.
script_scanner.hpp
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:554
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
Script_FatalError
A throw-class that is given when the script made a fatal error.
Definition: script_fatalerror.hpp:16
ContentInfo::unique_id
uint32 unique_id
Unique ID; either GRF ID or shortname.
Definition: tcp_content_type.h:69
ScriptFileChecksumCreator::dir
Subdirectory dir
The directory to look in.
Definition: script_scanner.cpp:165
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
script_fatalerror.hpp
FileScanner
Helper for scanning for files with a given name.
Definition: fileio_func.h:39
ScriptInfo::GetName
const char * GetName() const
Get the Name of the script.
Definition: script_info.hpp:55
ScriptScanner::FindMainScript
const char * FindMainScript(const ContentInfo *ci, bool md5sum)
Find a script of a ContentInfo.
Definition: script_scanner.cpp:259
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:113
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
ScriptInfo
All static information from an Script like name, version, etc.
Definition: script_info.hpp:30
IsSameScript
static bool IsSameScript(const ContentInfo *ci, bool md5sum, ScriptInfo *info, Subdirectory dir)
Check whether the script given in info is the same as in ci based on the shortname and md5 sum.
Definition: script_scanner.cpp:213
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
ScriptScanner::info_single_list
ScriptInfoList info_single_list
The list of all unique script. The best script (highest version) is shown.
Definition: script_scanner.hpp:91
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:604
FioFCloseFile
void FioFCloseFile(FILE *f)
Close a file in a safe way.
Definition: fileio.cpp:130