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