grfio.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "grfio.hpp"
  4. #include <cstdlib>
  5. #include <zlib.h>
  6. #include "cbasetypes.hpp"
  7. #include "des.hpp"
  8. #include "malloc.hpp"
  9. #include "showmsg.hpp"
  10. #include "strlib.hpp"
  11. #include "utils.hpp"
  12. //----------------------------
  13. // file entry table struct
  14. //----------------------------
  15. typedef struct _FILELIST {
  16. int srclen; // compressed size
  17. int srclen_aligned;
  18. int declen; // original size
  19. int srcpos; // position of entry in grf
  20. int next; // index of next filelist entry with same hash (-1: end of entry chain)
  21. char type;
  22. char fn[128-4*5]; // file name
  23. char* fnd; // if the file was cloned, contains name of original file
  24. char gentry; // read grf file select
  25. } FILELIST;
  26. #define FILELIST_TYPE_FILE 0x01 // entry is a file
  27. #define FILELIST_TYPE_ENCRYPT_HEADER 0x04 // encryption mode 1 (header DES only)
  28. #define FILELIST_TYPE_ENCRYPT_MIXED 0x02 // encryption mode 0 (header DES + periodic DES/shuffle)
  29. //gentry ... > 0 : data read from a grf file (gentry_table[gentry-1])
  30. //gentry ... 0 : data read from a local file (data directory)
  31. //gentry ... < 0 : entry "-(gentry)" is marked for a local file check
  32. // - if local file exists, gentry will be set to 0 (thus using the local file)
  33. // - if local file doesn't exist, sign is inverted (thus using the original file inside a grf)
  34. // (NOTE: this case is only used once (during startup) and only if GRFIO_LOCAL is enabled)
  35. // (NOTE: probably meant to be used to override grf contents by files in the data directory)
  36. //#define GRFIO_LOCAL
  37. // stores info about every loaded file
  38. FILELIST* filelist = nullptr;
  39. int filelist_entrys = 0;
  40. int filelist_maxentry = 0;
  41. // stores grf file names
  42. char** gentry_table = nullptr;
  43. int gentry_entrys = 0;
  44. int gentry_maxentry = 0;
  45. // the path to the data directory
  46. char data_dir[1024] = "";
  47. // little endian char array to uint conversion
  48. static unsigned int getlong(unsigned char* p)
  49. {
  50. return (p[0] << 0 | p[1] << 8 | p[2] << 16 | p[3] << 24);
  51. }
  52. static void NibbleSwap(unsigned char* src, int len)
  53. {
  54. while( len > 0 )
  55. {
  56. *src = (*src >> 4) | (*src << 4);
  57. ++src;
  58. --len;
  59. }
  60. }
  61. /// Substitutes some specific values for others, leaves rest intact. Obfuscation.
  62. /// NOTE: Operation is symmetric (calling it twice gives back the original input).
  63. static uint8_t grf_substitution(uint8_t in)
  64. {
  65. uint8_t out;
  66. switch( in )
  67. {
  68. case 0x00: out = 0x2B; break;
  69. case 0x2B: out = 0x00; break;
  70. case 0x6C: out = 0x80; break;
  71. case 0x01: out = 0x68; break;
  72. case 0x68: out = 0x01; break;
  73. case 0x48: out = 0x77; break;
  74. case 0x60: out = 0xFF; break;
  75. case 0x77: out = 0x48; break;
  76. case 0xB9: out = 0xC0; break;
  77. case 0xC0: out = 0xB9; break;
  78. case 0xFE: out = 0xEB; break;
  79. case 0xEB: out = 0xFE; break;
  80. case 0x80: out = 0x6C; break;
  81. case 0xFF: out = 0x60; break;
  82. default: out = in; break;
  83. }
  84. return out;
  85. }
  86. /* this is not used anywhere, is it ok to delete? */
  87. //static void grf_shuffle_enc(BIT64* src) {
  88. // BIT64 out;
  89. //
  90. // out.b[0] = src->b[3];
  91. // out.b[1] = src->b[4];
  92. // out.b[2] = src->b[5];
  93. // out.b[3] = src->b[0];
  94. // out.b[4] = src->b[1];
  95. // out.b[5] = src->b[6];
  96. // out.b[6] = src->b[2];
  97. // out.b[7] = grf_substitution(src->b[7]);
  98. //
  99. // *src = out;
  100. //}
  101. static void grf_shuffle_dec(BIT64* src)
  102. {
  103. BIT64 out;
  104. out.b[0] = src->b[3];
  105. out.b[1] = src->b[4];
  106. out.b[2] = src->b[6];
  107. out.b[3] = src->b[0];
  108. out.b[4] = src->b[1];
  109. out.b[5] = src->b[2];
  110. out.b[6] = src->b[5];
  111. out.b[7] = grf_substitution(src->b[7]);
  112. *src = out;
  113. }
  114. static void grf_decode_header(unsigned char* buf, size_t len)
  115. {
  116. BIT64* p = (BIT64*)buf;
  117. size_t nblocks = len / sizeof(BIT64);
  118. size_t i;
  119. // first 20 blocks are all des-encrypted
  120. for( i = 0; i < 20 && i < nblocks; ++i )
  121. des_decrypt_block(&p[i]);
  122. // the rest is plaintext, done.
  123. }
  124. static void grf_decode_full(unsigned char* buf, size_t len, int cycle)
  125. {
  126. BIT64* p = (BIT64*)buf;
  127. size_t nblocks = len / sizeof(BIT64);
  128. int dcycle, scycle;
  129. size_t i, j;
  130. // first 20 blocks are all des-encrypted
  131. for( i = 0; i < 20 && i < nblocks; ++i )
  132. des_decrypt_block(&p[i]);
  133. // after that only one of every 'dcycle' blocks is des-encrypted
  134. dcycle = cycle;
  135. // and one of every 'scycle' plaintext blocks is shuffled (starting from the 0th but skipping the 0th)
  136. scycle = 7;
  137. // so decrypt/de-shuffle periodically
  138. j = -1; // 0, adjusted to fit the ++j step
  139. for( i = 20; i < nblocks; ++i )
  140. {
  141. if( i % dcycle == 0 )
  142. {// decrypt block
  143. des_decrypt_block(&p[i]);
  144. continue;
  145. }
  146. ++j;
  147. if( j % scycle == 0 && j != 0 )
  148. {// de-shuffle block
  149. grf_shuffle_dec(&p[i]);
  150. continue;
  151. }
  152. // plaintext, do nothing.
  153. }
  154. }
  155. /// Decodes grf data.
  156. /// @param buf data to decode (in-place)
  157. /// @param len length of the data
  158. /// @param entry_type flags associated with the data
  159. /// @param entry_len true (unaligned) length of the data
  160. static void grf_decode(unsigned char* buf, size_t len, char entry_type, int entry_len)
  161. {
  162. if( entry_type & FILELIST_TYPE_ENCRYPT_MIXED )
  163. {// fully encrypted
  164. int digits;
  165. int cycle;
  166. int i;
  167. // compute number of digits of the entry length
  168. digits = 1;
  169. for( i = 10; i <= entry_len; i *= 10 )
  170. ++digits;
  171. // choose size of gap between two encrypted blocks
  172. // digits: 0 1 2 3 4 5 6 7 8 9 ...
  173. // cycle: 1 1 1 4 5 14 15 22 23 24 ...
  174. cycle = ( digits < 3 ) ? 1
  175. : ( digits < 5 ) ? digits + 1
  176. : ( digits < 7 ) ? digits + 9
  177. : digits + 15;
  178. grf_decode_full(buf, len, cycle);
  179. }
  180. else
  181. if( entry_type & FILELIST_TYPE_ENCRYPT_HEADER )
  182. {// header encrypted
  183. grf_decode_header(buf, len);
  184. }
  185. else
  186. {// plaintext
  187. ;
  188. }
  189. }
  190. /******************************************************
  191. *** Zlib Subroutines ***
  192. ******************************************************/
  193. /// zlib crc32
  194. unsigned long grfio_crc32(const unsigned char* buf, unsigned int len)
  195. {
  196. return crc32(crc32(0L, Z_NULL, 0), buf, len);
  197. }
  198. /// zlib uncompress
  199. int decode_zip(void* dest, unsigned long* destLen, const void* source, unsigned long sourceLen)
  200. {
  201. return uncompress((Bytef*)dest, destLen, (const Bytef*)source, sourceLen);
  202. }
  203. /// zlib compress
  204. int encode_zip(void* dest, unsigned long* destLen, const void* source, unsigned long sourceLen)
  205. {
  206. return compress((Bytef*)dest, destLen, (const Bytef*)source, sourceLen);
  207. }
  208. /***********************************************************
  209. *** File List Subroutines ***
  210. ***********************************************************/
  211. // file list hash table
  212. int filelist_hash[256];
  213. // initializes the table that holds the first elements of all hash chains
  214. static void hashinit(void)
  215. {
  216. int i;
  217. for (i = 0; i < 256; i++)
  218. filelist_hash[i] = -1;
  219. }
  220. // hashes a filename string into a number from {0..255}
  221. static int filehash(const char* fname)
  222. {
  223. unsigned int hash = 0;
  224. while(*fname) {
  225. hash = (hash<<1) + (hash>>7)*9 + TOLOWER(*fname);
  226. fname++;
  227. }
  228. return hash & 255;
  229. }
  230. // finds a FILELIST entry with the specified file name
  231. static FILELIST* filelist_find(const char* fname)
  232. {
  233. int hash, index;
  234. if (!filelist)
  235. return nullptr;
  236. hash = filelist_hash[filehash(fname)];
  237. for (index = hash; index != -1; index = filelist[index].next)
  238. if(!strcmpi(filelist[index].fn, fname))
  239. break;
  240. return (index >= 0) ? &filelist[index] : nullptr;
  241. }
  242. // returns the original file name
  243. char* grfio_find_file(const char* fname)
  244. {
  245. FILELIST *filelist_res = filelist_find(fname);
  246. if (!filelist_res) return nullptr;
  247. return (!filelist_res->fnd ? filelist_res->fn : filelist_res->fnd);
  248. }
  249. // adds a FILELIST entry into the list of loaded files
  250. static FILELIST* filelist_add(FILELIST* entry)
  251. {
  252. int hash;
  253. #define FILELIST_ADDS 1024 // number increment of file lists `
  254. if (filelist_entrys >= filelist_maxentry) {
  255. filelist = (FILELIST *)aRealloc(filelist, (filelist_maxentry + FILELIST_ADDS) * sizeof(FILELIST));
  256. memset(filelist + filelist_maxentry, '\0', FILELIST_ADDS * sizeof(FILELIST));
  257. filelist_maxentry += FILELIST_ADDS;
  258. }
  259. memcpy (&filelist[filelist_entrys], entry, sizeof(FILELIST));
  260. hash = filehash(entry->fn);
  261. filelist[filelist_entrys].next = filelist_hash[hash];
  262. filelist_hash[hash] = filelist_entrys;
  263. filelist_entrys++;
  264. return &filelist[filelist_entrys - 1];
  265. }
  266. // adds a new FILELIST entry or overwrites an existing one
  267. static FILELIST* filelist_modify(FILELIST* entry)
  268. {
  269. FILELIST* fentry = filelist_find(entry->fn);
  270. if (fentry != nullptr) {
  271. int tmp = fentry->next;
  272. memcpy(fentry, entry, sizeof(FILELIST));
  273. fentry->next = tmp;
  274. } else {
  275. fentry = filelist_add(entry);
  276. }
  277. return fentry;
  278. }
  279. // shrinks the file list array if too long
  280. static void filelist_compact(void)
  281. {
  282. if (filelist == nullptr)
  283. return;
  284. if (filelist_entrys < filelist_maxentry) {
  285. filelist = (FILELIST *)aRealloc(filelist, filelist_entrys * sizeof(FILELIST));
  286. filelist_maxentry = filelist_entrys;
  287. }
  288. }
  289. /***********************************************************
  290. *** Grfio Subroutines ***
  291. ***********************************************************/
  292. /// Combines are resource path with the data folder location to create local resource path.
  293. static void grfio_localpath_create(char* buffer, size_t size, const char* filename)
  294. {
  295. unsigned int i;
  296. size_t len;
  297. len = strlen(data_dir);
  298. if( data_dir[0] == '\0' || data_dir[len-1] == '/' || data_dir[len-1] == '\\' )
  299. {
  300. safesnprintf(buffer, size, "%s%s", data_dir, filename);
  301. }
  302. else
  303. {
  304. safesnprintf(buffer, size, "%s/%s", data_dir, filename);
  305. }
  306. // normalize path
  307. for( i = 0; buffer[i] != '\0'; ++i )
  308. if( buffer[i] == '\\' )
  309. buffer[i] = '/';
  310. }
  311. /// Reads a file into a newly allocated buffer (from grf or data directory).
  312. void* grfio_reads(const char* fname, size_t* size)
  313. {
  314. unsigned char* buf2 = nullptr;
  315. FILELIST* entry = filelist_find(fname);
  316. if( entry == nullptr || entry->gentry <= 0 ) {// LocalFileCheck
  317. char lfname[256];
  318. FILE* in;
  319. grfio_localpath_create(lfname, sizeof(lfname), ( entry && entry->fnd ) ? entry->fnd : fname);
  320. in = fopen(lfname, "rb");
  321. if( in != nullptr ) {
  322. fseek(in,0,SEEK_END);
  323. size_t declen = ftell(in);
  324. fseek(in,0,SEEK_SET);
  325. buf2 = (unsigned char *)aMalloc(declen+1); // +1 for resnametable zero-termination
  326. if(fread(buf2, 1, declen, in) != declen) ShowError("An error occured in fread grfio_reads, fname=%s \n",fname);
  327. fclose(in);
  328. if( size )
  329. *size = declen;
  330. } else {
  331. if (entry != nullptr && entry->gentry < 0) {
  332. entry->gentry = -entry->gentry; // local file checked
  333. } else {
  334. ShowError("grfio_reads: %s not found (local file: %s)\n", fname, lfname);
  335. return nullptr;
  336. }
  337. }
  338. }
  339. if( entry != nullptr && entry->gentry > 0 ) {// Archive[GRF] File Read
  340. char* grfname = gentry_table[entry->gentry - 1];
  341. FILE* in = fopen(grfname, "rb");
  342. if( in != nullptr ) {
  343. size_t fsize = entry->srclen_aligned;
  344. unsigned char *buf = (unsigned char *)aMalloc(fsize);
  345. fseek(in, entry->srcpos, 0);
  346. if(fread(buf, 1, fsize, in) != fsize) ShowError("An error occured in fread in grfio_reads, grfname=%s\n",grfname);
  347. fclose(in);
  348. buf2 = (unsigned char *)aMalloc(entry->declen+1); // +1 for resnametable zero-termination
  349. if( entry->type & FILELIST_TYPE_FILE )
  350. {// file
  351. uLongf len;
  352. grf_decode(buf, fsize, entry->type, entry->srclen);
  353. len = entry->declen;
  354. decode_zip(buf2, &len, buf, entry->srclen);
  355. if (len != (uLong)entry->declen) {
  356. ShowError("decode_zip size mismatch err: %d != %d\n", (int)len, entry->declen);
  357. aFree(buf);
  358. aFree(buf2);
  359. return nullptr;
  360. }
  361. } else {// directory?
  362. memcpy(buf2, buf, entry->declen);
  363. }
  364. if( size )
  365. *size = entry->declen;
  366. aFree(buf);
  367. } else {
  368. ShowError("grfio_reads: %s not found (GRF file: %s)\n", fname, grfname);
  369. return nullptr;
  370. }
  371. }
  372. return buf2;
  373. }
  374. int32 grfio_read_rsw_water_level( const char* fname ){
  375. unsigned char* rsw = (unsigned char *)grfio_reads( fname );
  376. if( rsw == nullptr ){
  377. // Error already reported in grfio_read
  378. return RSW_NO_WATER;
  379. }
  380. if( strncmp( (char*)rsw, "GRSW", strlen( "GRSW" ) ) ){
  381. ShowError( "grfio_read_rsw_water_level: Invalid RSW signature in file %s\n", fname );
  382. aFree( rsw );
  383. return RSW_NO_WATER;
  384. }
  385. uint16 version = ( rsw[4] << 8 ) | rsw[5];
  386. if( version < 0x104 || version > 0x205 ){
  387. ShowError( "grfio_read_rsw_water_level: Unsupported RSW version 0x%04x in file %s\n", version, fname );
  388. aFree( rsw );
  389. return RSW_NO_WATER;
  390. }
  391. int32 level;
  392. if( version >= 0x205 ){
  393. level = (int32)*(float*)( rsw + 171 );
  394. } else if( version >= 0x202 ){
  395. level = (int32)*(float*)( rsw + 167 );
  396. }else{
  397. level = (int32)*(float*)( rsw + 166 );
  398. }
  399. aFree( rsw );
  400. return level;
  401. }
  402. /// Decodes encrypted filename from a version 01xx grf index.
  403. static char* decode_filename(unsigned char* buf, int len)
  404. {
  405. int lop;
  406. for(lop=0;lop<len;lop+=8) {
  407. NibbleSwap(&buf[lop],8);
  408. des_decrypt(&buf[lop],8);
  409. }
  410. return (char*)buf;
  411. }
  412. /// Compares file extension against known large file types.
  413. /// @return true if the file should undergo full mode 0 decryption, and true otherwise.
  414. static bool isFullEncrypt(const char* fname)
  415. {
  416. const char* ext = strrchr(fname, '.');
  417. if( ext != nullptr ) {
  418. static const char extensions[4][5] = { ".gnd", ".gat", ".act", ".str" };
  419. size_t i;
  420. for( i = 0; i < ARRAYLENGTH(extensions); ++i )
  421. if( strcmpi(ext, extensions[i]) == 0 )
  422. return false;
  423. }
  424. return true;
  425. }
  426. /// Loads all entries in the specified grf file into the filelist.
  427. /// @param gentry index of the grf file name in the gentry_table
  428. static int grfio_entryread(const char* grfname, int gentry)
  429. {
  430. long grf_size;
  431. unsigned char grf_header[0x2e];
  432. int entry,entrys,ofs,grf_version;
  433. unsigned char *grf_filelist;
  434. FILE* fp = fopen(grfname, "rb");
  435. if( fp == nullptr ) {
  436. ShowWarning("GRF data file not found: '%s'\n",grfname);
  437. return 1; // 1:not found error
  438. } else
  439. ShowInfo("GRF data file found: '%s'\n",grfname);
  440. fseek(fp,0,SEEK_END);
  441. grf_size = ftell(fp);
  442. fseek(fp,0,SEEK_SET);
  443. if(fread(grf_header,1,0x2e,fp) != 0x2e) { ShowError("Couldn't read all grf_header element of %s \n", grfname); }
  444. if( strcmp((const char*)grf_header,"Master of Magic") != 0 || fseek(fp,getlong(grf_header+0x1e),SEEK_CUR) != 0 ) {
  445. fclose(fp);
  446. ShowError("GRF %s read error\n", grfname);
  447. ShowError("GRF possibly over 2GB in size.\n");
  448. return 2; // 2:file format error
  449. }
  450. grf_version = getlong(grf_header+0x2a) >> 8;
  451. if( grf_version == 0x01 ) {// ****** Grf version 01xx ******
  452. size_t list_size = grf_size - ftell(fp);
  453. grf_filelist = (unsigned char *) aMalloc(list_size);
  454. if(fread(grf_filelist,1,list_size,fp) != list_size) { ShowError("Couldn't read all grf_filelist element of %s \n", grfname); }
  455. fclose(fp);
  456. entrys = getlong(grf_header+0x26) - getlong(grf_header+0x22) - 7;
  457. // Get an entry
  458. for( entry = 0, ofs = 0; entry < entrys; ++entry ) {
  459. FILELIST aentry;
  460. int ofs2 = ofs+getlong(grf_filelist+ofs)+4;
  461. unsigned char type = grf_filelist[ofs2+12];
  462. if( type & FILELIST_TYPE_FILE ) {
  463. char* fname = decode_filename(grf_filelist+ofs+6, grf_filelist[ofs]-6);
  464. int srclen = getlong(grf_filelist+ofs2+0) - getlong(grf_filelist+ofs2+8) - 715;
  465. if( strlen(fname) > sizeof(aentry.fn) - 1 ) {
  466. ShowFatalError("GRF file name %s is too long\n", fname);
  467. aFree(grf_filelist);
  468. exit(EXIT_FAILURE);
  469. }
  470. type |= ( isFullEncrypt(fname) ) ? FILELIST_TYPE_ENCRYPT_MIXED : FILELIST_TYPE_ENCRYPT_HEADER;
  471. aentry.srclen = srclen;
  472. aentry.srclen_aligned = getlong(grf_filelist+ofs2+4)-37579;
  473. aentry.declen = getlong(grf_filelist+ofs2+8);
  474. aentry.srcpos = getlong(grf_filelist+ofs2+13)+0x2e;
  475. aentry.type = type;
  476. safestrncpy(aentry.fn, fname, sizeof(aentry.fn));
  477. aentry.fnd = nullptr;
  478. #ifdef GRFIO_LOCAL
  479. aentry.gentry = -(gentry+1); // As Flag for making it a negative number carrying out the first time LocalFileCheck
  480. #else
  481. aentry.gentry = gentry+1; // With no first time LocalFileCheck
  482. #endif
  483. filelist_modify(&aentry);
  484. }
  485. ofs = ofs2 + 17;
  486. }
  487. aFree(grf_filelist);
  488. } else if( grf_version == 0x02 ) {// ****** Grf version 02xx ******
  489. unsigned char eheader[8];
  490. unsigned char *rBuf;
  491. uLongf rSize, eSize;
  492. if(fread(eheader,1,8,fp) != 8) ShowError("An error occured in fread while reading eheader buffer\n");
  493. rSize = getlong(eheader); // Read Size
  494. eSize = getlong(eheader+4); // Extend Size
  495. if( (long)rSize > grf_size-ftell(fp) ) {
  496. fclose(fp);
  497. ShowError("Illegal data format: GRF compress entry size\n");
  498. return 4;
  499. }
  500. rBuf = (unsigned char *)aMalloc(rSize); // Get a Read Size
  501. grf_filelist = (unsigned char *)aMalloc(eSize); // Get a Extend Size
  502. if(fread(rBuf,1,rSize,fp) != rSize) ShowError("An error occured in fread \n");
  503. fclose(fp);
  504. decode_zip(grf_filelist, &eSize, rBuf, rSize); // Decode function
  505. aFree(rBuf);
  506. entrys = getlong(grf_header+0x26) - 7;
  507. // Get an entry
  508. for( entry = 0, ofs = 0; entry < entrys; ++entry ) {
  509. FILELIST aentry;
  510. char* fname = (char*)(grf_filelist+ofs);
  511. int ofs2 = ofs + (int)strlen(fname)+1;
  512. int type = grf_filelist[ofs2+12];
  513. if( strlen(fname) > sizeof(aentry.fn)-1 ) {
  514. ShowFatalError("GRF file name %s is too long\n", fname);
  515. aFree(grf_filelist);
  516. exit(EXIT_FAILURE);
  517. }
  518. if( type & FILELIST_TYPE_FILE ) {// file
  519. aentry.srclen = getlong(grf_filelist+ofs2+0);
  520. aentry.srclen_aligned = getlong(grf_filelist+ofs2+4);
  521. aentry.declen = getlong(grf_filelist+ofs2+8);
  522. aentry.srcpos = getlong(grf_filelist+ofs2+13)+0x2e;
  523. aentry.type = type;
  524. safestrncpy(aentry.fn, fname, sizeof(aentry.fn));
  525. aentry.fnd = nullptr;
  526. #ifdef GRFIO_LOCAL
  527. aentry.gentry = -(gentry+1); // As Flag for making it a negative number carrying out the first time LocalFileCheck
  528. #else
  529. aentry.gentry = gentry+1; // With no first time LocalFileCheck
  530. #endif
  531. filelist_modify(&aentry);
  532. }
  533. ofs = ofs2 + 17;
  534. }
  535. aFree(grf_filelist);
  536. } else {// ****** Grf Other version ******
  537. fclose(fp);
  538. ShowError("GRF version %04x not supported\n",getlong(grf_header+0x2a));
  539. return 4;
  540. }
  541. filelist_compact(); // Unnecessary area release of filelist
  542. return 0; // 0:no error
  543. }
  544. static bool grfio_parse_restable_row(const char* row)
  545. {
  546. char w1[256], w2[256];
  547. char src[512], dst[512];
  548. char local[512];
  549. FILELIST* entry;
  550. if( sscanf(row, "%255[^#\r\n]#%255[^#\r\n]#", w1, w2) != 2 )
  551. return false;
  552. if( strstr(w2, ".gat") == nullptr && strstr(w2, ".rsw") == nullptr )
  553. return false; // we only need the maps' GAT and RSW files
  554. sprintf(src, "data\\%s", w1);
  555. sprintf(dst, "data\\%s", w2);
  556. entry = filelist_find(dst);
  557. if( entry != nullptr )
  558. {// alias for GRF resource
  559. FILELIST fentry;
  560. memcpy(&fentry, entry, sizeof(FILELIST));
  561. safestrncpy(fentry.fn, src, sizeof(fentry.fn));
  562. fentry.fnd = aStrdup(dst);
  563. filelist_modify(&fentry);
  564. return true;
  565. }
  566. grfio_localpath_create(local, sizeof(local), dst);
  567. if( exists(local) )
  568. {// alias for local resource
  569. FILELIST fentry;
  570. memset(&fentry, 0, sizeof(fentry));
  571. safestrncpy(fentry.fn, src, sizeof(fentry.fn));
  572. fentry.fnd = aStrdup(dst);
  573. filelist_modify(&fentry);
  574. return true;
  575. }
  576. return false;
  577. }
  578. /// Grfio Resource file check.
  579. static void grfio_resourcecheck(void)
  580. {
  581. char restable[256];
  582. char *buf;
  583. size_t size;
  584. FILE* fp;
  585. int i = 0;
  586. // read resnametable from data directory and return if successful
  587. grfio_localpath_create(restable, sizeof(restable), "data\\resnametable.txt");
  588. fp = fopen(restable, "rb");
  589. if( fp != nullptr )
  590. {
  591. char line[256];
  592. while( fgets(line, sizeof(line), fp) )
  593. {
  594. if( grfio_parse_restable_row(line) )
  595. ++i;
  596. }
  597. fclose(fp);
  598. ShowStatus("Done reading '" CL_WHITE "%d" CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", i, "resnametable.txt");
  599. return; // we're done here!
  600. }
  601. // read resnametable from loaded GRF's, only if it cannot be loaded from the data directory
  602. buf = (char *)grfio_reads("data\\resnametable.txt", &size);
  603. if( buf != nullptr )
  604. {
  605. char *ptr;
  606. buf[size] = '\0';
  607. ptr = buf;
  608. while( static_cast<size_t>( ptr - buf ) < size )
  609. {
  610. if( grfio_parse_restable_row(ptr) )
  611. ++i;
  612. ptr = strchr(ptr, '\n');
  613. if( ptr == nullptr ) break;
  614. ptr++;
  615. }
  616. aFree(buf);
  617. ShowStatus("Done reading '" CL_WHITE "%d" CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", i, "data\\resnametable.txt");
  618. return;
  619. }
  620. }
  621. /// Reads a grf file and adds it to the list.
  622. static int grfio_add(const char* fname)
  623. {
  624. if( gentry_entrys >= gentry_maxentry )
  625. {
  626. #define GENTRY_ADDS 4 // The number increment of gentry_table entries
  627. gentry_maxentry += GENTRY_ADDS;
  628. gentry_table = (char**)aRealloc(gentry_table, gentry_maxentry * sizeof(char*));
  629. memset(gentry_table + (gentry_maxentry - GENTRY_ADDS), 0, sizeof(char*) * GENTRY_ADDS);
  630. }
  631. gentry_table[gentry_entrys++] = aStrdup(fname);
  632. return grfio_entryread(fname, gentry_entrys - 1);
  633. }
  634. /// Finalizes grfio.
  635. void grfio_final(void)
  636. {
  637. if (filelist != nullptr) {
  638. int i;
  639. for (i = 0; i < filelist_entrys; i++)
  640. if (filelist[i].fnd != nullptr)
  641. aFree(filelist[i].fnd);
  642. aFree(filelist);
  643. filelist = nullptr;
  644. }
  645. filelist_entrys = filelist_maxentry = 0;
  646. if (gentry_table != nullptr) {
  647. int i;
  648. for (i = 0; i < gentry_entrys; i++)
  649. if (gentry_table[i] != nullptr)
  650. aFree(gentry_table[i]);
  651. aFree(gentry_table);
  652. gentry_table = nullptr;
  653. }
  654. gentry_entrys = gentry_maxentry = 0;
  655. }
  656. /// Initializes grfio.
  657. void grfio_init(const char* fname)
  658. {
  659. FILE* data_conf;
  660. int grf_num = 0;
  661. hashinit(); // hash table initialization
  662. data_conf = fopen(fname, "r");
  663. if( data_conf != nullptr )
  664. {
  665. char line[1024];
  666. while( fgets(line, sizeof(line), data_conf) )
  667. {
  668. char w1[1024], w2[1024];
  669. if( line[0] == '/' && line[1] == '/' )
  670. continue; // skip comments
  671. if( sscanf(line, "%1023[^:]: %1023[^\r\n]", w1, w2) != 2 )
  672. continue; // skip unrecognized lines
  673. // Entry table reading
  674. if( strcmp(w1, "grf") == 0 ) // GRF file
  675. {
  676. if( grfio_add(w2) == 0 )
  677. ++grf_num;
  678. }
  679. else if( strcmp(w1,"data_dir") == 0 ) // Data directory
  680. {
  681. safestrncpy(data_dir, w2, sizeof(data_dir));
  682. }
  683. }
  684. fclose(data_conf);
  685. ShowStatus("Done reading '" CL_WHITE "%s" CL_RESET "'.\n", fname);
  686. }
  687. if( grf_num == 0 )
  688. ShowInfo("No GRF loaded, using default data directory\n");
  689. // Unneccessary area release of filelist
  690. filelist_compact();
  691. // Resource check
  692. grfio_resourcecheck();
  693. }