OpenTTD Source  1.11.0-beta2
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 '%s' when trying to load the script '%s'.", e.GetErrorMessage(), filename.c_str());
42  return false;
43  }
44  return true;
45 }
46 
47 ScriptScanner::ScriptScanner() :
48  engine(nullptr)
49 {
50 }
51 
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 
76 {
77  /* Forget about older scans */
78  this->Reset();
79 
80  /* Scan for scripts */
81  this->Scan(this->GetFileName(), this->GetDirectory());
82 }
83 
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 
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 '%s' 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: %s", this->info_list[script_name]->GetMainScript());
128  DEBUG(script, 1, " 2: %s", 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 
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 char *ScriptScanner::GetConsoleList(char *p, const char *last, bool newest_only) const
149 {
150  p += seprintf(p, last, "List of %s:\n", this->GetScannerName());
151  const ScriptInfoList &list = newest_only ? this->info_single_list : this->info_list;
152  for (const auto &item : list) {
153  ScriptInfo *i = item.second;
154  p += seprintf(p, last, "%10s (v%d): %s\n", i->GetName(), i->GetVersion(), i->GetDescription());
155  }
156  p += seprintf(p, last, "\n");
157 
158  return p;
159 }
160 
163  byte md5sum[16];
165 
171  {
172  this->dir = dir;
173  memset(this->md5sum, 0, sizeof(this->md5sum));
174  }
175 
176  /* Add the file and calculate the md5 sum. */
177  virtual bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename)
178  {
179  Md5 checksum;
180  uint8 buffer[1024];
181  size_t len, size;
182  byte tmp_md5sum[16];
183 
184  /* Open the file ... */
185  FILE *f = FioFOpenFile(filename.c_str(), "rb", this->dir, &size);
186  if (f == nullptr) return false;
187 
188  /* ... calculate md5sum... */
189  while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
190  size -= len;
191  checksum.Append(buffer, len);
192  }
193  checksum.Finish(tmp_md5sum);
194 
195  FioFCloseFile(f);
196 
197  /* ... and xor it to the overall md5sum. */
198  for (uint i = 0; i < sizeof(md5sum); i++) this->md5sum[i] ^= tmp_md5sum[i];
199 
200  return true;
201  }
202 };
203 
212 static bool IsSameScript(const ContentInfo *ci, bool md5sum, ScriptInfo *info, Subdirectory dir)
213 {
214  uint32 id = 0;
215  const char *str = info->GetShortName();
216  for (int j = 0; j < 4 && *str != '\0'; j++, str++) id |= *str << (8 * j);
217 
218  if (id != ci->unique_id) return false;
219  if (!md5sum) return true;
220 
221  ScriptFileChecksumCreator checksum(dir);
222  auto tar_filename = info->GetTarFile();
223  TarList::iterator iter;
224  if (!tar_filename.empty() && (iter = _tar_list[dir].find(tar_filename)) != _tar_list[dir].end()) {
225  /* The main script is in a tar file, so find all files that
226  * are in the same tar and add them to the MD5 checksumming. */
227  TarFileList::iterator tar;
228  FOR_ALL_TARS(tar, 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:163
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:162
strtolower
bool strtolower(char *str)
Convert a given ASCII string to lowercase.
Definition: string.cpp:354
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:170
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:1367
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:79
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:697
ScriptInfo::GetTarFile
std::string GetTarFile() const
Get the filename of the tar the script is in.
Definition: script_info.hpp:95
ScriptScanner::GetConsoleList
char * GetConsoleList(char *p, const char *last, bool newest_only) const
Get the list of registered scripts to print on the console.
Definition: script_scanner.cpp:148
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:678
GUISettings::ai_developer_tools
bool ai_developer_tools
activate AI developer tools
Definition: settings_type.h:166
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.
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
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:406
ContentInfo
Container for all important information about a piece of content.
Definition: tcp_content.h:54
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.h:74
FileScanner::subdir
Subdirectory subdir
The current sub directory we are searching through.
Definition: fileio_func.h:61
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:177
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:266
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:442
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:137
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.h:73
ScriptFileChecksumCreator::dir
Subdirectory dir
The directory to look in.
Definition: script_scanner.cpp:164
script_fatalerror.hpp
FileScanner
Helper for scanning for files with a given name.
Definition: fileio_func.h:59
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:112
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:454
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:212
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:383
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
Script_FatalError::GetErrorMessage
const char * GetErrorMessage()
The error message associated with the fatal error.
Definition: script_fatalerror.hpp:30
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:567
FioFCloseFile
void FioFCloseFile(FILE *f)
Close a file in a safe way.
Definition: fileio.cpp:288