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/>.
8 /** @file script_scanner.cpp Allows scanning for scripts. */
10 #include "../stdafx.h"
12 #include "../string_func.h"
13 #include "../settings_type.h"
15 #include "../script/squirrel.hpp"
16 #include "script_scanner.hpp"
17 #include "script_info.hpp"
18 #include "script_fatalerror.hpp"
20 #include "../network/network_content.h"
21 #include "../3rdparty/md5/md5.h"
22 #include "../tar_type.h"
24 #include "../safeguards.h"
26 bool ScriptScanner::AddFile(const std::string
&filename
, size_t, const std::string
&tar_filename
)
28 this->main_script
= filename
;
29 this->tar_file
= tar_filename
;
31 auto p
= this->main_script
.find_last_of(PATHSEPCHAR
);
32 this->main_script
.erase(p
!= std::string::npos
? p
+ 1 : 0);
33 this->main_script
+= "main.nut";
35 if (!FioCheckFileExists(filename
, this->subdir
) || !FioCheckFileExists(this->main_script
, this->subdir
)) return false;
39 this->engine
->LoadScript(filename
);
40 } catch (Script_FatalError
&e
) {
41 Debug(script
, 0, "Fatal error '{}' when trying to load the script '{}'.", e
.GetErrorMessage(), filename
);
47 ScriptScanner::ScriptScanner() :
52 void ScriptScanner::ResetEngine()
54 this->engine
->Reset();
55 this->engine
->SetGlobalPointer(this);
56 this->RegisterAPI(this->engine
);
59 void ScriptScanner::Initialize(const char *name
)
61 this->engine
= new Squirrel(name
);
68 ScriptScanner::~ScriptScanner()
75 void ScriptScanner::RescanDir()
77 /* Forget about older scans */
80 /* Scan for scripts */
81 this->Scan(this->GetFileName(), this->GetDirectory());
84 void ScriptScanner::Reset()
86 for (const auto &item
: this->info_list
) {
90 this->info_list
.clear();
91 this->info_single_list
.clear();
94 void ScriptScanner::RegisterScript(ScriptInfo
*info
)
96 std::string script_original_name
= this->GetScriptName(info
);
97 std::string script_name
= fmt::format("{}.{}", script_original_name
, info
->GetVersion());
99 /* Check if GetShortName follows the rules */
100 if (info
->GetShortName().size() != 4) {
101 Debug(script
, 0, "The script '{}' returned a string from GetShortName() which is not four characters. Unable to load the script.", info
->GetName());
106 if (this->info_list
.find(script_name
) != this->info_list
.end()) {
107 /* This script was already registered */
109 /* Windows doesn't care about the case */
110 if (StrEqualsIgnoreCase(this->info_list
[script_name
]->GetMainScript(), info
->GetMainScript())) {
112 if (this->info_list
[script_name
]->GetMainScript() == info
->GetMainScript()) {
118 Debug(script
, 1, "Registering two scripts with the same name and version");
119 Debug(script
, 1, " 1: {}", this->info_list
[script_name
]->GetMainScript());
120 Debug(script
, 1, " 2: {}", info
->GetMainScript());
121 Debug(script
, 1, "The first is taking precedence.");
127 this->info_list
[script_name
] = info
;
129 if (!info
->IsDeveloperOnly() || _settings_client
.gui
.ai_developer_tools
) {
130 /* Add the script to the 'unique' script list, where only the highest version
131 * of the script is registered. */
132 auto it
= this->info_single_list
.find(script_original_name
);
133 if (it
== this->info_single_list
.end()) {
134 this->info_single_list
[script_original_name
] = info
;
135 } else if (it
->second
->GetVersion() < info
->GetVersion()) {
141 void ScriptScanner::GetConsoleList(std::back_insert_iterator
<std::string
> &output_iterator
, bool newest_only
) const
143 fmt::format_to(output_iterator
, "List of {}:\n", this->GetScannerName());
144 const ScriptInfoList
&list
= newest_only
? this->info_single_list
: this->info_list
;
145 for (const auto &item
: list
) {
146 ScriptInfo
*i
= item
.second
;
147 fmt::format_to(output_iterator
, "{:>10} (v{:d}): {}\n", i
->GetName(), i
->GetVersion(), i
->GetDescription());
149 fmt::format_to(output_iterator
, "\n");
152 /** Helper for creating a MD5sum of all files within of a script. */
153 struct ScriptFileChecksumCreator
: FileScanner
{
154 MD5Hash md5sum
; ///< The final md5sum.
155 Subdirectory dir
; ///< The directory to look in.
158 * Initialise the md5sum to be all zeroes,
159 * so we can easily xor the data.
161 ScriptFileChecksumCreator(Subdirectory dir
) : dir(dir
) {}
163 /* Add the file and calculate the md5 sum. */
164 bool AddFile(const std::string
&filename
, size_t, const std::string
&) override
167 uint8_t buffer
[1024];
170 /* Open the file ... */
171 FILE *f
= FioFOpenFile(filename
, "rb", this->dir
, &size
);
172 if (f
== nullptr) return false;
174 /* ... calculate md5sum... */
175 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, f
)) != 0 && size
!= 0) {
177 checksum
.Append(buffer
, len
);
181 checksum
.Finish(tmp_md5sum
);
185 /* ... and xor it to the overall md5sum. */
186 this->md5sum
^= tmp_md5sum
;
193 * Check whether the script given in info is the same as in ci based
194 * on the shortname and md5 sum.
195 * @param ci The information to compare to.
196 * @param md5sum Whether to check the MD5 checksum.
197 * @param info The script to get the shortname and md5 sum from.
198 * @return True iff they're the same.
200 static bool IsSameScript(const ContentInfo
*ci
, bool md5sum
, ScriptInfo
*info
, Subdirectory dir
)
203 const char *str
= info
->GetShortName().c_str();
204 for (int j
= 0; j
< 4 && *str
!= '\0'; j
++, str
++) id
|= *str
<< (8 * j
);
206 if (id
!= ci
->unique_id
) return false;
207 if (!md5sum
) return true;
209 ScriptFileChecksumCreator
checksum(dir
);
210 auto tar_filename
= info
->GetTarFile();
211 TarList::iterator iter
;
212 if (!tar_filename
.empty() && (iter
= _tar_list
[dir
].find(tar_filename
)) != _tar_list
[dir
].end()) {
213 /* The main script is in a tar file, so find all files that
214 * are in the same tar and add them to the MD5 checksumming. */
215 for (const auto &tar
: _tar_filelist
[dir
]) {
216 /* Not in the same tar. */
217 if (tar
.second
.tar_filename
!= iter
->first
) continue;
219 /* Check the extension. */
220 const char *ext
= strrchr(tar
.first
.c_str(), '.');
221 if (ext
== nullptr || !StrEqualsIgnoreCase(ext
, ".nut")) continue;
223 checksum
.AddFile(tar
.first
, 0, tar_filename
);
226 /* There'll always be at least 1 path separator character in a script
227 * main script name as the search algorithm requires the main script to
228 * be in a subdirectory of the script directory; so <dir>/<path>/main.nut. */
229 const std::string
&main_script
= info
->GetMainScript();
230 std::string path
= main_script
.substr(0, main_script
.find_last_of(PATHSEPCHAR
));
231 checksum
.Scan(".nut", path
);
234 return ci
->md5sum
== checksum
.md5sum
;
237 bool ScriptScanner::HasScript(const ContentInfo
*ci
, bool md5sum
)
239 for (const auto &item
: this->info_list
) {
240 if (IsSameScript(ci
, md5sum
, item
.second
, this->GetDirectory())) return true;
245 const char *ScriptScanner::FindMainScript(const ContentInfo
*ci
, bool md5sum
)
247 for (const auto &item
: this->info_list
) {
248 if (IsSameScript(ci
, md5sum
, item
.second
, this->GetDirectory())) return item
.second
->GetMainScript().c_str();