DatFile.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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. if (orig_dict_.count(file->file_id()) == 0) {
  395. orig_dict_[file->file_id()] = new Subfile(this, dictionary_[file->file_id()]->MakeHeaderData());
  396. }
  397. auto journal = GetFragmentationJournal();
  398. if (journal[0].second != file_size_) {
  399. journal[0].second = file_size_;
  400. }
  401. file->file_size_ = data.size() - 8;
  402. if (patch_dict_.count(file->file_id()) == 0 || data.size() > file->block_size()) {
  403. file->file_offset_ = journal[0].second;
  404. file->block_size_ = std::max(data.size(), 256u);
  405. journal[0].second += data.size();
  406. BinaryData nulls(data.size());
  407. WriteData(nulls, nulls.size(), file_size_);
  408. this->file_size_ += data.size();
  409. }
  410. BinaryData fragments_count(4);
  411. fragments_count = BinaryData::FromNumber<4>(0);
  412. BinaryData file_data = fragments_count + data.CutData(4);
  413. if (file->file_id() != file_data.ToNumber<4>(8))
  414. throw DatException("Bad DatFile::ApplyFilePatch() - Created data's file_id doesn't match to original! "
  415. "Patch wasn't written to .dat file");
  416. WriteData(file_data, file_data.size(), file->file_offset());
  417. auto file_id = file->file_id();
  418. patched_list.insert(file_id);
  419. patch_dict_.erase(file_id); // Удалили старое значение в русском словаре
  420. patch_dict_[file_id] = new Subfile(this, file->MakeHeaderData()); // Создали новое значение
  421. UpdateFragmentationJournal(journal);
  422. }
  423. void DatFile::UpdateSubdirectories() {
  424. root_directory_->UpdateDirectories(patched_list, dictionary_);
  425. }
  426. std::vector<std::pair<long long, long long> > DatFile::GetFragmentationJournal() {
  427. BinaryData data(8);
  428. ReadData(data, 8, fragmentation_journal_offset_ + 8);
  429. std::vector<std::pair<long long, long long> > result;
  430. result.emplace_back(std::make_pair(data.ToNumber<4>(0), data.ToNumber<4>(4)));
  431. return result;
  432. }
  433. void DatFile::UpdateHeader() {
  434. WriteData(BinaryData::FromNumber<4>(constant1_), 4, 0x100);
  435. WriteData(BinaryData::FromNumber<4>(constant2_), 4, 0x140);
  436. WriteData(BinaryData::FromNumber<4>(file_size_), 4, 0x148);
  437. WriteData(BinaryData::FromNumber<4>(version1_), 4, 0x14C);
  438. WriteData(BinaryData::FromNumber<4>(version2_), 4, 0x150);
  439. WriteData(BinaryData::FromNumber<4>(fragmentation_journal_offset_), 4, 0x154);
  440. WriteData(BinaryData::FromNumber<4>(root_directory_offset_), 4, 0x160);
  441. }
  442. void DatFile::UpdateFragmentationJournal(const std::vector<std::pair<long long, long long> > &journal) {
  443. for (unsigned i = 0; i < journal.size(); i++) {
  444. long long size = journal[i].first;
  445. long long offset = journal[i].second;
  446. WriteData(BinaryData::FromNumber<4>(size), 4, fragmentation_journal_offset_ + 8 * (i + 1));
  447. WriteData(BinaryData::FromNumber<4>(offset), 4, fragmentation_journal_offset_ + 8 * (i + 1) + 4);
  448. }
  449. }
  450. bool DatFile::CommitChanges() {
  451. try {
  452. if (dat_state_ != UPDATED)
  453. return true;
  454. std::cout << "There are some updated files. Rewriting dictionary..." << std::endl << std::flush;
  455. auto journal = GetFragmentationJournal();
  456. if (!patched_list.empty()) {
  457. journal[0].second = file_size_;
  458. BinaryData nulls(size_t(journal[0].first));
  459. WriteData(nulls, nulls.size(), file_size_);
  460. file_size_ += journal[0].first;
  461. }
  462. UpdateFragmentationJournal(journal);
  463. std::cout << "Updated fragmentation journal..." << std::endl << std::flush;
  464. UpdateHeader();
  465. std::cout << "Updated header..." << std::endl << std::flush;
  466. UpdateSubdirectories();
  467. std::cout << "Updated subdirectories..." << std::endl << std::flush;
  468. std::cout << "Changed " << patched_list.size() << " files..." << std::endl << std::flush;
  469. std::cout << "Updating locales..." << std::endl;
  470. CommitLocales();
  471. std::cout << "Done!" << std::endl;
  472. patched_list.clear();
  473. dat_state_ = READY;
  474. return true;
  475. } catch (std::exception &e) {
  476. fprintf(stderr, "Bad DatFile::CommitChanges - caught exception %s\n", e.what());
  477. return false;
  478. }
  479. }
  480. bool DatFile::CloseDatFile() {
  481. if (dat_state_ == CLOSED) {
  482. fprintf(stderr, "DatFile::CloseDatFile() - dat state is already closed. Nothing to do\n");
  483. return true;
  484. }
  485. try {
  486. if (dat_state_ == UPDATED) {
  487. CommitChanges();
  488. }
  489. orig_dict_.clear();
  490. patched_list.clear();
  491. pending_patch_.clear();
  492. current_locale_ = ORIGINAL;
  493. filename_.clear();
  494. if (file_handler_ != nullptr)
  495. fclose(file_handler_);
  496. delete file_handler_;
  497. delete root_directory_;
  498. patched_list.clear();
  499. dictionary_.clear();
  500. dat_state_ = CLOSED;
  501. } catch (std::exception &e) {
  502. fprintf(stderr, "Bad DatFile::CloseDatFile() - caught exception %s\n", e.what());
  503. return false;
  504. }
  505. return true;
  506. }
  507. // LOCALE MANAGING SECTION
  508. void DatFile::InitLocale(LOCALE locale, const char* filename) {
  509. auto dict = GetLocaleDictReference(locale);
  510. dict->clear();
  511. FILE *dict_file = fopen(filename, "rb");
  512. if (dict_file == nullptr) {
  513. fprintf(stderr, "WARNING!!! DatFile::InitLocale() - cannot open .dat locale file %s\n", filename);
  514. return;
  515. }
  516. size_t size;
  517. fread(&size, sizeof(size_t), 1, dict_file);
  518. std::cout << "There are " << size << " files in " << std::string(filename) << " dictionary...\n";
  519. for (size_t i = 0; i < size; i++) {
  520. BinaryData header(32);
  521. fread(header.data(), unsigned(header.size()), 1, dict_file);
  522. auto file = new Subfile(this, header);
  523. (*dict)[file->file_id()] = file;
  524. }
  525. fclose(dict_file);
  526. }
  527. std::unordered_map<long long, Subfile *> *DatFile::GetLocaleDictReference(LOCALE locale) {
  528. switch (locale) {
  529. case PATCHED:
  530. return &patch_dict_;
  531. case ORIGINAL:
  532. return &orig_dict_;
  533. default:
  534. throw DatException("Bad DatFile::GetLocaleDictReference() - unknown locale!!!", LOCALE_EXCEPTION);
  535. }
  536. }
  537. void DatFile::SetLocale(LOCALE locale) {
  538. try {
  539. if (dat_state_ < READY) {
  540. fprintf(stderr, "Bad DatFile::SetLocale() - DatFile is in incorrect state... Cannot set locale\n");
  541. return;
  542. }
  543. if (current_locale_ == locale) {
  544. return;
  545. }
  546. dat_state_ = UPDATED;
  547. auto dict = GetLocaleDictReference(locale);
  548. for (auto file : *dict) {
  549. if (dictionary_[file.first] == nullptr) {
  550. fprintf(stderr,
  551. "WARNING: In locale dictionary there is file with file_id = %lld, which is not in .dat "
  552. "file! Passing it and removing from locale dictionary\n", file.first);
  553. dict->erase(file.first);
  554. continue;
  555. }
  556. if (dictionary_[file.first]->MakeHeaderData().CutData(8, 16) ==
  557. 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. } catch (std::exception &e) {
  572. fprintf(stderr, "Bad DatFile::SetLocale() - caught exception %s. Locale wasn't set.\n", e.what());
  573. return;
  574. }
  575. }
  576. void DatFile::SaveLocale(LOCALE locale, const char *filename) {
  577. auto dict = GetLocaleDictReference(locale);
  578. FILE *dict_file = fopen(filename, "wb");
  579. size_t count = size_t(dict->size());
  580. fwrite(&count, sizeof(size_t), 1, dict_file);
  581. for (auto file : *dict) {
  582. BinaryData header = file.second->MakeHeaderData();
  583. fwrite(header.data(), unsigned(header.size()), 1, dict_file);
  584. }
  585. fclose(dict_file);
  586. }
  587. bool DatFile::CheckIfUpdatedByGame() {
  588. return false;
  589. }
  590. void DatFile::RepairPatches(Database *db) {
  591. }
  592. LOCALE DatFile::current_locale() {
  593. if (dat_state_ < READY) {
  594. fprintf(stderr, "Bad DatFile::current_locale() - dat_file is in incorrect state!\n");
  595. return ORIGINAL;
  596. }
  597. if (current_locale_ != PATCHED && current_locale_ != ORIGINAL) {
  598. fprintf(stderr, "Bad DatFile::current_locale() - locale has incorrect value. Setting it to original\n");
  599. current_locale_ = ORIGINAL;
  600. }
  601. return current_locale_;
  602. }
  603. void DatFile::CommitLocales() {
  604. std::cout << "Commiting locales..." << std::endl;
  605. std::cout << "Saving patched locale..." << std::endl;
  606. SaveLocale(PATCHED, (std::string(filename_) + std::string("patched.dbgm")).c_str());
  607. std::cout << "Saving original locale..." << std::endl;
  608. SaveLocale(ORIGINAL,(std::string(filename_) + std::string("original.dbgm")).c_str());
  609. std::cout << "Writing current locale" << std::endl;
  610. FILE *locale = fopen((std::string(filename_) + ".dbgm").c_str(), "w");
  611. if (current_locale_ == ORIGINAL)
  612. fprintf(locale, "EN");
  613. else
  614. fprintf(locale, "RU");
  615. fclose(locale);
  616. std::cout << "Done!" << std::endl;
  617. }
  618. }
  619. }