DatFile.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 (data.options["cat"].IsDefined())
  203. file->category = data.options["cat"].as<long long>();
  204. else
  205. fprintf(stderr, "WARNING DatFile::PatchFile() - category option 'cat' was not set in patch subfile with id = %lld\n", file_id);
  206. BinaryData old_data = GetFileData(file);
  207. BinaryData patch_data = file->MakeForImport(old_data, data);
  208. ApplyFilePatch(file, patch_data, rewrite_original);
  209. return true;
  210. }
  211. // TODO: Write description
  212. bool DatFile::PatchAllDatabase(Database *db) {
  213. if (dat_state_ < READY) {
  214. throw DatException("Bad DatFile::PatchAllDatabase() - invalid DatFile state!", EXPORT_EXCEPTION);
  215. }
  216. SubfileData data;
  217. try {
  218. data = db->GetNextFile();
  219. } catch (std::exception &e) {
  220. fprintf(stderr, "Caught %s exception.\n", e.what());
  221. fprintf(stderr, "DatFile::PatchAllDatabase() error! Caught exception while fetching file from database! Stopping...\n");
  222. return false;
  223. }
  224. while (data != SubfileData()) {
  225. try {
  226. PatchFile(data);
  227. } catch (std::exception &e) {
  228. fprintf(stderr, "Caught %s exception.\n", e.what());
  229. fprintf(stderr, "DatFile::PatchAllDatabase() error! Caught exception while patching file! Passing...\n");
  230. }
  231. try {
  232. data = db->GetNextFile();
  233. } catch (std::exception &e) {
  234. fprintf(stderr, "Caught %s exception.\n", e.what());
  235. fprintf(stderr, "DatFile::PatchAllDatabase() error! Caught exception while fetching file from database! Stopping...\n");
  236. return false;
  237. }
  238. }
  239. CommitChanges();
  240. return true;
  241. }
  242. /// DatFile::WriteUnorderedDictionary(...);
  243. /// Prints list of all found files with some information about them to file.
  244. /// Gets std::string path - path to directory, where the file will be written with name "dict.txt"
  245. void DatFile::WriteUnorderedDictionary(std::string path) const {
  246. FILE *f;
  247. fopen_s(&f, (path + "dict.txt").c_str(), "w");
  248. fprintf(f, "file_id offset size size2 extension\n");
  249. for (auto i : dictionary_) {
  250. fprintf(f, "%lld %lld %lld %lld %s\n", i.second->file_id(), i.second->file_offset(), i.second->file_size(),
  251. i.second->block_size(), i.second->Extension().c_str());
  252. }
  253. fclose(f);
  254. }
  255. /// DatFile::files_number();
  256. /// Returns amount of files, found in dictionaries of DatFile. Some if them may be empty or erased.
  257. long long DatFile::files_number() const {
  258. return dictionary_.size();
  259. }
  260. /// DatFile::GetFileData()
  261. /// Returns BinaryData, which contains of subfile data, made from parts of file in DatFile
  262. BinaryData DatFile::GetFileData(const Subfile *file, long long int offset) {
  263. BinaryData mfile_id(4);
  264. ReadData(mfile_id, 4, file->file_offset() + 8);
  265. if (file->file_id() != mfile_id.ToNumber<4>(0))
  266. throw DatException("Bad DatFile::GetFileData() - file_id in Subfile doesn't match to file_id in DatFile.", READ_EXCEPTION);
  267. BinaryData data((unsigned)(file->file_size() + (8 - offset)));
  268. if (file->block_size() >= file->file_size() + 8) {
  269. ReadData(data, file->file_size() + (8 - offset), file->file_offset() + offset);
  270. return data;
  271. }
  272. BinaryData fragments_count(4);
  273. ReadData(fragments_count, 4, file->file_offset());
  274. long long fragments_number = fragments_count.ToNumber<4>(0);
  275. long long current_block_size = file->block_size() - offset - 8 * fragments_number;
  276. ReadData(data, current_block_size , file->file_offset() + offset);
  277. BinaryData FragmentsDictionary(8 * unsigned(fragments_number));
  278. ReadData(FragmentsDictionary, 8 * unsigned(fragments_number), file->file_offset() + file->block_size() - 8 * fragments_number);
  279. for (long long i = 0; i < fragments_number; i++) {
  280. long long fragment_size = FragmentsDictionary.ToNumber<4>(8 * i);
  281. long long fragment_offset = FragmentsDictionary.ToNumber<4>(8 * i + 4);
  282. ReadData(data, std::min(fragment_size, file->file_size() - current_block_size), fragment_offset, current_block_size );
  283. current_block_size += fragment_size;
  284. }
  285. return data;
  286. }
  287. /// DatFile special functions for opening and reading/writing raw data.
  288. /// Shouldn't be used by any external classes except Subfile and Subdirectory.
  289. void DatFile::OpenDatFile(const char *dat_name) {
  290. if (dat_state_ != CLOSED)
  291. throw DatException("Bad initialisation of DatFile - current DatFile isn't in correct state!",
  292. INIT_EXCEPTION);
  293. fopen_s(&file_handler_, dat_name, "r+b");
  294. if (file_handler_ == nullptr) {
  295. std::string err = "Bad DatFile::OpenDatFile. Unable to open file ";
  296. err += dat_name;
  297. throw DatException(err.c_str(), NOFILE_EXCEPTION);
  298. }
  299. fseek(file_handler_, 0, SEEK_END);
  300. file_size_ = ftell(file_handler_);
  301. fseek(file_handler_, 0, SEEK_SET);
  302. dat_state_ = SUCCESS_OPENED;
  303. }
  304. void DatFile::ReadSuperBlock() {
  305. if (dat_state_ != SUCCESS_OPENED)
  306. throw DatException("Bad DatFile::ReadSuperBlock() - DatFile isn't in valid state!", INIT_EXCEPTION);
  307. BinaryData data(1024);
  308. ReadData(data, 1024);
  309. constant1_ = data.ToNumber<4>(0x100);
  310. constant2_ = data.ToNumber<4>(0x140);
  311. version1_ = data.ToNumber<4>(0x14C);
  312. version2_ = data.ToNumber<4>(0x150);
  313. fragmentation_journal_offset_ = data.ToNumber<4>(0x154);
  314. root_directory_offset_ = data.ToNumber<4>(0x160);
  315. auto size1 = data.ToNumber<4>(0x148);
  316. if (constant1_ != 0x4C5000)
  317. throw DatException(
  318. "Bad DatFile::ReadSuperBlock - variable at position 0x100 is not equal to .dat file constant!",
  319. INIT_EXCEPTION);
  320. if (constant2_ != 0x5442)
  321. throw DatException(
  322. "Bad DatFile::ReadSuperBlock - variable at position 0x140 is not equal to .dat file constant!",
  323. INIT_EXCEPTION);
  324. if (file_size_ != size1)
  325. throw DatException(
  326. "Bad DatFile::ReadSuperBlock - variable at 0x148 position is not equal to .dat file size!",
  327. INIT_EXCEPTION);
  328. dat_state_ = SUCCESS_SUPERBLOCK;
  329. }
  330. void DatFile::MakeDirectories() {
  331. if (dat_state_ != SUCCESS_SUPERBLOCK)
  332. throw DatException("Bad DatFile::MakeDirectories() - DatFile isn't in valid state!", INIT_EXCEPTION);
  333. root_directory_ = new SubDirectory((unsigned) root_directory_offset_, this);
  334. dat_state_ = SUCCESS_DIRECTORIES;
  335. }
  336. void DatFile::MakeDictionary() {
  337. if (dat_state_ != SUCCESS_DIRECTORIES)
  338. throw DatException("Bad DatFile::MakeDictionary() - DatFile isn't in valid state!", INIT_EXCEPTION);
  339. try {
  340. if (root_directory_ == nullptr)
  341. throw DatException("Bad DatFile::MakeDictionary() - root_directory is nullptr!", INIT_EXCEPTION);
  342. root_directory_->MakeDictionary(dictionary_);
  343. } catch (std::exception &e) {
  344. fprintf(stderr, "Caught %s exception.", e.what());
  345. fprintf(stderr, "Bad DatFile::MakeDictionary() - File is corrupted?\n");
  346. return;
  347. }
  348. dat_state_ = SUCCESS_DICTIONARY;
  349. }
  350. void DatFile::ReadData(BinaryData &data, long long size, long long offset, long long data_offset) {
  351. if (dat_state_ == CLOSED)
  352. throw DatException("Bad DatFile::ReadData() - DatFile isn't in valid state!", READ_EXCEPTION);
  353. if (data_offset + size > data.size()) {
  354. std::string err = "Bad DatFile::ReadData - trying to read more than BinaryData size\n";
  355. err += std::string("Reading ") + std::to_string(size) + std::string(" bytes from ")
  356. + std::to_string(offset) + std::string(" position in dat file.");
  357. throw DatException(err.c_str(), READ_EXCEPTION);
  358. }
  359. if (offset + size > file_size_) {
  360. std::string err = "Bad DatFile::ReadData - trying to read more than DatFile size elapsed\n";
  361. err += std::string("Reading ") + std::to_string(size) + std::string(" bytes from ")
  362. + std::to_string(offset) + std::string(" position in dat file.");
  363. throw DatException(err.c_str(), READ_EXCEPTION);
  364. }
  365. _fseeki64(file_handler_, offset, SEEK_SET);
  366. fread(data.data() + data_offset, unsigned(size), 1, file_handler_);
  367. data.CheckCompression();
  368. }
  369. void DatFile::WriteData(const BinaryData &data, long long size, long long offset, long long data_offset) {
  370. if (dat_state_ < READY)
  371. throw DatException("Bad DatFile::WriteData() - DatFile isn't in valid state!", WRITE_EXCEPTION);
  372. _fseeki64(file_handler_, offset, SEEK_SET);
  373. if (data_offset + size > data.size())
  374. throw DatException("Bad DatFile::WriteData - trying to write more than BinaryData size", WRITE_EXCEPTION);
  375. fwrite(data.data() + data_offset, unsigned(size), 1, file_handler_);
  376. }
  377. /// Special functions used by patch process.
  378. /// Shouldn't be used by any external class.
  379. void DatFile::ApplyFilePatch(Subfile *file, const BinaryData &data, bool rewrite_original) {
  380. if (patched_list.count(file->file_id()) != 0) {
  381. fprintf(stderr, "Warning: DatFile::ApplyFilePatch - found 2 files in patch with the same file_id = %lld. Passing last...\n", file->file_id());
  382. return;
  383. }
  384. if (current_locale() != PATCHED && !rewrite_original) {
  385. std::cout << "Changing locale to RU in order to patch file" << std::endl;
  386. SetLocale(PATCHED);
  387. }
  388. dat_state_ = UPDATED;
  389. if (orig_dict_.count(file->file_id()) == 0 && !rewrite_original) {
  390. orig_dict_[file->file_id()] = new Subfile(this, file->MakeHeaderData());
  391. }
  392. auto journal = GetFragmentationJournal();
  393. if (journal[0].second != file_size_) {
  394. journal[0].second = file_size_;
  395. }
  396. file->file_size_ = data.size() - 8;
  397. if ((patch_dict_.count(file->file_id()) == 0 && !rewrite_original) || data.size() > file->block_size()) {
  398. file->file_offset_ = journal[0].second;
  399. file->block_size_ = std::max(data.size(), 256u);
  400. journal[0].second += data.size();
  401. BinaryData nulls(data.size());
  402. WriteData(nulls, nulls.size(), file_size_);
  403. this->file_size_ += data.size();
  404. }
  405. BinaryData fragments_count(4);
  406. fragments_count = BinaryData::FromNumber<4>(0);
  407. BinaryData file_data = fragments_count + data.CutData(4);
  408. if (file->file_id() != file_data.ToNumber<4>(8))
  409. throw DatException("Bad DatFile::ApplyFilePatch() - Created data's file_id doesn't match to original! "
  410. "Patch wasn't written to .dat file");
  411. WriteData(file_data, file_data.size(), file->file_offset());
  412. auto file_id = file->file_id();
  413. patched_list.insert(file_id);
  414. if (!rewrite_original) {
  415. patch_dict_.erase(file_id); // Удалили старое значение в русском словаре
  416. patch_dict_[file_id] = new Subfile(this, file->MakeHeaderData()); // Создали новое значение
  417. }
  418. // If category is forbidden, then return file header data to original state
  419. if (inactive_categories.count(file->category) != 0) {
  420. dictionary_[file_id]->file_offset_ = orig_dict_[file_id]->file_offset_;
  421. dictionary_[file_id]->file_size_ = orig_dict_[file_id]->file_size_;
  422. dictionary_[file_id]->block_size_ = orig_dict_[file_id]->block_size_;
  423. dictionary_[file_id]->timestamp_ = orig_dict_[file_id]->timestamp_;
  424. dictionary_[file_id]->version_ = orig_dict_[file_id]->version_;
  425. }
  426. if (orig_dict_.count(file_id) != 0)
  427. orig_dict_[file_id]->category = file->category;
  428. if (patch_dict_.count(file_id) != 0)
  429. patch_dict_[file_id]->category = file->category;
  430. UpdateFragmentationJournal(journal);
  431. }
  432. void DatFile::UpdateSubdirectories() {
  433. root_directory_->UpdateDirectories(patched_list, dictionary_);
  434. }
  435. std::vector<std::pair<long long, long long> > DatFile::GetFragmentationJournal() {
  436. BinaryData data(8);
  437. ReadData(data, 8, fragmentation_journal_offset_ + 8);
  438. std::vector<std::pair<long long, long long> > result;
  439. result.emplace_back(std::make_pair(data.ToNumber<4>(0), data.ToNumber<4>(4)));
  440. return result;
  441. }
  442. void DatFile::UpdateHeader() {
  443. WriteData(BinaryData::FromNumber<4>(constant1_), 4, 0x100);
  444. WriteData(BinaryData::FromNumber<4>(constant2_), 4, 0x140);
  445. WriteData(BinaryData::FromNumber<4>(file_size_), 4, 0x148);
  446. WriteData(BinaryData::FromNumber<4>(version1_), 4, 0x14C);
  447. WriteData(BinaryData::FromNumber<4>(version2_), 4, 0x150);
  448. WriteData(BinaryData::FromNumber<4>(fragmentation_journal_offset_), 4, 0x154);
  449. WriteData(BinaryData::FromNumber<4>(root_directory_offset_), 4, 0x160);
  450. }
  451. void DatFile::UpdateFragmentationJournal(const std::vector<std::pair<long long, long long> > &journal) {
  452. for (unsigned i = 0; i < journal.size(); i++) {
  453. long long size = journal[i].first;
  454. long long offset = journal[i].second;
  455. WriteData(BinaryData::FromNumber<4>(size), 4, fragmentation_journal_offset_ + 8 * (i + 1));
  456. WriteData(BinaryData::FromNumber<4>(offset), 4, fragmentation_journal_offset_ + 8 * (i + 1) + 4);
  457. }
  458. }
  459. bool DatFile::CommitChanges() {
  460. try {
  461. if (dat_state_ != UPDATED)
  462. return true;
  463. std::cout << "There are some updated files. Rewriting dictionary..." << std::endl << std::flush;
  464. std::cout << "Updating locales..." << std::endl;
  465. CommitLocales();
  466. auto journal = GetFragmentationJournal();
  467. if (!patched_list.empty()) {
  468. journal[0].second = file_size_;
  469. BinaryData nulls(size_t(journal[0].first));
  470. WriteData(nulls, nulls.size(), file_size_);
  471. file_size_ += journal[0].first;
  472. }
  473. UpdateFragmentationJournal(journal);
  474. std::cout << "Updated fragmentation journal..." << std::endl << std::flush;
  475. UpdateHeader();
  476. std::cout << "Updated header..." << std::endl << std::flush;
  477. UpdateSubdirectories();
  478. std::cout << "Updated subdirectories..." << std::endl << std::flush;
  479. std::cout << "Changed " << patched_list.size() << " files..." << std::endl << std::flush;
  480. std::cout << "Done!" << std::endl;
  481. patched_list.clear();
  482. dat_state_ = READY;
  483. return true;
  484. } catch (std::exception &e) {
  485. fprintf(stderr, "Bad DatFile::CommitChanges - caught exception %s\n", e.what());
  486. return false;
  487. }
  488. }
  489. bool DatFile::CloseDatFile() {
  490. if (dat_state_ == CLOSED) {
  491. fprintf(stderr, "DatFile::CloseDatFile() - dat state is already closed. Nothing to do\n");
  492. return true;
  493. }
  494. try {
  495. if (dat_state_ == UPDATED) {
  496. CommitChanges();
  497. }
  498. orig_dict_.clear();
  499. patched_list.clear();
  500. pending_patch_.clear();
  501. current_locale_ = ORIGINAL;
  502. filename_.clear();
  503. if (file_handler_ != nullptr)
  504. fclose(file_handler_);
  505. delete file_handler_;
  506. delete root_directory_;
  507. patched_list.clear();
  508. dictionary_.clear();
  509. dat_state_ = CLOSED;
  510. } catch (std::exception &e) {
  511. fprintf(stderr, "Bad DatFile::CloseDatFile() - caught exception %s\n", e.what());
  512. return false;
  513. }
  514. return true;
  515. }
  516. // LOCALE MANAGING SECTION
  517. void DatFile::InitLocales() {
  518. std::cout << "Initialising locales..." << std::endl;
  519. BinaryData dicts_data = GetFileData(dictionary_[2013266257]);
  520. if (dicts_data.size() < 29) {
  521. fprintf(stderr, "WARNING: DatFile::InitLocales() - locales file is empty.. Initialising locale dicts as empty\n");
  522. std::cout << "Could't find locales file... Continuing without them" << std::endl;;
  523. return;
  524. }
  525. BinaryData hi_data = dicts_data.CutData(14, 29) + BinaryData("\0", 1);
  526. std::string hi = std::string((char*)(hi_data.data()));
  527. std::cout << hi << std::endl;
  528. if (hi != "Hi from Gi1dor!") {
  529. fprintf(stderr, "WARNING: DatFile::InitLocales() - Didn't receive 'hi' from Gi1dor... Initialising locale dicts as empty\n");
  530. std::cout << "Could't init locales' file... Continuing without them" << std::endl;
  531. return;
  532. }
  533. int offset = 29;
  534. BinaryData current_locale_data = dicts_data.CutData(offset, offset + 4) + BinaryData("\0", 1);
  535. std::string locale((char*)(current_locale_data.data()));
  536. offset += 4;
  537. std::cout << locale << std::endl;
  538. if (locale != "PATC" && locale != "ORIG") {
  539. fprintf(stderr, "WARNING: DatFile::InitLocales() - Incorrect locale... Initialising locale dicts as empty\n");
  540. std::cout << "Could't recognize locale... Continuing without locales" << std::endl;;
  541. return;
  542. }
  543. current_locale_ = (locale == "PATC" ? PATCHED : ORIGINAL);
  544. // 14 bytes for old data
  545. // 15 bytes for "Hi from Gi1dor"
  546. // 4 bytes for LOCALE
  547. // 4 bytes for orig_dict.size()
  548. // (32 + 4) * orig_dict.size() bytes for orig_dict data
  549. // 4 bytes for patch_dict.size()
  550. // (32 + 4) * patch_dict.size() bytes for patch_dict data
  551. // 4 bytes for inactive_categories dict
  552. // 4 * inactive_categories.size() bytes for inactive_categories data
  553. size_t orig_dict_size = size_t(dicts_data.CutData(offset, offset + 4).ToNumber<4>(0));
  554. offset += 4;
  555. for (size_t i = 0; i < orig_dict_size; i++) {
  556. auto file = new Subfile(this, dicts_data.CutData(offset, offset + 32));
  557. orig_dict_[file->file_id()] = file;
  558. offset += 32;
  559. orig_dict_[file->file_id()]->category = dicts_data.ToNumber<4>(offset);
  560. offset += 4;
  561. if (orig_dict_[file->file_id()]->category == 0)
  562. fprintf(stderr, "WARNING DatFile::InitLocales() - file category is undefined (0)!\n");
  563. }
  564. size_t patch_dict_size = size_t(dicts_data.CutData(offset, offset + 4).ToNumber<4>(0));
  565. offset += 4;
  566. for (size_t i = 0; i < patch_dict_size; i++) {
  567. auto file = new Subfile(this, dicts_data.CutData(offset, offset + 32));
  568. patch_dict_[file->file_id()] = file;
  569. offset += 32;
  570. patch_dict_[file->file_id()]->category = dicts_data.ToNumber<4>(offset);
  571. offset += 4;
  572. if (patch_dict_[file->file_id()]->category == 0)
  573. fprintf(stderr, "WARNING DatFile::InitLocales() - file category is undefined (0)!\n");
  574. }
  575. size_t active_patches_dict_size = size_t(dicts_data.CutData(offset, offset + 4).ToNumber<4>(0));
  576. offset += 4;
  577. for (size_t i = 0; i < active_patches_dict_size; i++) {
  578. inactive_categories.insert(dicts_data.ToNumber<4>(offset));
  579. offset += 4;
  580. }
  581. std::cout << "There are " << patch_dict_.size() << " files in patch locale dictionary" << std::endl;
  582. std::cout << "There are " << orig_dict_.size() << " files in original locale dictionary" << std::endl;
  583. std::cout << "Unactive patches now: ";
  584. for (auto i : inactive_categories)
  585. std:: cout << i;
  586. std::cout << std::endl;
  587. }
  588. std::unordered_map<long long, Subfile *> *DatFile::GetLocaleDictReference(LOCALE locale) {
  589. switch (locale) {
  590. case PATCHED:
  591. return &patch_dict_;
  592. case ORIGINAL:
  593. return &orig_dict_;
  594. default:
  595. throw DatException("Bad DatFile::GetLocaleDictReference() - unknown locale!!!", LOCALE_EXCEPTION);
  596. }
  597. }
  598. void DatFile::SetLocale(LOCALE locale) {
  599. try {
  600. if (dat_state_ < READY) {
  601. fprintf(stderr, "Bad DatFile::SetLocale() - DatFile is in incorrect state... Cannot set locale\n");
  602. return;
  603. }
  604. if (current_locale_ == locale) {
  605. return;
  606. }
  607. dat_state_ = UPDATED;
  608. auto dict = GetLocaleDictReference(locale);
  609. for (auto file : *dict) {
  610. if (dictionary_[file.first] == nullptr) {
  611. fprintf(stderr,
  612. "WARNING: In locale dictionary there is file with file_id = %lld, which is not in .dat "
  613. "file! Passing it and removing from locale dictionary\n", file.first);
  614. dict->erase(file.first);
  615. continue;
  616. }
  617. if (dictionary_[file.first]->MakeHeaderData().CutData(8, 16) ==
  618. file.second->MakeHeaderData().CutData(8, 16) || inactive_categories.count(orig_dict_[file.first]->category) != 0)
  619. continue;
  620. long long file_id = file.first;
  621. Subfile *new_file = file.second;
  622. dictionary_[file_id]->file_offset_ = new_file->file_offset_;
  623. dictionary_[file_id]->file_size_ = new_file->file_size_;
  624. dictionary_[file_id]->block_size_ = new_file->block_size_;
  625. dictionary_[file_id]->timestamp_ = new_file->timestamp_;
  626. dictionary_[file_id]->version_ = new_file->version_;
  627. patched_list.insert(file.first);
  628. dat_state_ = UPDATED;
  629. }
  630. current_locale_ = locale;
  631. CommitChanges();
  632. } catch (std::exception &e) {
  633. fprintf(stderr, "Bad DatFile::SetLocale() - caught exception %s. Locale wasn't set.\n", e.what());
  634. return;
  635. }
  636. }
  637. bool DatFile::CheckIfUpdatedByGame() {
  638. return false;
  639. }
  640. void DatFile::RepairPatches(Database *db) {
  641. }
  642. LOCALE DatFile::current_locale() {
  643. if (dat_state_ < READY) {
  644. fprintf(stderr, "Bad DatFile::current_locale() - dat_file is in incorrect state!\n");
  645. return ORIGINAL;
  646. }
  647. if (current_locale_ != PATCHED && current_locale_ != ORIGINAL) {
  648. fprintf(stderr, "Bad DatFile::current_locale() - locale has incorrect value. Setting it to original\n");
  649. current_locale_ = ORIGINAL;
  650. }
  651. return current_locale_;
  652. }
  653. void DatFile::CommitLocales() {
  654. std::cout << "Committing locales..." << std::endl;
  655. SubfileData data = dictionary_[2013266257]->PrepareForExport(GetFileData(dictionary_[2013266257]));
  656. data.options["fid"] = "2013266257";
  657. data.options["ext"] = ".unknown";
  658. BinaryData old_data = BinaryData(GetFileData(dictionary_[2013266257u]));
  659. // 14 bytes for old data
  660. // 15 bytes for "Hi from Gi1dor"
  661. // 4 bytes for LOCALE
  662. // 4 bytes for orig_dict.size()
  663. // (32 + 4) * orig_dict.size() bytes for orig_dict data
  664. // 4 bytes for patch_dict.size()
  665. // (32 + 4) * patch_dict.size() bytes for patch_dict data
  666. // 4 bytes for inactive_categories list
  667. // 4 * inactive_categories.size() bytes for inactive_categories data
  668. data.binary_data = BinaryData(14 + 15 + 4
  669. + 4 + (32 + 4) * orig_dict_.size()
  670. + 4 + (32 + 4) * patch_dict_.size()
  671. + 4 + 4 * inactive_categories.size());
  672. size_t current_size = 0;
  673. data.binary_data.Append(GetFileData(dictionary_[2013266257u]).CutData(0, 14), current_size);
  674. current_size += 14;
  675. data.binary_data.Append(BinaryData("Hi from Gi1dor!", 15), current_size);
  676. current_size += 15;
  677. data.binary_data.Append(BinaryData((current_locale_ == ORIGINAL ? "ORIG" : "PATC"), 4), current_size);
  678. current_size += 4;
  679. data.binary_data.Append(BinaryData::FromNumber<4>(orig_dict_.size()), current_size);
  680. current_size += 4;
  681. for (auto file : orig_dict_) {
  682. data.binary_data.Append(file.second->MakeHeaderData(), current_size);
  683. current_size += 32;
  684. data.binary_data.Append(BinaryData::FromNumber<4>(file.second->category), current_size);
  685. current_size += 4;
  686. }
  687. data.binary_data.Append(BinaryData::FromNumber<4>(patch_dict_.size()), current_size);
  688. current_size += 4;
  689. for (auto file : patch_dict_) {
  690. data.binary_data.Append(file.second->MakeHeaderData(), current_size);
  691. current_size += 32;
  692. data.binary_data.Append(BinaryData::FromNumber<4>(file.second->category), current_size);
  693. current_size += 4;
  694. }
  695. data.binary_data.Append(BinaryData::FromNumber<4>(inactive_categories.size()), current_size);
  696. current_size += 4;
  697. for (auto patch_id : inactive_categories) {
  698. data.binary_data.Append(BinaryData::FromNumber<4>(patch_id), current_size);
  699. current_size += 4;
  700. }
  701. PatchFile(data, true);
  702. std::cout << "Done!" << std::endl;
  703. }
  704. void DatFile::EnableCategory(int category) {
  705. std::cout << "Disabling category " << category << std::endl;
  706. if (inactive_categories.count(category) == 0)
  707. return;
  708. inactive_categories.erase(category);
  709. for (auto file : dictionary_) {
  710. auto file_id = file.first;
  711. if (patch_dict_.count(file_id) > 0 && patch_dict_[file_id]->category == category) {
  712. dat_state_ = UPDATED;
  713. file.second->file_offset_ = patch_dict_[file_id]->file_offset_;
  714. file.second->file_size_ = patch_dict_[file_id]->file_size_;
  715. file.second->block_size_ = patch_dict_[file_id]->block_size_;
  716. file.second->timestamp_ = patch_dict_[file_id]->timestamp_;
  717. file.second->version_ = patch_dict_[file_id]->version_;
  718. patched_list.insert(file_id);
  719. }
  720. }
  721. }
  722. void DatFile::DisableCategory(int category) {
  723. std::cout << "Disabling category " << category << std::endl;
  724. if (inactive_categories.count(category) != 0)
  725. return;
  726. inactive_categories.insert(category);
  727. for (auto file : dictionary_) {
  728. auto file_id = file.first;
  729. if (orig_dict_.count(file_id) && orig_dict_[file_id]->category == category) {
  730. dat_state_ = UPDATED;
  731. file.second->file_offset_ = orig_dict_[file_id]->file_offset_;
  732. file.second->file_size_ = orig_dict_[file_id]->file_size_;
  733. file.second->block_size_ = orig_dict_[file_id]->block_size_;
  734. file.second->timestamp_ = orig_dict_[file_id]->timestamp_;
  735. file.second->version_ = orig_dict_[file_id]->version_;
  736. patched_list.insert(file_id);
  737. }
  738. }
  739. }
  740. const std::unordered_set<long long>& DatFile::GetInactiveCategoriesList() {
  741. return inactive_categories;
  742. }
  743. }
  744. }