DatFile.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. //
  2. // Created by Иван_Архипов on 31.10.2017.
  3. //
  4. #include "DatFile.h"
  5. #include "BinaryData.h"
  6. #include "DatException.h"
  7. #include "SubDirectory.h"
  8. #include "Subfile.h"
  9. #include "SubfileData.h"
  10. #include <locale>
  11. #include <algorithm>
  12. extern "C++"
  13. {
  14. namespace LOTRO_DAT {
  15. DatFile::DatFile() {
  16. dat_state_ = CLOSED;
  17. root_directory_ = nullptr;
  18. file_handler_ = nullptr;
  19. }
  20. bool DatFile::InitDatFile(const std::string &filename, int dat_id) {
  21. try {
  22. if (dat_state_ != CLOSED && filename == filename_)
  23. return true;
  24. if (dat_state_ != CLOSED && filename != filename_)
  25. CloseDatFile();
  26. dat_id_ = dat_id;
  27. dat_state_ = CLOSED;
  28. current_locale_ = ORIGINAL;
  29. root_directory_ = nullptr;
  30. file_handler_ = nullptr;
  31. filename_ = filename;
  32. OpenDatFile(filename.c_str());
  33. ReadSuperBlock();
  34. MakeDirectories();
  35. MakeDictionary();
  36. InitLocales();
  37. if (dat_state_ == SUCCESS_DICTIONARY)
  38. dat_state_ = READY;
  39. else
  40. throw DatException("Bad DatFile initialization! Not all init states were successfully passed!",
  41. INIT_EXCEPTION);
  42. } catch (std::exception &e) {
  43. fprintf(stderr, "Bad DatFile::InitDatFile() - caught exception %s. File closed\n", e.what());
  44. CloseDatFile();
  45. return false;
  46. }
  47. return true;
  48. }
  49. DAT_STATE DatFile::DatFileState() const {
  50. return dat_state_;
  51. }
  52. DatFile::~DatFile() {
  53. CloseDatFile();
  54. }
  55. /// Extracts file with file_id.
  56. /// If path is undefined then it will be recognised as current working directory
  57. /// Output file path consists of "path + file_id + file_extension";
  58. /// NOTICE: The directory, mentioned in "std::string path" variable SHOULD BE ALREADY CREATED;
  59. /// Otherwise DatException() will be thrown.
  60. /// Returns true, if file was successfully extracted;
  61. /// Throws DatException() if undefined behaviour happened
  62. bool DatFile::ExtractFile(long long file_id, const std::string &path) {
  63. if (dat_state_ < READY) {
  64. throw DatException("Bad DatFile::ExtractFile() - invalid DatFile state!", EXPORT_EXCEPTION);
  65. }
  66. BinaryData file_data;
  67. try {
  68. file_data = GetFileData(dictionary_[file_id], 8);
  69. } catch (std::exception &e) {
  70. fprintf(stderr, "Caught %s exception.", e.what());
  71. fprintf(stderr, "Unable to extract file due to uncaught exception while getting file data. Passing...\n");
  72. return false;
  73. }
  74. try {
  75. SubfileData export_data = dictionary_[file_id]->PrepareForExport(file_data);
  76. export_data.binary_data.WriteToFile(path + export_data.options["ext"].as<std::string>());
  77. } catch (std::exception &e) {
  78. fprintf(stderr, "Caught %s exception.", e.what());
  79. fprintf(stderr, "Unable to extract file due to uncaught exception while preparing file for export. Passing...\n");
  80. return false;
  81. }
  82. return true;
  83. }
  84. /// Extracts file with file_id to database "db".
  85. /// DATABASE SHOULD BE ALREADY CREATED; Otherwise DatException will be called.
  86. /// NOTICE: The directory, mentioned in "std::string path" variable SHOULD BE ALREADY CREATED;
  87. /// Otherwise DatException() will be thrown.
  88. /// Returns true, if file was successfully extracted;
  89. /// Throws DatException() if undefined behaviour happened
  90. bool DatFile::ExtractFile(long long file_id, Database *db) {
  91. if (dat_state_ < READY) {
  92. throw DatException("Bad DatFile::ExtractFile() - invalid DatFile state!", EXPORT_EXCEPTION);
  93. }
  94. BinaryData file_data;
  95. try {
  96. file_data = GetFileData(dictionary_[file_id], 8);
  97. } catch (std::exception &e) {
  98. fprintf(stderr, "Caught %s exception.", e.what());
  99. fprintf(stderr, "Unable to extract file due to uncaught exception while getting file data. Passing...\n");
  100. return false;
  101. }
  102. SubfileData export_data;
  103. try {
  104. export_data = dictionary_[file_id]->PrepareForExport(file_data);
  105. export_data.options["did"] = dat_id_;
  106. } catch (std::exception &e) {
  107. fprintf(stderr, "Caught %s exception.", e.what());
  108. fprintf(stderr, "Unable to extract file due to uncaught exception while preparing file for export. Passing...\n");
  109. return false;
  110. }
  111. if (export_data == SubfileData()) {
  112. fprintf(stderr, "WARNING: file with id %lld is empty. Passing it\n", dictionary_[file_id]->file_id());
  113. return true;
  114. }
  115. try {
  116. db->PushFile(export_data);
  117. } catch (std::exception &e) {
  118. fprintf(stderr, "Caught %s exception.", e.what());
  119. printf("Caught %s exception.", e.what());
  120. fflush(stdout);
  121. fprintf(stderr, "Unable to put file or it's part to database. Continuing without this part. Database may be not complete\n");
  122. }
  123. return true;
  124. }
  125. /// Extracts all files with specific type to "path + type + file_id + file_part + extension" files;
  126. /// If path is undefined then it will be recognised as current working directory
  127. /// NOTICE: The directory, mentioned in "std::string path" variable SHOULD BE ALREADY CREATED;
  128. /// Otherwise DatException() will be thrown.
  129. /// Returns number of successfully extracted files
  130. /// Throws DatException() if undefined behaviour happened
  131. int DatFile::ExtractAllFilesByType(FILE_TYPE type, std::string path) {
  132. if (dat_state_ < READY) {
  133. throw DatException("Bad DatFile::ExtractAllFilesByType() - invalid DatFile state!", EXPORT_EXCEPTION);
  134. }
  135. int success = 0;
  136. for (auto i : dictionary_) {
  137. FILE_TYPE file_type = i.second->FileType();
  138. if (file_type == type) {
  139. success += ExtractFile(i.second->file_id(), (path + std::to_string(i.second->file_id())));
  140. }
  141. }
  142. return success;
  143. }
  144. /// Extracts all files with specific type to database "db";
  145. /// DATABASE SHOULD BE ALREADY CREATED; Otherwise DatException will be called.
  146. /// Returns number of successfully extracted files
  147. /// Throws DatException() if undefined behaviour happened
  148. int DatFile::ExtractAllFilesByType(FILE_TYPE type, Database *db) {
  149. if (dat_state_ < READY) {
  150. throw DatException("Bad DatFile::ExtractAllFilesByType() - invalid DatFile state!", EXPORT_EXCEPTION);
  151. }
  152. int success = 0;
  153. for (auto i : dictionary_) {
  154. FILE_TYPE file_type = i.second->FileType();
  155. if (file_type == type) {
  156. success += ExtractFile(i.second->file_id(), db);
  157. }
  158. }
  159. return success;
  160. }
  161. // TODO: Write description and make asserts
  162. bool DatFile::PatchFile(const char *filename, YAML::Node options) {
  163. if (dat_state_ < READY) {
  164. throw DatException("Bad DatFile::PatchFile() - invalid DatFile state!", EXPORT_EXCEPTION);
  165. }
  166. if (options["did"].IsDefined() && options["did"].as<int>() != dat_id_)
  167. return false;
  168. BinaryData data;
  169. data.ReadFromFile(filename);
  170. auto file_id = options["fid"].as<long long>();
  171. if (dictionary_[file_id] == nullptr) {
  172. fprintf(stderr, "ERROR DatFile::PatchFile() - Cannot patch file - there is no file in dictionary with file_id = %lld.\n", file_id);
  173. return false;
  174. }
  175. BinaryData old_data = GetFileData(dictionary_[file_id]);
  176. data = dictionary_[file_id]->MakeForImport(old_data, SubfileData(data, u"", options));
  177. try {
  178. ApplyFilePatch(dictionary_[file_id], data);
  179. } catch (std::exception &e) {
  180. fprintf(stderr, "Caught %s exception.", e.what());
  181. fprintf(stderr,
  182. "Some errors happened while patching file with id = %lld. Continuing process without this file..\n"
  183. "WARNING: DAT FILE CAN BE CORRUPTED!\n", file_id);
  184. printf("Some errors happened while patching file with id = %lld. Continuing process without this file..\n"
  185. "WARNING: DAT FILE CAN BE CORRUPTED!\n", file_id);
  186. fflush(stdout);
  187. return false;
  188. }
  189. return true;
  190. }
  191. // TODO: Write description and make asserts
  192. bool DatFile::PatchFile(const SubfileData &data, bool rewrite_original) {
  193. if (dat_state_ < READY) {
  194. throw DatException("Bad DatFile::PatchFile() - invalid DatFile state!", EXPORT_EXCEPTION);
  195. }
  196. auto file_id = data.options["fid"].as<long long>();
  197. Subfile *file = dictionary_[file_id];
  198. if (file == nullptr) {
  199. fprintf(stderr, "ERROR DatFile::PatchFile() - Cannot patch file - there is no file in dictionary with file_id = %lld.\n", file_id);
  200. return false;
  201. }
  202. // If file has inactive category, then we should set it to patched state in order to commit patch and
  203. // then in ApplyFilePatch(), if new category is still inactive, return dictionary to its original state;
  204. if (inactive_categories.count(file->category) != 0 && patch_dict_.count(file_id) != 0) {
  205. dictionary_[file_id]->file_offset_ = patch_dict_[file_id]->file_offset_;
  206. dictionary_[file_id]->file_size_ = patch_dict_[file_id]->file_size_;
  207. dictionary_[file_id]->block_size_ = patch_dict_[file_id]->block_size_;
  208. dictionary_[file_id]->timestamp_ = patch_dict_[file_id]->timestamp_;
  209. dictionary_[file_id]->version_ = patch_dict_[file_id]->version_;
  210. }
  211. if (data.options["cat"].IsDefined()) {
  212. file->category = data.options["cat"].as<long long>();
  213. } else {
  214. fprintf(stderr, "WARNING DatFile::PatchFile() - category option 'cat' was not "
  215. "set in patch subfile with id = %lld. Setting it to 1\n", file_id);
  216. file->category = 1;
  217. }
  218. BinaryData old_data = GetFileData(file);
  219. BinaryData patch_data = file->MakeForImport(old_data, data);
  220. ApplyFilePatch(file, patch_data, rewrite_original);
  221. return true;
  222. }
  223. // TODO: Write description
  224. bool DatFile::PatchAllDatabase(Database *db) {
  225. if (dat_state_ < READY) {
  226. throw DatException("Bad DatFile::PatchAllDatabase() - invalid DatFile state!", EXPORT_EXCEPTION);
  227. }
  228. SubfileData data;
  229. try {
  230. data = db->GetNextFile();
  231. } catch (std::exception &e) {
  232. fprintf(stderr, "Caught %s exception.\n", e.what());
  233. fprintf(stderr, "DatFile::PatchAllDatabase() error! Caught exception while fetching file from database! Stopping...\n");
  234. return false;
  235. }
  236. while (data != SubfileData()) {
  237. try {
  238. PatchFile(data);
  239. } catch (std::exception &e) {
  240. fprintf(stderr, "Caught %s exception.\n", e.what());
  241. fprintf(stderr, "DatFile::PatchAllDatabase() error! Caught exception while patching file! Passing...\n");
  242. }
  243. try {
  244. data = db->GetNextFile();
  245. } catch (std::exception &e) {
  246. fprintf(stderr, "Caught %s exception.\n", e.what());
  247. fprintf(stderr, "DatFile::PatchAllDatabase() error! Caught exception while fetching file from database! Stopping...\n");
  248. return false;
  249. }
  250. }
  251. CommitChanges();
  252. return true;
  253. }
  254. /// DatFile::WriteUnorderedDictionary(...);
  255. /// Prints list of all found files with some information about them to file.
  256. /// Gets std::string path - path to directory, where the file will be written with name "dict.txt"
  257. void DatFile::WriteUnorderedDictionary(std::string path) const {
  258. FILE *f;
  259. fopen_s(&f, (path + "dict.txt").c_str(), "w");
  260. fprintf(f, "file_id offset size size2 extension\n");
  261. for (auto i : dictionary_) {
  262. fprintf(f, "%lld %lld %lld %lld %s\n", i.second->file_id(), i.second->file_offset(), i.second->file_size(),
  263. i.second->block_size(), i.second->Extension().c_str());
  264. }
  265. fclose(f);
  266. }
  267. /// DatFile::files_number();
  268. /// Returns amount of files, found in dictionaries of DatFile. Some if them may be empty or erased.
  269. long long DatFile::files_number() const {
  270. return dictionary_.size();
  271. }
  272. /// DatFile::GetFileData()
  273. /// Returns BinaryData, which contains of subfile data, made from parts of file in DatFile
  274. BinaryData DatFile::GetFileData(const Subfile *file, long long int offset) {
  275. BinaryData mfile_id(4);
  276. ReadData(mfile_id, 4, file->file_offset() + 8);
  277. if (file->file_id() != mfile_id.ToNumber<4>(0))
  278. throw DatException("Bad DatFile::GetFileData() - file_id in Subfile doesn't match to file_id in DatFile.", READ_EXCEPTION);
  279. BinaryData data((unsigned)(file->file_size() + (8 - offset)));
  280. if (file->block_size() >= file->file_size() + 8) {
  281. ReadData(data, file->file_size() + (8 - offset), file->file_offset() + offset);
  282. return data;
  283. }
  284. BinaryData fragments_count(4);
  285. ReadData(fragments_count, 4, file->file_offset());
  286. long long fragments_number = fragments_count.ToNumber<4>(0);
  287. long long current_block_size = file->block_size() - offset - 8 * fragments_number;
  288. ReadData(data, current_block_size , file->file_offset() + offset);
  289. BinaryData FragmentsDictionary(8 * unsigned(fragments_number));
  290. ReadData(FragmentsDictionary, 8 * unsigned(fragments_number), file->file_offset() + file->block_size() - 8 * fragments_number);
  291. for (long long i = 0; i < fragments_number; i++) {
  292. long long fragment_size = FragmentsDictionary.ToNumber<4>(8 * i);
  293. long long fragment_offset = FragmentsDictionary.ToNumber<4>(8 * i + 4);
  294. ReadData(data, std::min(fragment_size, file->file_size() - current_block_size), fragment_offset, current_block_size );
  295. current_block_size += fragment_size;
  296. }
  297. return data;
  298. }
  299. /// DatFile special functions for opening and reading/writing raw data.
  300. /// Shouldn't be used by any external classes except Subfile and Subdirectory.
  301. void DatFile::OpenDatFile(const char *dat_name) {
  302. if (dat_state_ != CLOSED)
  303. throw DatException("Bad initialisation of DatFile - current DatFile isn't in correct state!",
  304. INIT_EXCEPTION);
  305. fopen_s(&file_handler_, dat_name, "r+b");
  306. if (file_handler_ == nullptr) {
  307. std::string err = "Bad DatFile::OpenDatFile. Unable to open file ";
  308. err += dat_name;
  309. throw DatException(err.c_str(), NOFILE_EXCEPTION);
  310. }
  311. fseek(file_handler_, 0, SEEK_END);
  312. file_size_ = ftell(file_handler_);
  313. fseek(file_handler_, 0, SEEK_SET);
  314. dat_state_ = SUCCESS_OPENED;
  315. }
  316. void DatFile::ReadSuperBlock() {
  317. if (dat_state_ != SUCCESS_OPENED)
  318. throw DatException("Bad DatFile::ReadSuperBlock() - DatFile isn't in valid state!", INIT_EXCEPTION);
  319. BinaryData data(1024);
  320. ReadData(data, 1024);
  321. constant1_ = data.ToNumber<4>(0x100);
  322. constant2_ = data.ToNumber<4>(0x140);
  323. version1_ = data.ToNumber<4>(0x14C);
  324. version2_ = data.ToNumber<4>(0x150);
  325. fragmentation_journal_offset_ = data.ToNumber<4>(0x154);
  326. root_directory_offset_ = data.ToNumber<4>(0x160);
  327. auto size1 = data.ToNumber<4>(0x148);
  328. if (constant1_ != 0x4C5000)
  329. throw DatException(
  330. "Bad DatFile::ReadSuperBlock - variable at position 0x100 is not equal to .dat file constant!",
  331. INIT_EXCEPTION);
  332. if (constant2_ != 0x5442)
  333. throw DatException(
  334. "Bad DatFile::ReadSuperBlock - variable at position 0x140 is not equal to .dat file constant!",
  335. INIT_EXCEPTION);
  336. if (file_size_ != size1)
  337. throw DatException(
  338. "Bad DatFile::ReadSuperBlock - variable at 0x148 position is not equal to .dat file size!",
  339. INIT_EXCEPTION);
  340. dat_state_ = SUCCESS_SUPERBLOCK;
  341. }
  342. void DatFile::MakeDirectories() {
  343. if (dat_state_ != SUCCESS_SUPERBLOCK)
  344. throw DatException("Bad DatFile::MakeDirectories() - DatFile isn't in valid state!", INIT_EXCEPTION);
  345. root_directory_ = new SubDirectory((unsigned) root_directory_offset_, this);
  346. dat_state_ = SUCCESS_DIRECTORIES;
  347. }
  348. void DatFile::MakeDictionary() {
  349. if (dat_state_ != SUCCESS_DIRECTORIES)
  350. throw DatException("Bad DatFile::MakeDictionary() - DatFile isn't in valid state!", INIT_EXCEPTION);
  351. try {
  352. if (root_directory_ == nullptr)
  353. throw DatException("Bad DatFile::MakeDictionary() - root_directory is nullptr!", INIT_EXCEPTION);
  354. root_directory_->MakeDictionary(dictionary_);
  355. } catch (std::exception &e) {
  356. fprintf(stderr, "Caught %s exception.", e.what());
  357. fprintf(stderr, "Bad DatFile::MakeDictionary() - File is corrupted?\n");
  358. return;
  359. }
  360. dat_state_ = SUCCESS_DICTIONARY;
  361. }
  362. void DatFile::ReadData(BinaryData &data, long long size, long long offset, long long data_offset) {
  363. if (dat_state_ == CLOSED)
  364. throw DatException("Bad DatFile::ReadData() - DatFile isn't in valid state!", READ_EXCEPTION);
  365. if (data_offset + size > data.size()) {
  366. std::string err = "Bad DatFile::ReadData - trying to read more than BinaryData size\n";
  367. err += std::string("Reading ") + std::to_string(size) + std::string(" bytes from ")
  368. + std::to_string(offset) + std::string(" position in dat file.");
  369. throw DatException(err.c_str(), READ_EXCEPTION);
  370. }
  371. if (offset + size > file_size_) {
  372. std::string err = "Bad DatFile::ReadData - trying to read more than DatFile size elapsed\n";
  373. err += std::string("Reading ") + std::to_string(size) + std::string(" bytes from ")
  374. + std::to_string(offset) + std::string(" position in dat file.");
  375. throw DatException(err.c_str(), READ_EXCEPTION);
  376. }
  377. _fseeki64(file_handler_, offset, SEEK_SET);
  378. fread(data.data() + data_offset, unsigned(size), 1, file_handler_);
  379. data.CheckCompression();
  380. }
  381. void DatFile::WriteData(const BinaryData &data, long long size, long long offset, long long data_offset) {
  382. if (dat_state_ < READY)
  383. throw DatException("Bad DatFile::WriteData() - DatFile isn't in valid state!", WRITE_EXCEPTION);
  384. _fseeki64(file_handler_, offset, SEEK_SET);
  385. if (data_offset + size > data.size())
  386. throw DatException("Bad DatFile::WriteData - trying to write more than BinaryData size", WRITE_EXCEPTION);
  387. fwrite(data.data() + data_offset, unsigned(size), 1, file_handler_);
  388. }
  389. /// Special functions used by patch process.
  390. /// Shouldn't be used by any external class.
  391. void DatFile::ApplyFilePatch(Subfile *file, const BinaryData &data, bool rewrite_original) {
  392. auto file_id = file->file_id();
  393. if (patched_list.count(file_id) != 0) {
  394. fprintf(stderr, "Warning: DatFile::ApplyFilePatch - found 2 files in patch with the same file_id = %lld. Passing last...\n", file->file_id());
  395. return;
  396. }
  397. if (current_locale() != PATCHED && !rewrite_original) {
  398. std::cout << "Changing locale to RU in order to patch file" << std::endl;
  399. SetLocale(PATCHED);
  400. }
  401. dat_state_ = UPDATED;
  402. if (orig_dict_.count(file_id) == 0 && !rewrite_original) {
  403. orig_dict_[file_id] = new Subfile(this, file->MakeHeaderData());
  404. }
  405. auto journal = GetFragmentationJournal();
  406. if (journal[0].second != file_size_) {
  407. journal[0].second = file_size_;
  408. }
  409. file->file_size_ = data.size() - 8;
  410. if ((patch_dict_.count(file_id) == 0 && !rewrite_original) || data.size() > file->block_size()) {
  411. file->file_offset_ = journal[0].second;
  412. file->block_size_ = std::max(data.size(), 256u);
  413. journal[0].second += data.size();
  414. BinaryData nulls(data.size());
  415. WriteData(nulls, nulls.size(), file_size_);
  416. this->file_size_ += data.size();
  417. }
  418. BinaryData fragments_count(4);
  419. fragments_count = BinaryData::FromNumber<4>(0);
  420. BinaryData file_data = fragments_count + data.CutData(4);
  421. if (file_id != file_data.ToNumber<4>(8))
  422. throw DatException("Bad DatFile::ApplyFilePatch() - Created data's file_id doesn't match to original! "
  423. "Patch wasn't written to .dat file");
  424. WriteData(file_data, file_data.size(), file->file_offset());
  425. patched_list.insert(file_id);
  426. if (!rewrite_original) {
  427. patch_dict_.erase(file_id); // Удалили старое значение в русском словаре
  428. patch_dict_[file_id] = new Subfile(this, file->MakeHeaderData()); // Создали новое значение
  429. }
  430. // If category is forbidden, then return file header data to original state
  431. if (inactive_categories.count(file->category) != 0) {
  432. dictionary_[file_id]->file_offset_ = orig_dict_[file_id]->file_offset_;
  433. dictionary_[file_id]->file_size_ = orig_dict_[file_id]->file_size_;
  434. dictionary_[file_id]->block_size_ = orig_dict_[file_id]->block_size_;
  435. dictionary_[file_id]->timestamp_ = orig_dict_[file_id]->timestamp_;
  436. dictionary_[file_id]->version_ = orig_dict_[file_id]->version_;
  437. }
  438. if (orig_dict_.count(file_id) != 0)
  439. orig_dict_[file_id]->category = file->category;
  440. if (patch_dict_.count(file_id) != 0)
  441. patch_dict_[file_id]->category = file->category;
  442. UpdateFragmentationJournal(journal);
  443. }
  444. void DatFile::UpdateSubdirectories() {
  445. root_directory_->UpdateDirectories(patched_list, dictionary_);
  446. }
  447. std::vector<std::pair<long long, long long> > DatFile::GetFragmentationJournal() {
  448. BinaryData data(8);
  449. ReadData(data, 8, fragmentation_journal_offset_ + 8);
  450. std::vector<std::pair<long long, long long> > result;
  451. result.emplace_back(std::make_pair(data.ToNumber<4>(0), data.ToNumber<4>(4)));
  452. return result;
  453. }
  454. void DatFile::UpdateHeader() {
  455. WriteData(BinaryData::FromNumber<4>(constant1_), 4, 0x100);
  456. WriteData(BinaryData::FromNumber<4>(constant2_), 4, 0x140);
  457. WriteData(BinaryData::FromNumber<4>(file_size_), 4, 0x148);
  458. WriteData(BinaryData::FromNumber<4>(version1_), 4, 0x14C);
  459. WriteData(BinaryData::FromNumber<4>(version2_), 4, 0x150);
  460. WriteData(BinaryData::FromNumber<4>(fragmentation_journal_offset_), 4, 0x154);
  461. WriteData(BinaryData::FromNumber<4>(root_directory_offset_), 4, 0x160);
  462. }
  463. void DatFile::UpdateFragmentationJournal(const std::vector<std::pair<long long, long long> > &journal) {
  464. for (unsigned i = 0; i < journal.size(); i++) {
  465. long long size = journal[i].first;
  466. long long offset = journal[i].second;
  467. WriteData(BinaryData::FromNumber<4>(size), 4, fragmentation_journal_offset_ + 8 * (i + 1));
  468. WriteData(BinaryData::FromNumber<4>(offset), 4, fragmentation_journal_offset_ + 8 * (i + 1) + 4);
  469. }
  470. }
  471. bool DatFile::CommitChanges() {
  472. try {
  473. if (dat_state_ != UPDATED)
  474. return true;
  475. std::cout << "There are some updated files. Rewriting dictionary..." << std::endl << std::flush;
  476. std::cout << "Updating locales..." << std::endl;
  477. CommitLocales();
  478. auto journal = GetFragmentationJournal();
  479. if (!patched_list.empty()) {
  480. journal[0].second = file_size_;
  481. BinaryData nulls(size_t(journal[0].first));
  482. WriteData(nulls, nulls.size(), file_size_);
  483. file_size_ += journal[0].first;
  484. }
  485. UpdateFragmentationJournal(journal);
  486. std::cout << "Updated fragmentation journal..." << std::endl << std::flush;
  487. UpdateHeader();
  488. std::cout << "Updated header..." << std::endl << std::flush;
  489. UpdateSubdirectories();
  490. std::cout << "Updated subdirectories..." << std::endl << std::flush;
  491. std::cout << "Changed " << patched_list.size() << " files..." << std::endl << std::flush;
  492. std::cout << "Done!" << std::endl;
  493. patched_list.clear();
  494. dat_state_ = READY;
  495. return true;
  496. } catch (std::exception &e) {
  497. fprintf(stderr, "Bad DatFile::CommitChanges - caught exception %s\n", e.what());
  498. return false;
  499. }
  500. }
  501. bool DatFile::CloseDatFile() {
  502. if (dat_state_ == CLOSED) {
  503. fprintf(stderr, "DatFile::CloseDatFile() - dat state is already closed. Nothing to do\n");
  504. return true;
  505. }
  506. try {
  507. if (dat_state_ == UPDATED) {
  508. CommitChanges();
  509. }
  510. orig_dict_.clear();
  511. patched_list.clear();
  512. pending_patch_.clear();
  513. current_locale_ = ORIGINAL;
  514. filename_.clear();
  515. if (file_handler_ != nullptr)
  516. fclose(file_handler_);
  517. delete file_handler_;
  518. delete root_directory_;
  519. patched_list.clear();
  520. dictionary_.clear();
  521. dat_state_ = CLOSED;
  522. } catch (std::exception &e) {
  523. fprintf(stderr, "Bad DatFile::CloseDatFile() - caught exception %s\n", e.what());
  524. return false;
  525. }
  526. return true;
  527. }
  528. // LOCALE MANAGING SECTION
  529. void DatFile::InitLocales() {
  530. std::cout << "Initialising locales..." << std::endl;
  531. BinaryData dicts_data = GetFileData(dictionary_[2013266257]);
  532. if (dicts_data.size() < 29) {
  533. fprintf(stderr, "WARNING: DatFile::InitLocales() - locales file is empty.. Initialising locale dicts as empty\n");
  534. std::cout << "Could't find locales file... Continuing without them" << std::endl;;
  535. return;
  536. }
  537. BinaryData hi_data = dicts_data.CutData(14, 29) + BinaryData("\0", 1);
  538. std::string hi = std::string((char*)(hi_data.data()));
  539. std::cout << hi << std::endl;
  540. if (hi != "Hi from Gi1dor!") {
  541. fprintf(stderr, "WARNING: DatFile::InitLocales() - Didn't receive 'hi' from Gi1dor... Initialising locale dicts as empty\n");
  542. std::cout << "Could't init locales' file... Continuing without them" << std::endl;
  543. return;
  544. }
  545. int offset = 29;
  546. BinaryData current_locale_data = dicts_data.CutData(offset, offset + 4) + BinaryData("\0", 1);
  547. std::string locale((char*)(current_locale_data.data()));
  548. offset += 4;
  549. std::cout << locale << std::endl;
  550. if (locale != "PATC" && locale != "ORIG") {
  551. fprintf(stderr, "WARNING: DatFile::InitLocales() - Incorrect locale... Initialising locale dicts as empty\n");
  552. std::cout << "Could't recognize locale... Continuing without locales" << std::endl;;
  553. return;
  554. }
  555. current_locale_ = (locale == "PATC" ? PATCHED : ORIGINAL);
  556. // 14 bytes for old data
  557. // 15 bytes for "Hi from Gi1dor"
  558. // 4 bytes for LOCALE
  559. // 4 bytes for orig_dict.size()
  560. // (32 + 4) * orig_dict.size() bytes for orig_dict data
  561. // 4 bytes for patch_dict.size()
  562. // (32 + 4) * patch_dict.size() bytes for patch_dict data
  563. // 4 bytes for inactive_categories dict
  564. // 4 * inactive_categories.size() bytes for inactive_categories data
  565. size_t orig_dict_size = size_t(dicts_data.CutData(offset, offset + 4).ToNumber<4>(0));
  566. offset += 4;
  567. for (size_t i = 0; i < orig_dict_size; i++) {
  568. auto file = new Subfile(this, dicts_data.CutData(offset, offset + 32));
  569. orig_dict_[file->file_id()] = file;
  570. offset += 32;
  571. orig_dict_[file->file_id()]->category = dicts_data.ToNumber<4>(offset);
  572. offset += 4;
  573. if (orig_dict_[file->file_id()]->category == 0)
  574. fprintf(stderr, "WARNING DatFile::InitLocales() - file category is undefined (0)!\n");
  575. }
  576. size_t patch_dict_size = size_t(dicts_data.CutData(offset, offset + 4).ToNumber<4>(0));
  577. offset += 4;
  578. for (size_t i = 0; i < patch_dict_size; i++) {
  579. auto file = new Subfile(this, dicts_data.CutData(offset, offset + 32));
  580. patch_dict_[file->file_id()] = file;
  581. offset += 32;
  582. patch_dict_[file->file_id()]->category = dicts_data.ToNumber<4>(offset);
  583. offset += 4;
  584. if (patch_dict_[file->file_id()]->category == 0)
  585. fprintf(stderr, "WARNING DatFile::InitLocales() - file category is undefined (0)!\n");
  586. }
  587. size_t active_patches_dict_size = size_t(dicts_data.CutData(offset, offset + 4).ToNumber<4>(0));
  588. offset += 4;
  589. for (size_t i = 0; i < active_patches_dict_size; i++) {
  590. inactive_categories.insert(dicts_data.ToNumber<4>(offset));
  591. offset += 4;
  592. }
  593. std::cout << "There are " << patch_dict_.size() << " files in patch locale dictionary" << std::endl;
  594. std::cout << "There are " << orig_dict_.size() << " files in original locale dictionary" << std::endl;
  595. std::cout << "Unactive patches now: ";
  596. for (auto i : inactive_categories)
  597. std:: cout << i;
  598. std::cout << std::endl;
  599. }
  600. std::unordered_map<long long, Subfile *> *DatFile::GetLocaleDictReference(LOCALE locale) {
  601. switch (locale) {
  602. case PATCHED:
  603. return &patch_dict_;
  604. case ORIGINAL:
  605. return &orig_dict_;
  606. default:
  607. throw DatException("Bad DatFile::GetLocaleDictReference() - unknown locale!!!", LOCALE_EXCEPTION);
  608. }
  609. }
  610. void DatFile::SetLocale(LOCALE locale) {
  611. try {
  612. if (dat_state_ < READY) {
  613. fprintf(stderr, "Bad DatFile::SetLocale() - DatFile is in incorrect state... Cannot set locale\n");
  614. return;
  615. }
  616. if (current_locale_ == locale) {
  617. return;
  618. }
  619. dat_state_ = UPDATED;
  620. auto dict = GetLocaleDictReference(locale);
  621. for (auto file : *dict) {
  622. if (dictionary_[file.first] == nullptr) {
  623. fprintf(stderr,
  624. "WARNING: In locale dictionary there is file with file_id = %lld, which is not in .dat "
  625. "file! Passing it and removing from locale dictionary\n", file.first);
  626. dict->erase(file.first);
  627. continue;
  628. }
  629. if (dictionary_[file.first]->MakeHeaderData().CutData(8, 16) ==
  630. file.second->MakeHeaderData().CutData(8, 16) || inactive_categories.count(orig_dict_[file.first]->category) != 0)
  631. continue;
  632. long long file_id = file.first;
  633. Subfile *new_file = file.second;
  634. dictionary_[file_id]->file_offset_ = new_file->file_offset_;
  635. dictionary_[file_id]->file_size_ = new_file->file_size_;
  636. dictionary_[file_id]->block_size_ = new_file->block_size_;
  637. dictionary_[file_id]->timestamp_ = new_file->timestamp_;
  638. dictionary_[file_id]->version_ = new_file->version_;
  639. patched_list.insert(file.first);
  640. dat_state_ = UPDATED;
  641. }
  642. current_locale_ = locale;
  643. CommitChanges();
  644. } catch (std::exception &e) {
  645. fprintf(stderr, "Bad DatFile::SetLocale() - caught exception %s. Locale wasn't set.\n", e.what());
  646. return;
  647. }
  648. }
  649. bool DatFile::CheckIfUpdatedByGame() {
  650. return false;
  651. }
  652. void DatFile::RepairPatches(Database *db) {
  653. }
  654. LOCALE DatFile::current_locale() {
  655. if (dat_state_ < READY) {
  656. fprintf(stderr, "Bad DatFile::current_locale() - dat_file is in incorrect state!\n");
  657. return ORIGINAL;
  658. }
  659. if (current_locale_ != PATCHED && current_locale_ != ORIGINAL) {
  660. fprintf(stderr, "Bad DatFile::current_locale() - locale has incorrect value. Setting it to original\n");
  661. current_locale_ = ORIGINAL;
  662. }
  663. return current_locale_;
  664. }
  665. void DatFile::CommitLocales() {
  666. std::cout << "Committing locales..." << std::endl;
  667. SubfileData data = dictionary_[2013266257]->PrepareForExport(GetFileData(dictionary_[2013266257]));
  668. data.options["fid"] = "2013266257";
  669. data.options["ext"] = ".unknown";
  670. BinaryData old_data = BinaryData(GetFileData(dictionary_[2013266257u]));
  671. // 14 bytes for old data
  672. // 15 bytes for "Hi from Gi1dor"
  673. // 4 bytes for LOCALE
  674. // 4 bytes for orig_dict.size()
  675. // (32 + 4) * orig_dict.size() bytes for orig_dict data
  676. // 4 bytes for patch_dict.size()
  677. // (32 + 4) * patch_dict.size() bytes for patch_dict data
  678. // 4 bytes for inactive_categories list
  679. // 4 * inactive_categories.size() bytes for inactive_categories data
  680. data.binary_data = BinaryData(14 + 15 + 4
  681. + 4 + (32 + 4) * orig_dict_.size()
  682. + 4 + (32 + 4) * patch_dict_.size()
  683. + 4 + 4 * inactive_categories.size());
  684. size_t current_size = 0;
  685. data.binary_data.Append(GetFileData(dictionary_[2013266257u]).CutData(0, 14), current_size);
  686. current_size += 14;
  687. data.binary_data.Append(BinaryData("Hi from Gi1dor!", 15), current_size);
  688. current_size += 15;
  689. data.binary_data.Append(BinaryData((current_locale_ == ORIGINAL ? "ORIG" : "PATC"), 4), current_size);
  690. current_size += 4;
  691. data.binary_data.Append(BinaryData::FromNumber<4>(orig_dict_.size()), current_size);
  692. current_size += 4;
  693. for (auto file : orig_dict_) {
  694. data.binary_data.Append(file.second->MakeHeaderData(), current_size);
  695. current_size += 32;
  696. data.binary_data.Append(BinaryData::FromNumber<4>(file.second->category), current_size);
  697. current_size += 4;
  698. }
  699. data.binary_data.Append(BinaryData::FromNumber<4>(patch_dict_.size()), current_size);
  700. current_size += 4;
  701. for (auto file : patch_dict_) {
  702. data.binary_data.Append(file.second->MakeHeaderData(), current_size);
  703. current_size += 32;
  704. data.binary_data.Append(BinaryData::FromNumber<4>(file.second->category), current_size);
  705. current_size += 4;
  706. }
  707. data.binary_data.Append(BinaryData::FromNumber<4>(inactive_categories.size()), current_size);
  708. current_size += 4;
  709. for (auto patch_id : inactive_categories) {
  710. data.binary_data.Append(BinaryData::FromNumber<4>(patch_id), current_size);
  711. current_size += 4;
  712. }
  713. PatchFile(data, true);
  714. std::cout << "Done!" << std::endl;
  715. }
  716. void DatFile::EnableCategory(int category) {
  717. std::cout << "Disabling category " << category << std::endl;
  718. if (inactive_categories.count(category) == 0)
  719. return;
  720. inactive_categories.erase(category);
  721. for (auto file : dictionary_) {
  722. auto file_id = file.first;
  723. if (patch_dict_.count(file_id) > 0 && patch_dict_[file_id]->category == category) {
  724. dat_state_ = UPDATED;
  725. file.second->file_offset_ = patch_dict_[file_id]->file_offset_;
  726. file.second->file_size_ = patch_dict_[file_id]->file_size_;
  727. file.second->block_size_ = patch_dict_[file_id]->block_size_;
  728. file.second->timestamp_ = patch_dict_[file_id]->timestamp_;
  729. file.second->version_ = patch_dict_[file_id]->version_;
  730. patched_list.insert(file_id);
  731. }
  732. }
  733. }
  734. void DatFile::DisableCategory(int category) {
  735. std::cout << "Disabling category " << category << std::endl;
  736. if (inactive_categories.count(category) != 0)
  737. return;
  738. inactive_categories.insert(category);
  739. for (auto file : dictionary_) {
  740. auto file_id = file.first;
  741. if (orig_dict_.count(file_id) && orig_dict_[file_id]->category == category) {
  742. dat_state_ = UPDATED;
  743. file.second->file_offset_ = orig_dict_[file_id]->file_offset_;
  744. file.second->file_size_ = orig_dict_[file_id]->file_size_;
  745. file.second->block_size_ = orig_dict_[file_id]->block_size_;
  746. file.second->timestamp_ = orig_dict_[file_id]->timestamp_;
  747. file.second->version_ = orig_dict_[file_id]->version_;
  748. patched_list.insert(file_id);
  749. }
  750. }
  751. }
  752. const std::unordered_set<long long>& DatFile::GetInactiveCategoriesList() {
  753. return inactive_categories;
  754. }
  755. }
  756. }