DatFile.cpp 29 KB

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