DatFile.cpp 29 KB

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