archive_read_support_format_lha.c 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915
  1. /*-
  2. * Copyright (c) 2008-2014 Michihiro NAKAJIMA
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
  15. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  16. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  17. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
  18. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  19. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  20. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  23. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #include "archive_platform.h"
  26. #ifdef HAVE_ERRNO_H
  27. #include <errno.h>
  28. #endif
  29. #ifdef HAVE_LIMITS_H
  30. #include <limits.h>
  31. #endif
  32. #ifdef HAVE_STDLIB_H
  33. #include <stdlib.h>
  34. #endif
  35. #ifdef HAVE_STRING_H
  36. #include <string.h>
  37. #endif
  38. #include "archive.h"
  39. #include "archive_entry.h"
  40. #include "archive_entry_locale.h"
  41. #include "archive_private.h"
  42. #include "archive_read_private.h"
  43. #include "archive_endian.h"
  44. #define MAXMATCH 256 /* Maximum match length. */
  45. #define MINMATCH 3 /* Minimum match length. */
  46. /*
  47. * Literal table format:
  48. * +0 +256 +510
  49. * +---------------+-------------------------+
  50. * | literal code | match length |
  51. * | 0 ... 255 | MINMATCH ... MAXMATCH |
  52. * +---------------+-------------------------+
  53. * <--- LT_BITLEN_SIZE --->
  54. */
  55. /* Literal table size. */
  56. #define LT_BITLEN_SIZE (UCHAR_MAX + 1 + MAXMATCH - MINMATCH + 1)
  57. /* Position table size.
  58. * Note: this used for both position table and pre literal table.*/
  59. #define PT_BITLEN_SIZE (3 + 16)
  60. struct lzh_dec {
  61. /* Decoding status. */
  62. int state;
  63. /*
  64. * Window to see last 8Ki(lh5),32Ki(lh6),64Ki(lh7) bytes of decoded
  65. * data.
  66. */
  67. int w_size;
  68. int w_mask;
  69. /* Window buffer, which is a loop buffer. */
  70. unsigned char *w_buff;
  71. /* The insert position to the window. */
  72. int w_pos;
  73. /* The position where we can copy decoded code from the window. */
  74. int copy_pos;
  75. /* The length how many bytes we can copy decoded code from
  76. * the window. */
  77. int copy_len;
  78. /*
  79. * Bit stream reader.
  80. */
  81. struct lzh_br {
  82. #define CACHE_TYPE uint64_t
  83. #define CACHE_BITS (8 * sizeof(CACHE_TYPE))
  84. /* Cache buffer. */
  85. CACHE_TYPE cache_buffer;
  86. /* Indicates how many bits avail in cache_buffer. */
  87. int cache_avail;
  88. } br;
  89. /*
  90. * Huffman coding.
  91. */
  92. struct huffman {
  93. int len_size;
  94. int len_avail;
  95. int len_bits;
  96. int freq[17];
  97. unsigned char *bitlen;
  98. /*
  99. * Use a index table. It's faster than searching a huffman
  100. * coding tree, which is a binary tree. But a use of a large
  101. * index table causes L1 cache read miss many times.
  102. */
  103. #define HTBL_BITS 10
  104. int max_bits;
  105. int shift_bits;
  106. int tbl_bits;
  107. int tree_used;
  108. int tree_avail;
  109. /* Direct access table. */
  110. uint16_t *tbl;
  111. /* Binary tree table for extra bits over the direct access. */
  112. struct htree_t {
  113. uint16_t left;
  114. uint16_t right;
  115. } *tree;
  116. } lt, pt;
  117. int blocks_avail;
  118. int pos_pt_len_size;
  119. int pos_pt_len_bits;
  120. int literal_pt_len_size;
  121. int literal_pt_len_bits;
  122. int reading_position;
  123. int loop;
  124. int error;
  125. };
  126. struct lzh_stream {
  127. const unsigned char *next_in;
  128. int avail_in;
  129. int64_t total_in;
  130. const unsigned char *ref_ptr;
  131. int avail_out;
  132. int64_t total_out;
  133. struct lzh_dec *ds;
  134. };
  135. struct lha {
  136. /* entry_bytes_remaining is the number of bytes we expect. */
  137. int64_t entry_offset;
  138. int64_t entry_bytes_remaining;
  139. int64_t entry_unconsumed;
  140. uint16_t entry_crc_calculated;
  141. size_t header_size; /* header size */
  142. unsigned char level; /* header level */
  143. char method[3]; /* compress type */
  144. int64_t compsize; /* compressed data size */
  145. int64_t origsize; /* original file size */
  146. int setflag;
  147. #define BIRTHTIME_IS_SET 1
  148. #define ATIME_IS_SET 2
  149. #define UNIX_MODE_IS_SET 4
  150. #define CRC_IS_SET 8
  151. time_t birthtime;
  152. long birthtime_tv_nsec;
  153. time_t mtime;
  154. long mtime_tv_nsec;
  155. time_t atime;
  156. long atime_tv_nsec;
  157. mode_t mode;
  158. int64_t uid;
  159. int64_t gid;
  160. struct archive_string uname;
  161. struct archive_string gname;
  162. uint16_t header_crc;
  163. uint16_t crc;
  164. /* dirname and filename could be in different codepages */
  165. struct archive_string_conv *sconv_dir;
  166. struct archive_string_conv *sconv_fname;
  167. struct archive_string_conv *opt_sconv;
  168. struct archive_string dirname;
  169. struct archive_string filename;
  170. struct archive_wstring ws;
  171. unsigned char dos_attr;
  172. /* Flag to mark progress that an archive was read their first header.*/
  173. char found_first_header;
  174. /* Flag to mark that indicates an empty directory. */
  175. char directory;
  176. /* Flags to mark progress of decompression. */
  177. char decompress_init;
  178. char end_of_entry;
  179. char end_of_entry_cleanup;
  180. char entry_is_compressed;
  181. char format_name[64];
  182. struct lzh_stream strm;
  183. };
  184. /*
  185. * LHA header common member offset.
  186. */
  187. #define H_METHOD_OFFSET 2 /* Compress type. */
  188. #define H_ATTR_OFFSET 19 /* DOS attribute. */
  189. #define H_LEVEL_OFFSET 20 /* Header Level. */
  190. #define H_SIZE 22 /* Minimum header size. */
  191. static int archive_read_format_lha_bid(struct archive_read *, int);
  192. static int archive_read_format_lha_options(struct archive_read *,
  193. const char *, const char *);
  194. static int archive_read_format_lha_read_header(struct archive_read *,
  195. struct archive_entry *);
  196. static int archive_read_format_lha_read_data(struct archive_read *,
  197. const void **, size_t *, int64_t *);
  198. static int archive_read_format_lha_read_data_skip(struct archive_read *);
  199. static int archive_read_format_lha_cleanup(struct archive_read *);
  200. static void lha_replace_path_separator(struct lha *,
  201. struct archive_entry *);
  202. static int lha_read_file_header_0(struct archive_read *, struct lha *);
  203. static int lha_read_file_header_1(struct archive_read *, struct lha *);
  204. static int lha_read_file_header_2(struct archive_read *, struct lha *);
  205. static int lha_read_file_header_3(struct archive_read *, struct lha *);
  206. static int lha_read_file_extended_header(struct archive_read *,
  207. struct lha *, uint16_t *, int, size_t, size_t *);
  208. static size_t lha_check_header_format(const void *);
  209. static int lha_skip_sfx(struct archive_read *);
  210. static time_t lha_dos_time(const unsigned char *);
  211. static time_t lha_win_time(uint64_t, long *);
  212. static unsigned char lha_calcsum(unsigned char, const void *,
  213. int, size_t);
  214. static int lha_parse_linkname(struct archive_wstring *,
  215. struct archive_wstring *);
  216. static int lha_read_data_none(struct archive_read *, const void **,
  217. size_t *, int64_t *);
  218. static int lha_read_data_lzh(struct archive_read *, const void **,
  219. size_t *, int64_t *);
  220. static void lha_crc16_init(void);
  221. static uint16_t lha_crc16(uint16_t, const void *, size_t);
  222. static int lzh_decode_init(struct lzh_stream *, const char *);
  223. static void lzh_decode_free(struct lzh_stream *);
  224. static int lzh_decode(struct lzh_stream *, int);
  225. static int lzh_br_fillup(struct lzh_stream *, struct lzh_br *);
  226. static int lzh_huffman_init(struct huffman *, size_t, int);
  227. static void lzh_huffman_free(struct huffman *);
  228. static int lzh_read_pt_bitlen(struct lzh_stream *, int start, int end);
  229. static int lzh_make_fake_table(struct huffman *, uint16_t);
  230. static int lzh_make_huffman_table(struct huffman *);
  231. static inline int lzh_decode_huffman(struct huffman *, unsigned);
  232. static int lzh_decode_huffman_tree(struct huffman *, unsigned, int);
  233. int
  234. archive_read_support_format_lha(struct archive *_a)
  235. {
  236. struct archive_read *a = (struct archive_read *)_a;
  237. struct lha *lha;
  238. int r;
  239. archive_check_magic(_a, ARCHIVE_READ_MAGIC,
  240. ARCHIVE_STATE_NEW, "archive_read_support_format_lha");
  241. lha = (struct lha *)calloc(1, sizeof(*lha));
  242. if (lha == NULL) {
  243. archive_set_error(&a->archive, ENOMEM,
  244. "Can't allocate lha data");
  245. return (ARCHIVE_FATAL);
  246. }
  247. archive_string_init(&lha->ws);
  248. r = __archive_read_register_format(a,
  249. lha,
  250. "lha",
  251. archive_read_format_lha_bid,
  252. archive_read_format_lha_options,
  253. archive_read_format_lha_read_header,
  254. archive_read_format_lha_read_data,
  255. archive_read_format_lha_read_data_skip,
  256. NULL,
  257. archive_read_format_lha_cleanup,
  258. NULL,
  259. NULL);
  260. if (r != ARCHIVE_OK)
  261. free(lha);
  262. return (ARCHIVE_OK);
  263. }
  264. static size_t
  265. lha_check_header_format(const void *h)
  266. {
  267. const unsigned char *p = h;
  268. size_t next_skip_bytes;
  269. switch (p[H_METHOD_OFFSET+3]) {
  270. /*
  271. * "-lh0-" ... "-lh7-" "-lhd-"
  272. * "-lzs-" "-lz5-"
  273. */
  274. case '0': case '1': case '2': case '3':
  275. case '4': case '5': case '6': case '7':
  276. case 'd':
  277. case 's':
  278. next_skip_bytes = 4;
  279. /* b0 == 0 means the end of an LHa archive file. */
  280. if (p[0] == 0)
  281. break;
  282. if (p[H_METHOD_OFFSET] != '-' || p[H_METHOD_OFFSET+1] != 'l'
  283. || p[H_METHOD_OFFSET+4] != '-')
  284. break;
  285. if (p[H_METHOD_OFFSET+2] == 'h') {
  286. /* "-lh?-" */
  287. if (p[H_METHOD_OFFSET+3] == 's')
  288. break;
  289. if (p[H_LEVEL_OFFSET] == 0)
  290. return (0);
  291. if (p[H_LEVEL_OFFSET] <= 3 && p[H_ATTR_OFFSET] == 0x20)
  292. return (0);
  293. }
  294. if (p[H_METHOD_OFFSET+2] == 'z') {
  295. /* LArc extensions: -lzs-,-lz4- and -lz5- */
  296. if (p[H_LEVEL_OFFSET] != 0)
  297. break;
  298. if (p[H_METHOD_OFFSET+3] == 's'
  299. || p[H_METHOD_OFFSET+3] == '4'
  300. || p[H_METHOD_OFFSET+3] == '5')
  301. return (0);
  302. }
  303. break;
  304. case 'h': next_skip_bytes = 1; break;
  305. case 'z': next_skip_bytes = 1; break;
  306. case 'l': next_skip_bytes = 2; break;
  307. case '-': next_skip_bytes = 3; break;
  308. default : next_skip_bytes = 4; break;
  309. }
  310. return (next_skip_bytes);
  311. }
  312. static int
  313. archive_read_format_lha_bid(struct archive_read *a, int best_bid)
  314. {
  315. const char *p;
  316. const void *buff;
  317. ssize_t bytes_avail, offset, window;
  318. size_t next;
  319. /* If there's already a better bid than we can ever
  320. make, don't bother testing. */
  321. if (best_bid > 30)
  322. return (-1);
  323. if ((p = __archive_read_ahead(a, H_SIZE, NULL)) == NULL)
  324. return (-1);
  325. if (lha_check_header_format(p) == 0)
  326. return (30);
  327. if (p[0] == 'M' && p[1] == 'Z') {
  328. /* PE file */
  329. offset = 0;
  330. window = 4096;
  331. while (offset < (1024 * 20)) {
  332. buff = __archive_read_ahead(a, offset + window,
  333. &bytes_avail);
  334. if (buff == NULL) {
  335. /* Remaining bytes are less than window. */
  336. window >>= 1;
  337. if (window < (H_SIZE + 3))
  338. return (0);
  339. continue;
  340. }
  341. p = (const char *)buff + offset;
  342. while (p + H_SIZE < (const char *)buff + bytes_avail) {
  343. if ((next = lha_check_header_format(p)) == 0)
  344. return (30);
  345. p += next;
  346. }
  347. offset = p - (const char *)buff;
  348. }
  349. }
  350. return (0);
  351. }
  352. static int
  353. archive_read_format_lha_options(struct archive_read *a,
  354. const char *key, const char *val)
  355. {
  356. struct lha *lha;
  357. int ret = ARCHIVE_FAILED;
  358. lha = (struct lha *)(a->format->data);
  359. if (strcmp(key, "hdrcharset") == 0) {
  360. if (val == NULL || val[0] == 0)
  361. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  362. "lha: hdrcharset option needs a character-set name");
  363. else {
  364. lha->opt_sconv =
  365. archive_string_conversion_from_charset(
  366. &a->archive, val, 0);
  367. if (lha->opt_sconv != NULL)
  368. ret = ARCHIVE_OK;
  369. else
  370. ret = ARCHIVE_FATAL;
  371. }
  372. return (ret);
  373. }
  374. /* Note: The "warn" return is just to inform the options
  375. * supervisor that we didn't handle it. It will generate
  376. * a suitable error if no one used this option. */
  377. return (ARCHIVE_WARN);
  378. }
  379. static int
  380. lha_skip_sfx(struct archive_read *a)
  381. {
  382. const void *h;
  383. const char *p, *q;
  384. size_t next, skip;
  385. ssize_t bytes, window;
  386. window = 4096;
  387. for (;;) {
  388. h = __archive_read_ahead(a, window, &bytes);
  389. if (h == NULL) {
  390. /* Remaining bytes are less than window. */
  391. window >>= 1;
  392. if (window < (H_SIZE + 3))
  393. goto fatal;
  394. continue;
  395. }
  396. if (bytes < H_SIZE)
  397. goto fatal;
  398. p = h;
  399. q = p + bytes;
  400. /*
  401. * Scan ahead until we find something that looks
  402. * like the lha header.
  403. */
  404. while (p + H_SIZE < q) {
  405. if ((next = lha_check_header_format(p)) == 0) {
  406. skip = p - (const char *)h;
  407. __archive_read_consume(a, skip);
  408. return (ARCHIVE_OK);
  409. }
  410. p += next;
  411. }
  412. skip = p - (const char *)h;
  413. __archive_read_consume(a, skip);
  414. }
  415. fatal:
  416. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  417. "Couldn't find out LHa header");
  418. return (ARCHIVE_FATAL);
  419. }
  420. static int
  421. truncated_error(struct archive_read *a)
  422. {
  423. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  424. "Truncated LHa header");
  425. return (ARCHIVE_FATAL);
  426. }
  427. static int
  428. archive_read_format_lha_read_header(struct archive_read *a,
  429. struct archive_entry *entry)
  430. {
  431. struct archive_wstring linkname;
  432. struct archive_wstring pathname;
  433. struct lha *lha;
  434. const unsigned char *p;
  435. const char *signature;
  436. int err;
  437. struct archive_mstring conv_buffer;
  438. const wchar_t *conv_buffer_p;
  439. lha_crc16_init();
  440. a->archive.archive_format = ARCHIVE_FORMAT_LHA;
  441. if (a->archive.archive_format_name == NULL)
  442. a->archive.archive_format_name = "lha";
  443. lha = (struct lha *)(a->format->data);
  444. lha->decompress_init = 0;
  445. lha->end_of_entry = 0;
  446. lha->end_of_entry_cleanup = 0;
  447. lha->entry_unconsumed = 0;
  448. if ((p = __archive_read_ahead(a, H_SIZE, NULL)) == NULL) {
  449. /*
  450. * LHa archiver added 0 to the tail of its archive file as
  451. * the mark of the end of the archive.
  452. */
  453. signature = __archive_read_ahead(a, sizeof(signature[0]), NULL);
  454. if (signature == NULL || signature[0] == 0)
  455. return (ARCHIVE_EOF);
  456. return (truncated_error(a));
  457. }
  458. signature = (const char *)p;
  459. if (lha->found_first_header == 0 &&
  460. signature[0] == 'M' && signature[1] == 'Z') {
  461. /* This is an executable? Must be self-extracting... */
  462. err = lha_skip_sfx(a);
  463. if (err < ARCHIVE_WARN)
  464. return (err);
  465. if ((p = __archive_read_ahead(a, sizeof(*p), NULL)) == NULL)
  466. return (truncated_error(a));
  467. signature = (const char *)p;
  468. }
  469. /* signature[0] == 0 means the end of an LHa archive file. */
  470. if (signature[0] == 0)
  471. return (ARCHIVE_EOF);
  472. /*
  473. * Check the header format and method type.
  474. */
  475. if (lha_check_header_format(p) != 0) {
  476. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  477. "Bad LHa file");
  478. return (ARCHIVE_FATAL);
  479. }
  480. /* We've found the first header. */
  481. lha->found_first_header = 1;
  482. /* Set a default value and common data */
  483. lha->header_size = 0;
  484. lha->level = p[H_LEVEL_OFFSET];
  485. lha->method[0] = p[H_METHOD_OFFSET+1];
  486. lha->method[1] = p[H_METHOD_OFFSET+2];
  487. lha->method[2] = p[H_METHOD_OFFSET+3];
  488. if (memcmp(lha->method, "lhd", 3) == 0)
  489. lha->directory = 1;
  490. else
  491. lha->directory = 0;
  492. if (memcmp(lha->method, "lh0", 3) == 0 ||
  493. memcmp(lha->method, "lz4", 3) == 0)
  494. lha->entry_is_compressed = 0;
  495. else
  496. lha->entry_is_compressed = 1;
  497. lha->compsize = 0;
  498. lha->origsize = 0;
  499. lha->setflag = 0;
  500. lha->birthtime = 0;
  501. lha->birthtime_tv_nsec = 0;
  502. lha->mtime = 0;
  503. lha->mtime_tv_nsec = 0;
  504. lha->atime = 0;
  505. lha->atime_tv_nsec = 0;
  506. lha->mode = (lha->directory)? 0777 : 0666;
  507. lha->uid = 0;
  508. lha->gid = 0;
  509. archive_string_empty(&lha->dirname);
  510. archive_string_empty(&lha->filename);
  511. lha->dos_attr = 0;
  512. if (lha->opt_sconv != NULL) {
  513. lha->sconv_dir = lha->opt_sconv;
  514. lha->sconv_fname = lha->opt_sconv;
  515. } else {
  516. lha->sconv_dir = NULL;
  517. lha->sconv_fname = NULL;
  518. }
  519. switch (p[H_LEVEL_OFFSET]) {
  520. case 0:
  521. err = lha_read_file_header_0(a, lha);
  522. break;
  523. case 1:
  524. err = lha_read_file_header_1(a, lha);
  525. break;
  526. case 2:
  527. err = lha_read_file_header_2(a, lha);
  528. break;
  529. case 3:
  530. err = lha_read_file_header_3(a, lha);
  531. break;
  532. default:
  533. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  534. "Unsupported LHa header level %d", p[H_LEVEL_OFFSET]);
  535. err = ARCHIVE_FATAL;
  536. break;
  537. }
  538. if (err < ARCHIVE_WARN)
  539. return (err);
  540. if (!lha->directory && archive_strlen(&lha->filename) == 0)
  541. /* The filename has not been set */
  542. return (truncated_error(a));
  543. /*
  544. * Make a pathname from a dirname and a filename, after converting to Unicode.
  545. * This is because codepages might differ between dirname and filename.
  546. */
  547. archive_string_init(&pathname);
  548. archive_string_init(&linkname);
  549. archive_string_init(&conv_buffer.aes_mbs);
  550. archive_string_init(&conv_buffer.aes_mbs_in_locale);
  551. archive_string_init(&conv_buffer.aes_utf8);
  552. archive_string_init(&conv_buffer.aes_wcs);
  553. if (0 != archive_mstring_copy_mbs_len_l(&conv_buffer, lha->dirname.s, lha->dirname.length, lha->sconv_dir)) {
  554. archive_set_error(&a->archive,
  555. ARCHIVE_ERRNO_FILE_FORMAT,
  556. "Pathname cannot be converted "
  557. "from %s to Unicode.",
  558. archive_string_conversion_charset_name(lha->sconv_dir));
  559. err = ARCHIVE_FATAL;
  560. } else if (0 != archive_mstring_get_wcs(&a->archive, &conv_buffer, &conv_buffer_p))
  561. err = ARCHIVE_FATAL;
  562. if (err == ARCHIVE_FATAL) {
  563. archive_mstring_clean(&conv_buffer);
  564. archive_wstring_free(&pathname);
  565. archive_wstring_free(&linkname);
  566. return (err);
  567. }
  568. archive_wstring_copy(&pathname, &conv_buffer.aes_wcs);
  569. archive_string_empty(&conv_buffer.aes_mbs);
  570. archive_string_empty(&conv_buffer.aes_mbs_in_locale);
  571. archive_string_empty(&conv_buffer.aes_utf8);
  572. archive_wstring_empty(&conv_buffer.aes_wcs);
  573. if (0 != archive_mstring_copy_mbs_len_l(&conv_buffer, lha->filename.s, lha->filename.length, lha->sconv_fname)) {
  574. archive_set_error(&a->archive,
  575. ARCHIVE_ERRNO_FILE_FORMAT,
  576. "Pathname cannot be converted "
  577. "from %s to Unicode.",
  578. archive_string_conversion_charset_name(lha->sconv_fname));
  579. err = ARCHIVE_FATAL;
  580. }
  581. else if (0 != archive_mstring_get_wcs(&a->archive, &conv_buffer, &conv_buffer_p))
  582. err = ARCHIVE_FATAL;
  583. if (err == ARCHIVE_FATAL) {
  584. archive_mstring_clean(&conv_buffer);
  585. archive_wstring_free(&pathname);
  586. archive_wstring_free(&linkname);
  587. return (err);
  588. }
  589. archive_wstring_concat(&pathname, &conv_buffer.aes_wcs);
  590. archive_mstring_clean(&conv_buffer);
  591. if ((lha->mode & AE_IFMT) == AE_IFLNK) {
  592. /*
  593. * Extract the symlink-name if it's included in the pathname.
  594. */
  595. if (!lha_parse_linkname(&linkname, &pathname)) {
  596. /* We couldn't get the symlink-name. */
  597. archive_set_error(&a->archive,
  598. ARCHIVE_ERRNO_FILE_FORMAT,
  599. "Unknown symlink-name");
  600. archive_wstring_free(&pathname);
  601. archive_wstring_free(&linkname);
  602. return (ARCHIVE_FAILED);
  603. }
  604. } else {
  605. /*
  606. * Make sure a file-type is set.
  607. * The mode has been overridden if it is in the extended data.
  608. */
  609. lha->mode = (lha->mode & ~AE_IFMT) |
  610. ((lha->directory)? AE_IFDIR: AE_IFREG);
  611. }
  612. if ((lha->setflag & UNIX_MODE_IS_SET) == 0 &&
  613. (lha->dos_attr & 1) != 0)
  614. lha->mode &= ~(0222);/* read only. */
  615. /*
  616. * Set basic file parameters.
  617. */
  618. archive_entry_copy_pathname_w(entry, pathname.s);
  619. archive_wstring_free(&pathname);
  620. if (archive_strlen(&linkname) > 0) {
  621. archive_entry_copy_symlink_w(entry, linkname.s);
  622. } else
  623. archive_entry_set_symlink(entry, NULL);
  624. archive_wstring_free(&linkname);
  625. /*
  626. * When a header level is 0, there is a possibility that
  627. * a pathname and a symlink has '\' character, a directory
  628. * separator in DOS/Windows. So we should convert it to '/'.
  629. */
  630. if (p[H_LEVEL_OFFSET] == 0)
  631. lha_replace_path_separator(lha, entry);
  632. archive_entry_set_mode(entry, lha->mode);
  633. archive_entry_set_uid(entry, lha->uid);
  634. archive_entry_set_gid(entry, lha->gid);
  635. if (archive_strlen(&lha->uname) > 0)
  636. archive_entry_set_uname(entry, lha->uname.s);
  637. if (archive_strlen(&lha->gname) > 0)
  638. archive_entry_set_gname(entry, lha->gname.s);
  639. if (lha->setflag & BIRTHTIME_IS_SET) {
  640. archive_entry_set_birthtime(entry, lha->birthtime,
  641. lha->birthtime_tv_nsec);
  642. archive_entry_set_ctime(entry, lha->birthtime,
  643. lha->birthtime_tv_nsec);
  644. } else {
  645. archive_entry_unset_birthtime(entry);
  646. archive_entry_unset_ctime(entry);
  647. }
  648. archive_entry_set_mtime(entry, lha->mtime, lha->mtime_tv_nsec);
  649. if (lha->setflag & ATIME_IS_SET)
  650. archive_entry_set_atime(entry, lha->atime,
  651. lha->atime_tv_nsec);
  652. else
  653. archive_entry_unset_atime(entry);
  654. if (lha->directory || archive_entry_symlink(entry) != NULL)
  655. archive_entry_unset_size(entry);
  656. else
  657. archive_entry_set_size(entry, lha->origsize);
  658. /*
  659. * Prepare variables used to read a file content.
  660. */
  661. lha->entry_bytes_remaining = lha->compsize;
  662. if (lha->entry_bytes_remaining < 0) {
  663. archive_set_error(&a->archive,
  664. ARCHIVE_ERRNO_FILE_FORMAT,
  665. "Invalid LHa entry size");
  666. return (ARCHIVE_FATAL);
  667. }
  668. lha->entry_offset = 0;
  669. lha->entry_crc_calculated = 0;
  670. /*
  671. * This file does not have a content.
  672. */
  673. if (lha->directory || lha->compsize == 0)
  674. lha->end_of_entry = 1;
  675. sprintf(lha->format_name, "lha -%c%c%c-",
  676. lha->method[0], lha->method[1], lha->method[2]);
  677. a->archive.archive_format_name = lha->format_name;
  678. return (err);
  679. }
  680. /*
  681. * Replace a DOS path separator '\' by a character '/'.
  682. * Some multi-byte character set have a character '\' in its second byte.
  683. */
  684. static void
  685. lha_replace_path_separator(struct lha *lha, struct archive_entry *entry)
  686. {
  687. const wchar_t *wp;
  688. size_t i;
  689. if ((wp = archive_entry_pathname_w(entry)) != NULL) {
  690. archive_wstrcpy(&(lha->ws), wp);
  691. for (i = 0; i < archive_strlen(&(lha->ws)); i++) {
  692. if (lha->ws.s[i] == L'\\')
  693. lha->ws.s[i] = L'/';
  694. }
  695. archive_entry_copy_pathname_w(entry, lha->ws.s);
  696. }
  697. if ((wp = archive_entry_symlink_w(entry)) != NULL) {
  698. archive_wstrcpy(&(lha->ws), wp);
  699. for (i = 0; i < archive_strlen(&(lha->ws)); i++) {
  700. if (lha->ws.s[i] == L'\\')
  701. lha->ws.s[i] = L'/';
  702. }
  703. archive_entry_copy_symlink_w(entry, lha->ws.s);
  704. }
  705. }
  706. /*
  707. * Header 0 format
  708. *
  709. * +0 +1 +2 +7 +11
  710. * +---------------+----------+----------------+-------------------+
  711. * |header size(*1)|header sum|compression type|compressed size(*2)|
  712. * +---------------+----------+----------------+-------------------+
  713. * <---------------------(*1)----------*
  714. *
  715. * +11 +15 +17 +19 +20 +21
  716. * +-----------------+---------+---------+--------------+----------------+
  717. * |uncompressed size|time(DOS)|date(DOS)|attribute(DOS)|header level(=0)|
  718. * +-----------------+---------+---------+--------------+----------------+
  719. * *--------------------------------(*1)---------------------------------*
  720. *
  721. * +21 +22 +22+(*3) +22+(*3)+2 +22+(*3)+2+(*4)
  722. * +---------------+---------+----------+----------------+------------------+
  723. * |name length(*3)|file name|file CRC16|extra header(*4)| compressed data |
  724. * +---------------+---------+----------+----------------+------------------+
  725. * <--(*3)-> <------(*2)------>
  726. * *----------------------(*1)-------------------------->
  727. *
  728. */
  729. #define H0_HEADER_SIZE_OFFSET 0
  730. #define H0_HEADER_SUM_OFFSET 1
  731. #define H0_COMP_SIZE_OFFSET 7
  732. #define H0_ORIG_SIZE_OFFSET 11
  733. #define H0_DOS_TIME_OFFSET 15
  734. #define H0_NAME_LEN_OFFSET 21
  735. #define H0_FILE_NAME_OFFSET 22
  736. #define H0_FIXED_SIZE 24
  737. static int
  738. lha_read_file_header_0(struct archive_read *a, struct lha *lha)
  739. {
  740. const unsigned char *p;
  741. int extdsize, namelen;
  742. unsigned char headersum, sum_calculated;
  743. if ((p = __archive_read_ahead(a, H0_FIXED_SIZE, NULL)) == NULL)
  744. return (truncated_error(a));
  745. lha->header_size = p[H0_HEADER_SIZE_OFFSET] + 2;
  746. headersum = p[H0_HEADER_SUM_OFFSET];
  747. lha->compsize = archive_le32dec(p + H0_COMP_SIZE_OFFSET);
  748. lha->origsize = archive_le32dec(p + H0_ORIG_SIZE_OFFSET);
  749. lha->mtime = lha_dos_time(p + H0_DOS_TIME_OFFSET);
  750. namelen = p[H0_NAME_LEN_OFFSET];
  751. extdsize = (int)lha->header_size - H0_FIXED_SIZE - namelen;
  752. if ((namelen > 221 || extdsize < 0) && extdsize != -2) {
  753. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  754. "Invalid LHa header");
  755. return (ARCHIVE_FATAL);
  756. }
  757. if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
  758. return (truncated_error(a));
  759. archive_strncpy(&lha->filename, p + H0_FILE_NAME_OFFSET, namelen);
  760. /* When extdsize == -2, A CRC16 value is not present in the header. */
  761. if (extdsize >= 0) {
  762. lha->crc = archive_le16dec(p + H0_FILE_NAME_OFFSET + namelen);
  763. lha->setflag |= CRC_IS_SET;
  764. }
  765. sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
  766. /* Read an extended header */
  767. if (extdsize > 0) {
  768. /* This extended data is set by 'LHa for UNIX' only.
  769. * Maybe fixed size.
  770. */
  771. p += H0_FILE_NAME_OFFSET + namelen + 2;
  772. if (p[0] == 'U' && extdsize == 12) {
  773. /* p[1] is a minor version. */
  774. lha->mtime = archive_le32dec(&p[2]);
  775. lha->mode = archive_le16dec(&p[6]);
  776. lha->uid = archive_le16dec(&p[8]);
  777. lha->gid = archive_le16dec(&p[10]);
  778. lha->setflag |= UNIX_MODE_IS_SET;
  779. }
  780. }
  781. __archive_read_consume(a, lha->header_size);
  782. if (sum_calculated != headersum) {
  783. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  784. "LHa header sum error");
  785. return (ARCHIVE_FATAL);
  786. }
  787. return (ARCHIVE_OK);
  788. }
  789. /*
  790. * Header 1 format
  791. *
  792. * +0 +1 +2 +7 +11
  793. * +---------------+----------+----------------+-------------+
  794. * |header size(*1)|header sum|compression type|skip size(*2)|
  795. * +---------------+----------+----------------+-------------+
  796. * <---------------(*1)----------*
  797. *
  798. * +11 +15 +17 +19 +20 +21
  799. * +-----------------+---------+---------+--------------+----------------+
  800. * |uncompressed size|time(DOS)|date(DOS)|attribute(DOS)|header level(=1)|
  801. * +-----------------+---------+---------+--------------+----------------+
  802. * *-------------------------------(*1)----------------------------------*
  803. *
  804. * +21 +22 +22+(*3) +22+(*3)+2 +22+(*3)+3 +22+(*3)+3+(*4)
  805. * +---------------+---------+----------+-----------+-----------+
  806. * |name length(*3)|file name|file CRC16| creator |padding(*4)|
  807. * +---------------+---------+----------+-----------+-----------+
  808. * <--(*3)->
  809. * *----------------------------(*1)----------------------------*
  810. *
  811. * +22+(*3)+3+(*4) +22+(*3)+3+(*4)+2 +22+(*3)+3+(*4)+2+(*5)
  812. * +----------------+---------------------+------------------------+
  813. * |next header size| extended header(*5) | compressed data |
  814. * +----------------+---------------------+------------------------+
  815. * *------(*1)-----> <--------------------(*2)-------------------->
  816. */
  817. #define H1_HEADER_SIZE_OFFSET 0
  818. #define H1_HEADER_SUM_OFFSET 1
  819. #define H1_COMP_SIZE_OFFSET 7
  820. #define H1_ORIG_SIZE_OFFSET 11
  821. #define H1_DOS_TIME_OFFSET 15
  822. #define H1_NAME_LEN_OFFSET 21
  823. #define H1_FILE_NAME_OFFSET 22
  824. #define H1_FIXED_SIZE 27
  825. static int
  826. lha_read_file_header_1(struct archive_read *a, struct lha *lha)
  827. {
  828. const unsigned char *p;
  829. size_t extdsize;
  830. int i, err, err2;
  831. int namelen, padding;
  832. unsigned char headersum, sum_calculated;
  833. err = ARCHIVE_OK;
  834. if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)
  835. return (truncated_error(a));
  836. lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;
  837. headersum = p[H1_HEADER_SUM_OFFSET];
  838. /* Note: An extended header size is included in a compsize. */
  839. lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);
  840. lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);
  841. lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);
  842. namelen = p[H1_NAME_LEN_OFFSET];
  843. /* Calculate a padding size. The result will be normally 0 only(?) */
  844. padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;
  845. if (namelen > 230 || padding < 0)
  846. goto invalid;
  847. if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
  848. return (truncated_error(a));
  849. for (i = 0; i < namelen; i++) {
  850. if (p[i + H1_FILE_NAME_OFFSET] == 0xff)
  851. goto invalid;/* Invalid filename. */
  852. }
  853. archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);
  854. lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);
  855. lha->setflag |= CRC_IS_SET;
  856. sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
  857. /* Consume used bytes but not include `next header size' data
  858. * since it will be consumed in lha_read_file_extended_header(). */
  859. __archive_read_consume(a, lha->header_size - 2);
  860. /* Read extended headers */
  861. err2 = lha_read_file_extended_header(a, lha, NULL, 2,
  862. (size_t)(lha->compsize + 2), &extdsize);
  863. if (err2 < ARCHIVE_WARN)
  864. return (err2);
  865. if (err2 < err)
  866. err = err2;
  867. /* Get a real compressed file size. */
  868. lha->compsize -= extdsize - 2;
  869. if (lha->compsize < 0)
  870. goto invalid; /* Invalid compressed file size */
  871. if (sum_calculated != headersum) {
  872. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  873. "LHa header sum error");
  874. return (ARCHIVE_FATAL);
  875. }
  876. return (err);
  877. invalid:
  878. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  879. "Invalid LHa header");
  880. return (ARCHIVE_FATAL);
  881. }
  882. /*
  883. * Header 2 format
  884. *
  885. * +0 +2 +7 +11 +15
  886. * +---------------+----------------+-------------------+-----------------+
  887. * |header size(*1)|compression type|compressed size(*2)|uncompressed size|
  888. * +---------------+----------------+-------------------+-----------------+
  889. * <--------------------------------(*1)---------------------------------*
  890. *
  891. * +15 +19 +20 +21 +23 +24
  892. * +-----------------+------------+----------------+----------+-----------+
  893. * |data/time(time_t)| 0x20 fixed |header level(=2)|file CRC16| creator |
  894. * +-----------------+------------+----------------+----------+-----------+
  895. * *---------------------------------(*1)---------------------------------*
  896. *
  897. * +24 +26 +26+(*3) +26+(*3)+(*4)
  898. * +----------------+-------------------+-------------+-------------------+
  899. * |next header size|extended header(*3)| padding(*4) | compressed data |
  900. * +----------------+-------------------+-------------+-------------------+
  901. * *--------------------------(*1)-------------------> <------(*2)------->
  902. *
  903. */
  904. #define H2_HEADER_SIZE_OFFSET 0
  905. #define H2_COMP_SIZE_OFFSET 7
  906. #define H2_ORIG_SIZE_OFFSET 11
  907. #define H2_TIME_OFFSET 15
  908. #define H2_CRC_OFFSET 21
  909. #define H2_FIXED_SIZE 24
  910. static int
  911. lha_read_file_header_2(struct archive_read *a, struct lha *lha)
  912. {
  913. const unsigned char *p;
  914. size_t extdsize;
  915. int err, padding;
  916. uint16_t header_crc;
  917. if ((p = __archive_read_ahead(a, H2_FIXED_SIZE, NULL)) == NULL)
  918. return (truncated_error(a));
  919. lha->header_size =archive_le16dec(p + H2_HEADER_SIZE_OFFSET);
  920. lha->compsize = archive_le32dec(p + H2_COMP_SIZE_OFFSET);
  921. lha->origsize = archive_le32dec(p + H2_ORIG_SIZE_OFFSET);
  922. lha->mtime = archive_le32dec(p + H2_TIME_OFFSET);
  923. lha->crc = archive_le16dec(p + H2_CRC_OFFSET);
  924. lha->setflag |= CRC_IS_SET;
  925. if (lha->header_size < H2_FIXED_SIZE) {
  926. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  927. "Invalid LHa header size");
  928. return (ARCHIVE_FATAL);
  929. }
  930. header_crc = lha_crc16(0, p, H2_FIXED_SIZE);
  931. __archive_read_consume(a, H2_FIXED_SIZE);
  932. /* Read extended headers */
  933. err = lha_read_file_extended_header(a, lha, &header_crc, 2,
  934. lha->header_size - H2_FIXED_SIZE, &extdsize);
  935. if (err < ARCHIVE_WARN)
  936. return (err);
  937. /* Calculate a padding size. The result will be normally 0 or 1. */
  938. padding = (int)lha->header_size - (int)(H2_FIXED_SIZE + extdsize);
  939. if (padding > 0) {
  940. if ((p = __archive_read_ahead(a, padding, NULL)) == NULL)
  941. return (truncated_error(a));
  942. header_crc = lha_crc16(header_crc, p, padding);
  943. __archive_read_consume(a, padding);
  944. }
  945. if (header_crc != lha->header_crc) {
  946. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  947. "LHa header CRC error");
  948. return (ARCHIVE_FATAL);
  949. }
  950. return (err);
  951. }
  952. /*
  953. * Header 3 format
  954. *
  955. * +0 +2 +7 +11 +15
  956. * +------------+----------------+-------------------+-----------------+
  957. * | 0x04 fixed |compression type|compressed size(*2)|uncompressed size|
  958. * +------------+----------------+-------------------+-----------------+
  959. * <-------------------------------(*1)-------------------------------*
  960. *
  961. * +15 +19 +20 +21 +23 +24
  962. * +-----------------+------------+----------------+----------+-----------+
  963. * |date/time(time_t)| 0x20 fixed |header level(=3)|file CRC16| creator |
  964. * +-----------------+------------+----------------+----------+-----------+
  965. * *--------------------------------(*1)----------------------------------*
  966. *
  967. * +24 +28 +32 +32+(*3)
  968. * +---------------+----------------+-------------------+-----------------+
  969. * |header size(*1)|next header size|extended header(*3)| compressed data |
  970. * +---------------+----------------+-------------------+-----------------+
  971. * *------------------------(*1)-----------------------> <------(*2)----->
  972. *
  973. */
  974. #define H3_FIELD_LEN_OFFSET 0
  975. #define H3_COMP_SIZE_OFFSET 7
  976. #define H3_ORIG_SIZE_OFFSET 11
  977. #define H3_TIME_OFFSET 15
  978. #define H3_CRC_OFFSET 21
  979. #define H3_HEADER_SIZE_OFFSET 24
  980. #define H3_FIXED_SIZE 28
  981. static int
  982. lha_read_file_header_3(struct archive_read *a, struct lha *lha)
  983. {
  984. const unsigned char *p;
  985. size_t extdsize;
  986. int err;
  987. uint16_t header_crc;
  988. if ((p = __archive_read_ahead(a, H3_FIXED_SIZE, NULL)) == NULL)
  989. return (truncated_error(a));
  990. if (archive_le16dec(p + H3_FIELD_LEN_OFFSET) != 4)
  991. goto invalid;
  992. lha->header_size =archive_le32dec(p + H3_HEADER_SIZE_OFFSET);
  993. lha->compsize = archive_le32dec(p + H3_COMP_SIZE_OFFSET);
  994. lha->origsize = archive_le32dec(p + H3_ORIG_SIZE_OFFSET);
  995. lha->mtime = archive_le32dec(p + H3_TIME_OFFSET);
  996. lha->crc = archive_le16dec(p + H3_CRC_OFFSET);
  997. lha->setflag |= CRC_IS_SET;
  998. if (lha->header_size < H3_FIXED_SIZE + 4)
  999. goto invalid;
  1000. header_crc = lha_crc16(0, p, H3_FIXED_SIZE);
  1001. __archive_read_consume(a, H3_FIXED_SIZE);
  1002. /* Read extended headers */
  1003. err = lha_read_file_extended_header(a, lha, &header_crc, 4,
  1004. lha->header_size - H3_FIXED_SIZE, &extdsize);
  1005. if (err < ARCHIVE_WARN)
  1006. return (err);
  1007. if (header_crc != lha->header_crc) {
  1008. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1009. "LHa header CRC error");
  1010. return (ARCHIVE_FATAL);
  1011. }
  1012. return (err);
  1013. invalid:
  1014. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1015. "Invalid LHa header");
  1016. return (ARCHIVE_FATAL);
  1017. }
  1018. /*
  1019. * Extended header format
  1020. *
  1021. * +0 +2 +3 -- used in header 1 and 2
  1022. * +0 +4 +5 -- used in header 3
  1023. * +--------------+---------+-------------------+--------------+--
  1024. * |ex-header size|header id| data |ex-header size| .......
  1025. * +--------------+---------+-------------------+--------------+--
  1026. * <-------------( ex-header size)------------> <-- next extended header --*
  1027. *
  1028. * If the ex-header size is zero, it is the make of the end of extended
  1029. * headers.
  1030. *
  1031. */
  1032. static int
  1033. lha_read_file_extended_header(struct archive_read *a, struct lha *lha,
  1034. uint16_t *crc, int sizefield_length, size_t limitsize, size_t *total_size)
  1035. {
  1036. const void *h;
  1037. const unsigned char *extdheader;
  1038. size_t extdsize;
  1039. size_t datasize;
  1040. unsigned int i;
  1041. unsigned char extdtype;
  1042. #define EXT_HEADER_CRC 0x00 /* Header CRC and information*/
  1043. #define EXT_FILENAME 0x01 /* Filename */
  1044. #define EXT_DIRECTORY 0x02 /* Directory name */
  1045. #define EXT_DOS_ATTR 0x40 /* MS-DOS attribute */
  1046. #define EXT_TIMESTAMP 0x41 /* Windows time stamp */
  1047. #define EXT_FILESIZE 0x42 /* Large file size */
  1048. #define EXT_TIMEZONE 0x43 /* Time zone */
  1049. #define EXT_UTF16_FILENAME 0x44 /* UTF-16 filename */
  1050. #define EXT_UTF16_DIRECTORY 0x45 /* UTF-16 directory name */
  1051. #define EXT_CODEPAGE 0x46 /* Codepage */
  1052. #define EXT_UNIX_MODE 0x50 /* File permission */
  1053. #define EXT_UNIX_GID_UID 0x51 /* gid,uid */
  1054. #define EXT_UNIX_GNAME 0x52 /* Group name */
  1055. #define EXT_UNIX_UNAME 0x53 /* User name */
  1056. #define EXT_UNIX_MTIME 0x54 /* Modified time */
  1057. #define EXT_OS2_NEW_ATTR 0x7f /* new attribute(OS/2 only) */
  1058. #define EXT_NEW_ATTR 0xff /* new attribute */
  1059. *total_size = sizefield_length;
  1060. for (;;) {
  1061. /* Read an extended header size. */
  1062. if ((h =
  1063. __archive_read_ahead(a, sizefield_length, NULL)) == NULL)
  1064. return (truncated_error(a));
  1065. /* Check if the size is the zero indicates the end of the
  1066. * extended header. */
  1067. if (sizefield_length == sizeof(uint16_t))
  1068. extdsize = archive_le16dec(h);
  1069. else
  1070. extdsize = archive_le32dec(h);
  1071. if (extdsize == 0) {
  1072. /* End of extended header */
  1073. if (crc != NULL)
  1074. *crc = lha_crc16(*crc, h, sizefield_length);
  1075. __archive_read_consume(a, sizefield_length);
  1076. return (ARCHIVE_OK);
  1077. }
  1078. /* Sanity check to the extended header size. */
  1079. if (((uint64_t)*total_size + extdsize) >
  1080. (uint64_t)limitsize ||
  1081. extdsize <= (size_t)sizefield_length)
  1082. goto invalid;
  1083. /* Read the extended header. */
  1084. if ((h = __archive_read_ahead(a, extdsize, NULL)) == NULL)
  1085. return (truncated_error(a));
  1086. *total_size += extdsize;
  1087. extdheader = (const unsigned char *)h;
  1088. /* Get the extended header type. */
  1089. extdtype = extdheader[sizefield_length];
  1090. /* Calculate an extended data size. */
  1091. datasize = extdsize - (1 + sizefield_length);
  1092. /* Skip an extended header size field and type field. */
  1093. extdheader += sizefield_length + 1;
  1094. if (crc != NULL && extdtype != EXT_HEADER_CRC)
  1095. *crc = lha_crc16(*crc, h, extdsize);
  1096. switch (extdtype) {
  1097. case EXT_HEADER_CRC:
  1098. /* We only use a header CRC. Following data will not
  1099. * be used. */
  1100. if (datasize >= 2) {
  1101. lha->header_crc = archive_le16dec(extdheader);
  1102. if (crc != NULL) {
  1103. static const char zeros[2] = {0, 0};
  1104. *crc = lha_crc16(*crc, h,
  1105. extdsize - datasize);
  1106. /* CRC value itself as zero */
  1107. *crc = lha_crc16(*crc, zeros, 2);
  1108. *crc = lha_crc16(*crc,
  1109. extdheader+2, datasize - 2);
  1110. }
  1111. }
  1112. break;
  1113. case EXT_FILENAME:
  1114. if (datasize == 0) {
  1115. /* maybe directory header */
  1116. archive_string_empty(&lha->filename);
  1117. break;
  1118. }
  1119. if (extdheader[0] == '\0')
  1120. goto invalid;
  1121. archive_strncpy(&lha->filename,
  1122. (const char *)extdheader, datasize);
  1123. break;
  1124. case EXT_UTF16_FILENAME:
  1125. if (datasize == 0) {
  1126. /* maybe directory header */
  1127. archive_string_empty(&lha->filename);
  1128. break;
  1129. } else if (datasize & 1) {
  1130. /* UTF-16 characters take always 2 or 4 bytes */
  1131. goto invalid;
  1132. }
  1133. if (extdheader[0] == '\0')
  1134. goto invalid;
  1135. archive_string_empty(&lha->filename);
  1136. archive_array_append(&lha->filename,
  1137. (const char *)extdheader, datasize);
  1138. /* Setup a string conversion for a filename. */
  1139. lha->sconv_fname =
  1140. archive_string_conversion_from_charset(&a->archive,
  1141. "UTF-16LE", 1);
  1142. if (lha->sconv_fname == NULL)
  1143. return (ARCHIVE_FATAL);
  1144. break;
  1145. case EXT_DIRECTORY:
  1146. if (datasize == 0 || extdheader[0] == '\0')
  1147. /* no directory name data. exit this case. */
  1148. goto invalid;
  1149. archive_strncpy(&lha->dirname,
  1150. (const char *)extdheader, datasize);
  1151. /*
  1152. * Convert directory delimiter from 0xFF
  1153. * to '/' for local system.
  1154. */
  1155. for (i = 0; i < lha->dirname.length; i++) {
  1156. if ((unsigned char)lha->dirname.s[i] == 0xFF)
  1157. lha->dirname.s[i] = '/';
  1158. }
  1159. /* Is last character directory separator? */
  1160. if (lha->dirname.s[lha->dirname.length-1] != '/')
  1161. /* invalid directory data */
  1162. goto invalid;
  1163. break;
  1164. case EXT_UTF16_DIRECTORY:
  1165. /* UTF-16 characters take always 2 or 4 bytes */
  1166. if (datasize == 0 || (datasize & 1) ||
  1167. extdheader[0] == '\0') {
  1168. /* no directory name data. exit this case. */
  1169. goto invalid;
  1170. }
  1171. archive_string_empty(&lha->dirname);
  1172. archive_array_append(&lha->dirname,
  1173. (const char *)extdheader, datasize);
  1174. lha->sconv_dir =
  1175. archive_string_conversion_from_charset(&a->archive,
  1176. "UTF-16LE", 1);
  1177. if (lha->sconv_dir == NULL)
  1178. return (ARCHIVE_FATAL);
  1179. else {
  1180. /*
  1181. * Convert directory delimiter from 0xFFFF
  1182. * to '/' for local system.
  1183. */
  1184. uint16_t dirSep;
  1185. uint16_t d = 1;
  1186. if (archive_be16dec(&d) == 1)
  1187. dirSep = 0x2F00;
  1188. else
  1189. dirSep = 0x002F;
  1190. /* UTF-16LE character */
  1191. uint16_t *utf16name =
  1192. (uint16_t *)lha->dirname.s;
  1193. for (i = 0; i < lha->dirname.length / 2; i++) {
  1194. if (utf16name[i] == 0xFFFF) {
  1195. utf16name[i] = dirSep;
  1196. }
  1197. }
  1198. /* Is last character directory separator? */
  1199. if (utf16name[lha->dirname.length / 2 - 1] !=
  1200. dirSep) {
  1201. /* invalid directory data */
  1202. goto invalid;
  1203. }
  1204. }
  1205. break;
  1206. case EXT_DOS_ATTR:
  1207. if (datasize == 2)
  1208. lha->dos_attr = (unsigned char)
  1209. (archive_le16dec(extdheader) & 0xff);
  1210. break;
  1211. case EXT_TIMESTAMP:
  1212. if (datasize == (sizeof(uint64_t) * 3)) {
  1213. lha->birthtime = lha_win_time(
  1214. archive_le64dec(extdheader),
  1215. &lha->birthtime_tv_nsec);
  1216. extdheader += sizeof(uint64_t);
  1217. lha->mtime = lha_win_time(
  1218. archive_le64dec(extdheader),
  1219. &lha->mtime_tv_nsec);
  1220. extdheader += sizeof(uint64_t);
  1221. lha->atime = lha_win_time(
  1222. archive_le64dec(extdheader),
  1223. &lha->atime_tv_nsec);
  1224. lha->setflag |= BIRTHTIME_IS_SET |
  1225. ATIME_IS_SET;
  1226. }
  1227. break;
  1228. case EXT_FILESIZE:
  1229. if (datasize == sizeof(uint64_t) * 2) {
  1230. lha->compsize = archive_le64dec(extdheader);
  1231. extdheader += sizeof(uint64_t);
  1232. lha->origsize = archive_le64dec(extdheader);
  1233. }
  1234. break;
  1235. case EXT_CODEPAGE:
  1236. /* Get an archived filename charset from codepage.
  1237. * This overwrites the charset specified by
  1238. * hdrcharset option. */
  1239. if (datasize == sizeof(uint32_t)) {
  1240. struct archive_string cp;
  1241. const char *charset;
  1242. archive_string_init(&cp);
  1243. switch (archive_le32dec(extdheader)) {
  1244. case 65001: /* UTF-8 */
  1245. charset = "UTF-8";
  1246. break;
  1247. default:
  1248. archive_string_sprintf(&cp, "CP%d",
  1249. (int)archive_le32dec(extdheader));
  1250. charset = cp.s;
  1251. break;
  1252. }
  1253. lha->sconv_dir =
  1254. archive_string_conversion_from_charset(
  1255. &(a->archive), charset, 1);
  1256. lha->sconv_fname =
  1257. archive_string_conversion_from_charset(
  1258. &(a->archive), charset, 1);
  1259. archive_string_free(&cp);
  1260. if (lha->sconv_dir == NULL)
  1261. return (ARCHIVE_FATAL);
  1262. if (lha->sconv_fname == NULL)
  1263. return (ARCHIVE_FATAL);
  1264. }
  1265. break;
  1266. case EXT_UNIX_MODE:
  1267. if (datasize == sizeof(uint16_t)) {
  1268. lha->mode = archive_le16dec(extdheader);
  1269. lha->setflag |= UNIX_MODE_IS_SET;
  1270. }
  1271. break;
  1272. case EXT_UNIX_GID_UID:
  1273. if (datasize == (sizeof(uint16_t) * 2)) {
  1274. lha->gid = archive_le16dec(extdheader);
  1275. lha->uid = archive_le16dec(extdheader+2);
  1276. }
  1277. break;
  1278. case EXT_UNIX_GNAME:
  1279. if (datasize > 0)
  1280. archive_strncpy(&lha->gname,
  1281. (const char *)extdheader, datasize);
  1282. break;
  1283. case EXT_UNIX_UNAME:
  1284. if (datasize > 0)
  1285. archive_strncpy(&lha->uname,
  1286. (const char *)extdheader, datasize);
  1287. break;
  1288. case EXT_UNIX_MTIME:
  1289. if (datasize == sizeof(uint32_t))
  1290. lha->mtime = archive_le32dec(extdheader);
  1291. break;
  1292. case EXT_OS2_NEW_ATTR:
  1293. /* This extended header is OS/2 depend. */
  1294. if (datasize == 16) {
  1295. lha->dos_attr = (unsigned char)
  1296. (archive_le16dec(extdheader) & 0xff);
  1297. lha->mode = archive_le16dec(extdheader+2);
  1298. lha->gid = archive_le16dec(extdheader+4);
  1299. lha->uid = archive_le16dec(extdheader+6);
  1300. lha->birthtime = archive_le32dec(extdheader+8);
  1301. lha->atime = archive_le32dec(extdheader+12);
  1302. lha->setflag |= UNIX_MODE_IS_SET
  1303. | BIRTHTIME_IS_SET | ATIME_IS_SET;
  1304. }
  1305. break;
  1306. case EXT_NEW_ATTR:
  1307. if (datasize == 20) {
  1308. lha->mode = (mode_t)archive_le32dec(extdheader);
  1309. lha->gid = archive_le32dec(extdheader+4);
  1310. lha->uid = archive_le32dec(extdheader+8);
  1311. lha->birthtime = archive_le32dec(extdheader+12);
  1312. lha->atime = archive_le32dec(extdheader+16);
  1313. lha->setflag |= UNIX_MODE_IS_SET
  1314. | BIRTHTIME_IS_SET | ATIME_IS_SET;
  1315. }
  1316. break;
  1317. case EXT_TIMEZONE: /* Not supported */
  1318. break;
  1319. default:
  1320. break;
  1321. }
  1322. __archive_read_consume(a, extdsize);
  1323. }
  1324. invalid:
  1325. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1326. "Invalid extended LHa header");
  1327. return (ARCHIVE_FATAL);
  1328. }
  1329. static int
  1330. lha_end_of_entry(struct archive_read *a)
  1331. {
  1332. struct lha *lha = (struct lha *)(a->format->data);
  1333. int r = ARCHIVE_EOF;
  1334. if (!lha->end_of_entry_cleanup) {
  1335. if ((lha->setflag & CRC_IS_SET) &&
  1336. lha->crc != lha->entry_crc_calculated) {
  1337. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1338. "LHa data CRC error");
  1339. r = ARCHIVE_WARN;
  1340. }
  1341. /* End-of-entry cleanup done. */
  1342. lha->end_of_entry_cleanup = 1;
  1343. }
  1344. return (r);
  1345. }
  1346. static int
  1347. archive_read_format_lha_read_data(struct archive_read *a,
  1348. const void **buff, size_t *size, int64_t *offset)
  1349. {
  1350. struct lha *lha = (struct lha *)(a->format->data);
  1351. int r;
  1352. if (lha->entry_unconsumed) {
  1353. /* Consume as much as the decompressor actually used. */
  1354. __archive_read_consume(a, lha->entry_unconsumed);
  1355. lha->entry_unconsumed = 0;
  1356. }
  1357. if (lha->end_of_entry) {
  1358. *offset = lha->entry_offset;
  1359. *size = 0;
  1360. *buff = NULL;
  1361. return (lha_end_of_entry(a));
  1362. }
  1363. if (lha->entry_is_compressed)
  1364. r = lha_read_data_lzh(a, buff, size, offset);
  1365. else
  1366. /* No compression. */
  1367. r = lha_read_data_none(a, buff, size, offset);
  1368. return (r);
  1369. }
  1370. /*
  1371. * Read a file content in no compression.
  1372. *
  1373. * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
  1374. * lha->end_of_entry if it consumes all of the data.
  1375. */
  1376. static int
  1377. lha_read_data_none(struct archive_read *a, const void **buff,
  1378. size_t *size, int64_t *offset)
  1379. {
  1380. struct lha *lha = (struct lha *)(a->format->data);
  1381. ssize_t bytes_avail;
  1382. if (lha->entry_bytes_remaining == 0) {
  1383. *buff = NULL;
  1384. *size = 0;
  1385. *offset = lha->entry_offset;
  1386. lha->end_of_entry = 1;
  1387. return (ARCHIVE_OK);
  1388. }
  1389. /*
  1390. * Note: '1' here is a performance optimization.
  1391. * Recall that the decompression layer returns a count of
  1392. * available bytes; asking for more than that forces the
  1393. * decompressor to combine reads by copying data.
  1394. */
  1395. *buff = __archive_read_ahead(a, 1, &bytes_avail);
  1396. if (bytes_avail <= 0) {
  1397. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1398. "Truncated LHa file data");
  1399. return (ARCHIVE_FATAL);
  1400. }
  1401. if (bytes_avail > lha->entry_bytes_remaining)
  1402. bytes_avail = (ssize_t)lha->entry_bytes_remaining;
  1403. lha->entry_crc_calculated =
  1404. lha_crc16(lha->entry_crc_calculated, *buff, bytes_avail);
  1405. *size = bytes_avail;
  1406. *offset = lha->entry_offset;
  1407. lha->entry_offset += bytes_avail;
  1408. lha->entry_bytes_remaining -= bytes_avail;
  1409. if (lha->entry_bytes_remaining == 0)
  1410. lha->end_of_entry = 1;
  1411. lha->entry_unconsumed = bytes_avail;
  1412. return (ARCHIVE_OK);
  1413. }
  1414. /*
  1415. * Read a file content in LZHUFF encoding.
  1416. *
  1417. * Returns ARCHIVE_OK if successful, returns ARCHIVE_WARN if compression is
  1418. * unsupported, ARCHIVE_FATAL otherwise, sets lha->end_of_entry if it consumes
  1419. * all of the data.
  1420. */
  1421. static int
  1422. lha_read_data_lzh(struct archive_read *a, const void **buff,
  1423. size_t *size, int64_t *offset)
  1424. {
  1425. struct lha *lha = (struct lha *)(a->format->data);
  1426. ssize_t bytes_avail;
  1427. int r;
  1428. /* If we haven't yet read any data, initialize the decompressor. */
  1429. if (!lha->decompress_init) {
  1430. r = lzh_decode_init(&(lha->strm), lha->method);
  1431. switch (r) {
  1432. case ARCHIVE_OK:
  1433. break;
  1434. case ARCHIVE_FAILED:
  1435. /* Unsupported compression. */
  1436. *buff = NULL;
  1437. *size = 0;
  1438. *offset = 0;
  1439. archive_set_error(&a->archive,
  1440. ARCHIVE_ERRNO_FILE_FORMAT,
  1441. "Unsupported lzh compression method -%c%c%c-",
  1442. lha->method[0], lha->method[1], lha->method[2]);
  1443. /* We know compressed size; just skip it. */
  1444. archive_read_format_lha_read_data_skip(a);
  1445. return (ARCHIVE_WARN);
  1446. default:
  1447. archive_set_error(&a->archive, ENOMEM,
  1448. "Couldn't allocate memory "
  1449. "for lzh decompression");
  1450. return (ARCHIVE_FATAL);
  1451. }
  1452. /* We've initialized decompression for this stream. */
  1453. lha->decompress_init = 1;
  1454. lha->strm.avail_out = 0;
  1455. lha->strm.total_out = 0;
  1456. }
  1457. /*
  1458. * Note: '1' here is a performance optimization.
  1459. * Recall that the decompression layer returns a count of
  1460. * available bytes; asking for more than that forces the
  1461. * decompressor to combine reads by copying data.
  1462. */
  1463. lha->strm.next_in = __archive_read_ahead(a, 1, &bytes_avail);
  1464. if (bytes_avail <= 0) {
  1465. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1466. "Truncated LHa file body");
  1467. return (ARCHIVE_FATAL);
  1468. }
  1469. if (bytes_avail > lha->entry_bytes_remaining)
  1470. bytes_avail = (ssize_t)lha->entry_bytes_remaining;
  1471. lha->strm.avail_in = (int)bytes_avail;
  1472. lha->strm.total_in = 0;
  1473. lha->strm.avail_out = 0;
  1474. r = lzh_decode(&(lha->strm), bytes_avail == lha->entry_bytes_remaining);
  1475. switch (r) {
  1476. case ARCHIVE_OK:
  1477. break;
  1478. case ARCHIVE_EOF:
  1479. lha->end_of_entry = 1;
  1480. break;
  1481. default:
  1482. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1483. "Bad lzh data");
  1484. return (ARCHIVE_FAILED);
  1485. }
  1486. lha->entry_unconsumed = lha->strm.total_in;
  1487. lha->entry_bytes_remaining -= lha->strm.total_in;
  1488. if (lha->strm.avail_out) {
  1489. *offset = lha->entry_offset;
  1490. *size = lha->strm.avail_out;
  1491. *buff = lha->strm.ref_ptr;
  1492. lha->entry_crc_calculated =
  1493. lha_crc16(lha->entry_crc_calculated, *buff, *size);
  1494. lha->entry_offset += *size;
  1495. } else {
  1496. *offset = lha->entry_offset;
  1497. *size = 0;
  1498. *buff = NULL;
  1499. if (lha->end_of_entry)
  1500. return (lha_end_of_entry(a));
  1501. }
  1502. return (ARCHIVE_OK);
  1503. }
  1504. /*
  1505. * Skip a file content.
  1506. */
  1507. static int
  1508. archive_read_format_lha_read_data_skip(struct archive_read *a)
  1509. {
  1510. struct lha *lha;
  1511. int64_t bytes_skipped;
  1512. lha = (struct lha *)(a->format->data);
  1513. if (lha->entry_unconsumed) {
  1514. /* Consume as much as the decompressor actually used. */
  1515. __archive_read_consume(a, lha->entry_unconsumed);
  1516. lha->entry_unconsumed = 0;
  1517. }
  1518. /* if we've already read to end of data, we're done. */
  1519. if (lha->end_of_entry_cleanup)
  1520. return (ARCHIVE_OK);
  1521. /*
  1522. * If the length is at the beginning, we can skip the
  1523. * compressed data much more quickly.
  1524. */
  1525. bytes_skipped = __archive_read_consume(a, lha->entry_bytes_remaining);
  1526. if (bytes_skipped < 0)
  1527. return (ARCHIVE_FATAL);
  1528. /* This entry is finished and done. */
  1529. lha->end_of_entry_cleanup = lha->end_of_entry = 1;
  1530. return (ARCHIVE_OK);
  1531. }
  1532. static int
  1533. archive_read_format_lha_cleanup(struct archive_read *a)
  1534. {
  1535. struct lha *lha = (struct lha *)(a->format->data);
  1536. lzh_decode_free(&(lha->strm));
  1537. archive_string_free(&(lha->dirname));
  1538. archive_string_free(&(lha->filename));
  1539. archive_string_free(&(lha->uname));
  1540. archive_string_free(&(lha->gname));
  1541. archive_wstring_free(&(lha->ws));
  1542. free(lha);
  1543. (a->format->data) = NULL;
  1544. return (ARCHIVE_OK);
  1545. }
  1546. /*
  1547. * 'LHa for UNIX' utility has archived a symbolic-link name after
  1548. * a pathname with '|' character.
  1549. * This function extracts the symbolic-link name from the pathname.
  1550. *
  1551. * example.
  1552. * 1. a symbolic-name is 'aaa/bb/cc'
  1553. * 2. a filename is 'xxx/bbb'
  1554. * then a archived pathname is 'xxx/bbb|aaa/bb/cc'
  1555. */
  1556. static int
  1557. lha_parse_linkname(struct archive_wstring *linkname,
  1558. struct archive_wstring *pathname)
  1559. {
  1560. wchar_t * linkptr;
  1561. size_t symlen;
  1562. linkptr = wcschr(pathname->s, L'|');
  1563. if (linkptr != NULL) {
  1564. symlen = wcslen(linkptr + 1);
  1565. archive_wstrncpy(linkname, linkptr+1, symlen);
  1566. *linkptr = 0;
  1567. pathname->length = wcslen(pathname->s);
  1568. return (1);
  1569. }
  1570. return (0);
  1571. }
  1572. /* Convert an MSDOS-style date/time into Unix-style time. */
  1573. static time_t
  1574. lha_dos_time(const unsigned char *p)
  1575. {
  1576. int msTime, msDate;
  1577. struct tm ts;
  1578. msTime = archive_le16dec(p);
  1579. msDate = archive_le16dec(p+2);
  1580. memset(&ts, 0, sizeof(ts));
  1581. ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
  1582. ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
  1583. ts.tm_mday = msDate & 0x1f; /* Day of month. */
  1584. ts.tm_hour = (msTime >> 11) & 0x1f;
  1585. ts.tm_min = (msTime >> 5) & 0x3f;
  1586. ts.tm_sec = (msTime << 1) & 0x3e;
  1587. ts.tm_isdst = -1;
  1588. return (mktime(&ts));
  1589. }
  1590. /* Convert an MS-Windows-style date/time into Unix-style time. */
  1591. static time_t
  1592. lha_win_time(uint64_t wintime, long *ns)
  1593. {
  1594. #define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000)
  1595. if (wintime >= EPOC_TIME) {
  1596. wintime -= EPOC_TIME; /* 1970-01-01 00:00:00 (UTC) */
  1597. if (ns != NULL)
  1598. *ns = (long)(wintime % 10000000) * 100;
  1599. return (wintime / 10000000);
  1600. } else {
  1601. if (ns != NULL)
  1602. *ns = 0;
  1603. return (0);
  1604. }
  1605. }
  1606. static unsigned char
  1607. lha_calcsum(unsigned char sum, const void *pp, int offset, size_t size)
  1608. {
  1609. unsigned char const *p = (unsigned char const *)pp;
  1610. p += offset;
  1611. for (;size > 0; --size)
  1612. sum += *p++;
  1613. return (sum);
  1614. }
  1615. static uint16_t crc16tbl[2][256];
  1616. static void
  1617. lha_crc16_init(void)
  1618. {
  1619. unsigned int i;
  1620. static int crc16init = 0;
  1621. if (crc16init)
  1622. return;
  1623. crc16init = 1;
  1624. for (i = 0; i < 256; i++) {
  1625. unsigned int j;
  1626. uint16_t crc = (uint16_t)i;
  1627. for (j = 8; j; j--)
  1628. crc = (crc >> 1) ^ ((crc & 1) * 0xA001);
  1629. crc16tbl[0][i] = crc;
  1630. }
  1631. for (i = 0; i < 256; i++) {
  1632. crc16tbl[1][i] = (crc16tbl[0][i] >> 8)
  1633. ^ crc16tbl[0][crc16tbl[0][i] & 0xff];
  1634. }
  1635. }
  1636. static uint16_t
  1637. lha_crc16(uint16_t crc, const void *pp, size_t len)
  1638. {
  1639. const unsigned char *p = (const unsigned char *)pp;
  1640. const uint16_t *buff;
  1641. const union {
  1642. uint32_t i;
  1643. char c[4];
  1644. } u = { 0x01020304 };
  1645. if (len == 0)
  1646. return crc;
  1647. /* Process unaligned address. */
  1648. if (((uintptr_t)p) & (uintptr_t)0x1) {
  1649. crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff];
  1650. len--;
  1651. }
  1652. buff = (const uint16_t *)p;
  1653. /*
  1654. * Modern C compiler such as GCC does not unroll automatically yet
  1655. * without unrolling pragma, and Clang is so. So we should
  1656. * unroll this loop for its performance.
  1657. */
  1658. for (;len >= 8; len -= 8) {
  1659. /* This if statement expects compiler optimization will
  1660. * remove the statement which will not be executed. */
  1661. #undef bswap16
  1662. #ifndef __has_builtin
  1663. # define __has_builtin(x) 0
  1664. #endif
  1665. #if defined(_MSC_VER) && _MSC_VER >= 1400 /* Visual Studio */
  1666. # define bswap16(x) _byteswap_ushort(x)
  1667. #elif defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ > 4)
  1668. /* GCC 4.8 and later has __builtin_bswap16() */
  1669. # define bswap16(x) __builtin_bswap16(x)
  1670. #elif defined(__clang__) && __has_builtin(__builtin_bswap16)
  1671. /* All clang versions have __builtin_bswap16() */
  1672. # define bswap16(x) __builtin_bswap16(x)
  1673. #else
  1674. # define bswap16(x) ((((x) >> 8) & 0xff) | ((x) << 8))
  1675. #endif
  1676. #define CRC16W do { \
  1677. if(u.c[0] == 1) { /* Big endian */ \
  1678. crc ^= bswap16(*buff); buff++; \
  1679. } else \
  1680. crc ^= *buff++; \
  1681. crc = crc16tbl[1][crc & 0xff] ^ crc16tbl[0][crc >> 8];\
  1682. } while (0)
  1683. CRC16W;
  1684. CRC16W;
  1685. CRC16W;
  1686. CRC16W;
  1687. #undef CRC16W
  1688. #undef bswap16
  1689. }
  1690. p = (const unsigned char *)buff;
  1691. for (;len; len--) {
  1692. crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff];
  1693. }
  1694. return crc;
  1695. }
  1696. /*
  1697. * Initialize LZHUF decoder.
  1698. *
  1699. * Returns ARCHIVE_OK if initialization was successful.
  1700. * Returns ARCHIVE_FAILED if method is unsupported.
  1701. * Returns ARCHIVE_FATAL if initialization failed; memory allocation
  1702. * error occurred.
  1703. */
  1704. static int
  1705. lzh_decode_init(struct lzh_stream *strm, const char *method)
  1706. {
  1707. struct lzh_dec *ds;
  1708. int w_bits, w_size;
  1709. if (strm->ds == NULL) {
  1710. strm->ds = calloc(1, sizeof(*strm->ds));
  1711. if (strm->ds == NULL)
  1712. return (ARCHIVE_FATAL);
  1713. }
  1714. ds = strm->ds;
  1715. ds->error = ARCHIVE_FAILED;
  1716. if (method == NULL || method[0] != 'l' || method[1] != 'h')
  1717. return (ARCHIVE_FAILED);
  1718. switch (method[2]) {
  1719. case '5':
  1720. w_bits = 13;/* 8KiB for window */
  1721. break;
  1722. case '6':
  1723. w_bits = 15;/* 32KiB for window */
  1724. break;
  1725. case '7':
  1726. w_bits = 16;/* 64KiB for window */
  1727. break;
  1728. default:
  1729. return (ARCHIVE_FAILED);/* Not supported. */
  1730. }
  1731. ds->error = ARCHIVE_FATAL;
  1732. /* Expand a window size up to 128 KiB for decompressing process
  1733. * performance whatever its original window size is. */
  1734. ds->w_size = 1U << 17;
  1735. ds->w_mask = ds->w_size -1;
  1736. if (ds->w_buff == NULL) {
  1737. ds->w_buff = malloc(ds->w_size);
  1738. if (ds->w_buff == NULL)
  1739. return (ARCHIVE_FATAL);
  1740. }
  1741. w_size = 1U << w_bits;
  1742. memset(ds->w_buff + ds->w_size - w_size, 0x20, w_size);
  1743. ds->w_pos = 0;
  1744. ds->state = 0;
  1745. ds->pos_pt_len_size = w_bits + 1;
  1746. ds->pos_pt_len_bits = (w_bits == 15 || w_bits == 16)? 5: 4;
  1747. ds->literal_pt_len_size = PT_BITLEN_SIZE;
  1748. ds->literal_pt_len_bits = 5;
  1749. ds->br.cache_buffer = 0;
  1750. ds->br.cache_avail = 0;
  1751. if (lzh_huffman_init(&(ds->lt), LT_BITLEN_SIZE, 16)
  1752. != ARCHIVE_OK)
  1753. return (ARCHIVE_FATAL);
  1754. ds->lt.len_bits = 9;
  1755. if (lzh_huffman_init(&(ds->pt), PT_BITLEN_SIZE, 16)
  1756. != ARCHIVE_OK)
  1757. return (ARCHIVE_FATAL);
  1758. ds->error = 0;
  1759. return (ARCHIVE_OK);
  1760. }
  1761. /*
  1762. * Release LZHUF decoder.
  1763. */
  1764. static void
  1765. lzh_decode_free(struct lzh_stream *strm)
  1766. {
  1767. if (strm->ds == NULL)
  1768. return;
  1769. free(strm->ds->w_buff);
  1770. lzh_huffman_free(&(strm->ds->lt));
  1771. lzh_huffman_free(&(strm->ds->pt));
  1772. free(strm->ds);
  1773. strm->ds = NULL;
  1774. }
  1775. /*
  1776. * Bit stream reader.
  1777. */
  1778. /* Check that the cache buffer has enough bits. */
  1779. #define lzh_br_has(br, n) ((br)->cache_avail >= n)
  1780. /* Get compressed data by bit. */
  1781. #define lzh_br_bits(br, n) \
  1782. (((uint16_t)((br)->cache_buffer >> \
  1783. ((br)->cache_avail - (n)))) & cache_masks[n])
  1784. #define lzh_br_bits_forced(br, n) \
  1785. (((uint16_t)((br)->cache_buffer << \
  1786. ((n) - (br)->cache_avail))) & cache_masks[n])
  1787. /* Read ahead to make sure the cache buffer has enough compressed data we
  1788. * will use.
  1789. * True : completed, there is enough data in the cache buffer.
  1790. * False : we met that strm->next_in is empty, we have to get following
  1791. * bytes. */
  1792. #define lzh_br_read_ahead_0(strm, br, n) \
  1793. (lzh_br_has(br, (n)) || lzh_br_fillup(strm, br))
  1794. /* True : the cache buffer has some bits as much as we need.
  1795. * False : there are no enough bits in the cache buffer to be used,
  1796. * we have to get following bytes if we could. */
  1797. #define lzh_br_read_ahead(strm, br, n) \
  1798. (lzh_br_read_ahead_0((strm), (br), (n)) || lzh_br_has((br), (n)))
  1799. /* Notify how many bits we consumed. */
  1800. #define lzh_br_consume(br, n) ((br)->cache_avail -= (n))
  1801. #define lzh_br_unconsume(br, n) ((br)->cache_avail += (n))
  1802. static const uint16_t cache_masks[] = {
  1803. 0x0000, 0x0001, 0x0003, 0x0007,
  1804. 0x000F, 0x001F, 0x003F, 0x007F,
  1805. 0x00FF, 0x01FF, 0x03FF, 0x07FF,
  1806. 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF,
  1807. 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF
  1808. };
  1809. /*
  1810. * Shift away used bits in the cache data and fill it up with following bits.
  1811. * Call this when cache buffer does not have enough bits you need.
  1812. *
  1813. * Returns 1 if the cache buffer is full.
  1814. * Returns 0 if the cache buffer is not full; input buffer is empty.
  1815. */
  1816. static int
  1817. lzh_br_fillup(struct lzh_stream *strm, struct lzh_br *br)
  1818. {
  1819. int n = CACHE_BITS - br->cache_avail;
  1820. for (;;) {
  1821. const int x = n >> 3;
  1822. if (strm->avail_in >= x) {
  1823. switch (x) {
  1824. case 8:
  1825. br->cache_buffer =
  1826. ((uint64_t)strm->next_in[0]) << 56 |
  1827. ((uint64_t)strm->next_in[1]) << 48 |
  1828. ((uint64_t)strm->next_in[2]) << 40 |
  1829. ((uint64_t)strm->next_in[3]) << 32 |
  1830. ((uint32_t)strm->next_in[4]) << 24 |
  1831. ((uint32_t)strm->next_in[5]) << 16 |
  1832. ((uint32_t)strm->next_in[6]) << 8 |
  1833. (uint32_t)strm->next_in[7];
  1834. strm->next_in += 8;
  1835. strm->avail_in -= 8;
  1836. br->cache_avail += 8 * 8;
  1837. return (1);
  1838. case 7:
  1839. br->cache_buffer =
  1840. (br->cache_buffer << 56) |
  1841. ((uint64_t)strm->next_in[0]) << 48 |
  1842. ((uint64_t)strm->next_in[1]) << 40 |
  1843. ((uint64_t)strm->next_in[2]) << 32 |
  1844. ((uint32_t)strm->next_in[3]) << 24 |
  1845. ((uint32_t)strm->next_in[4]) << 16 |
  1846. ((uint32_t)strm->next_in[5]) << 8 |
  1847. (uint32_t)strm->next_in[6];
  1848. strm->next_in += 7;
  1849. strm->avail_in -= 7;
  1850. br->cache_avail += 7 * 8;
  1851. return (1);
  1852. case 6:
  1853. br->cache_buffer =
  1854. (br->cache_buffer << 48) |
  1855. ((uint64_t)strm->next_in[0]) << 40 |
  1856. ((uint64_t)strm->next_in[1]) << 32 |
  1857. ((uint32_t)strm->next_in[2]) << 24 |
  1858. ((uint32_t)strm->next_in[3]) << 16 |
  1859. ((uint32_t)strm->next_in[4]) << 8 |
  1860. (uint32_t)strm->next_in[5];
  1861. strm->next_in += 6;
  1862. strm->avail_in -= 6;
  1863. br->cache_avail += 6 * 8;
  1864. return (1);
  1865. case 0:
  1866. /* We have enough compressed data in
  1867. * the cache buffer.*/
  1868. return (1);
  1869. default:
  1870. break;
  1871. }
  1872. }
  1873. if (strm->avail_in == 0) {
  1874. /* There is not enough compressed data to fill up the
  1875. * cache buffer. */
  1876. return (0);
  1877. }
  1878. br->cache_buffer =
  1879. (br->cache_buffer << 8) | *strm->next_in++;
  1880. strm->avail_in--;
  1881. br->cache_avail += 8;
  1882. n -= 8;
  1883. }
  1884. }
  1885. /*
  1886. * Decode LZHUF.
  1887. *
  1888. * 1. Returns ARCHIVE_OK if output buffer or input buffer are empty.
  1889. * Please set available buffer and call this function again.
  1890. * 2. Returns ARCHIVE_EOF if decompression has been completed.
  1891. * 3. Returns ARCHIVE_FAILED if an error occurred; compressed data
  1892. * is broken or you do not set 'last' flag properly.
  1893. * 4. 'last' flag is very important, you must set 1 to the flag if there
  1894. * is no input data. The lha compressed data format does not provide how
  1895. * to know the compressed data is really finished.
  1896. * Note: lha command utility check if the total size of output bytes is
  1897. * reached the uncompressed size recorded in its header. it does not mind
  1898. * that the decoding process is properly finished.
  1899. * GNU ZIP can decompress another compressed file made by SCO LZH compress.
  1900. * it handles EOF as null to fill read buffer with zero until the decoding
  1901. * process meet 2 bytes of zeros at reading a size of a next chunk, so the
  1902. * zeros are treated as the mark of the end of the data although the zeros
  1903. * is dummy, not the file data.
  1904. */
  1905. static int lzh_read_blocks(struct lzh_stream *, int);
  1906. static int lzh_decode_blocks(struct lzh_stream *, int);
  1907. #define ST_RD_BLOCK 0
  1908. #define ST_RD_PT_1 1
  1909. #define ST_RD_PT_2 2
  1910. #define ST_RD_PT_3 3
  1911. #define ST_RD_PT_4 4
  1912. #define ST_RD_LITERAL_1 5
  1913. #define ST_RD_LITERAL_2 6
  1914. #define ST_RD_LITERAL_3 7
  1915. #define ST_RD_POS_DATA_1 8
  1916. #define ST_GET_LITERAL 9
  1917. #define ST_GET_POS_1 10
  1918. #define ST_GET_POS_2 11
  1919. #define ST_COPY_DATA 12
  1920. static int
  1921. lzh_decode(struct lzh_stream *strm, int last)
  1922. {
  1923. struct lzh_dec *ds = strm->ds;
  1924. int avail_in;
  1925. int r;
  1926. if (ds->error)
  1927. return (ds->error);
  1928. avail_in = strm->avail_in;
  1929. do {
  1930. if (ds->state < ST_GET_LITERAL)
  1931. r = lzh_read_blocks(strm, last);
  1932. else
  1933. r = lzh_decode_blocks(strm, last);
  1934. } while (r == 100);
  1935. strm->total_in += avail_in - strm->avail_in;
  1936. return (r);
  1937. }
  1938. static void
  1939. lzh_emit_window(struct lzh_stream *strm, size_t s)
  1940. {
  1941. strm->ref_ptr = strm->ds->w_buff;
  1942. strm->avail_out = (int)s;
  1943. strm->total_out += s;
  1944. }
  1945. static int
  1946. lzh_read_blocks(struct lzh_stream *strm, int last)
  1947. {
  1948. struct lzh_dec *ds = strm->ds;
  1949. struct lzh_br *br = &(ds->br);
  1950. int c = 0, i;
  1951. unsigned rbits;
  1952. for (;;) {
  1953. switch (ds->state) {
  1954. case ST_RD_BLOCK:
  1955. /*
  1956. * Read a block number indicates how many blocks
  1957. * we will handle. The block is composed of a
  1958. * literal and a match, sometimes a literal only
  1959. * in particular, there are no reference data at
  1960. * the beginning of the decompression.
  1961. */
  1962. if (!lzh_br_read_ahead_0(strm, br, 16)) {
  1963. if (!last)
  1964. /* We need following data. */
  1965. return (ARCHIVE_OK);
  1966. if (lzh_br_has(br, 8)) {
  1967. /*
  1968. * It seems there are extra bits.
  1969. * 1. Compressed data is broken.
  1970. * 2. `last' flag does not properly
  1971. * set.
  1972. */
  1973. goto failed;
  1974. }
  1975. if (ds->w_pos > 0) {
  1976. lzh_emit_window(strm, ds->w_pos);
  1977. ds->w_pos = 0;
  1978. return (ARCHIVE_OK);
  1979. }
  1980. /* End of compressed data; we have completely
  1981. * handled all compressed data. */
  1982. return (ARCHIVE_EOF);
  1983. }
  1984. ds->blocks_avail = lzh_br_bits(br, 16);
  1985. if (ds->blocks_avail == 0)
  1986. goto failed;
  1987. lzh_br_consume(br, 16);
  1988. /*
  1989. * Read a literal table compressed in huffman
  1990. * coding.
  1991. */
  1992. ds->pt.len_size = ds->literal_pt_len_size;
  1993. ds->pt.len_bits = ds->literal_pt_len_bits;
  1994. ds->reading_position = 0;
  1995. /* FALL THROUGH */
  1996. case ST_RD_PT_1:
  1997. /* Note: ST_RD_PT_1, ST_RD_PT_2 and ST_RD_PT_4 are
  1998. * used in reading both a literal table and a
  1999. * position table. */
  2000. if (!lzh_br_read_ahead(strm, br, ds->pt.len_bits)) {
  2001. if (last)
  2002. goto failed;/* Truncated data. */
  2003. ds->state = ST_RD_PT_1;
  2004. return (ARCHIVE_OK);
  2005. }
  2006. ds->pt.len_avail = lzh_br_bits(br, ds->pt.len_bits);
  2007. lzh_br_consume(br, ds->pt.len_bits);
  2008. /* FALL THROUGH */
  2009. case ST_RD_PT_2:
  2010. if (ds->pt.len_avail == 0) {
  2011. /* There is no bitlen. */
  2012. if (!lzh_br_read_ahead(strm, br,
  2013. ds->pt.len_bits)) {
  2014. if (last)
  2015. goto failed;/* Truncated data.*/
  2016. ds->state = ST_RD_PT_2;
  2017. return (ARCHIVE_OK);
  2018. }
  2019. if (!lzh_make_fake_table(&(ds->pt),
  2020. lzh_br_bits(br, ds->pt.len_bits)))
  2021. goto failed;/* Invalid data. */
  2022. lzh_br_consume(br, ds->pt.len_bits);
  2023. if (ds->reading_position)
  2024. ds->state = ST_GET_LITERAL;
  2025. else
  2026. ds->state = ST_RD_LITERAL_1;
  2027. break;
  2028. } else if (ds->pt.len_avail > ds->pt.len_size)
  2029. goto failed;/* Invalid data. */
  2030. ds->loop = 0;
  2031. memset(ds->pt.freq, 0, sizeof(ds->pt.freq));
  2032. if (ds->pt.len_avail < 3 ||
  2033. ds->pt.len_size == ds->pos_pt_len_size) {
  2034. ds->state = ST_RD_PT_4;
  2035. break;
  2036. }
  2037. /* FALL THROUGH */
  2038. case ST_RD_PT_3:
  2039. ds->loop = lzh_read_pt_bitlen(strm, ds->loop, 3);
  2040. if (ds->loop < 3) {
  2041. if (ds->loop < 0 || last)
  2042. goto failed;/* Invalid data. */
  2043. /* Not completed, get following data. */
  2044. ds->state = ST_RD_PT_3;
  2045. return (ARCHIVE_OK);
  2046. }
  2047. /* There are some null in bitlen of the literal. */
  2048. if (!lzh_br_read_ahead(strm, br, 2)) {
  2049. if (last)
  2050. goto failed;/* Truncated data. */
  2051. ds->state = ST_RD_PT_3;
  2052. return (ARCHIVE_OK);
  2053. }
  2054. c = lzh_br_bits(br, 2);
  2055. lzh_br_consume(br, 2);
  2056. if (c > ds->pt.len_avail - 3)
  2057. goto failed;/* Invalid data. */
  2058. for (i = 3; c-- > 0 ;)
  2059. ds->pt.bitlen[i++] = 0;
  2060. ds->loop = i;
  2061. /* FALL THROUGH */
  2062. case ST_RD_PT_4:
  2063. ds->loop = lzh_read_pt_bitlen(strm, ds->loop,
  2064. ds->pt.len_avail);
  2065. if (ds->loop < ds->pt.len_avail) {
  2066. if (ds->loop < 0 || last)
  2067. goto failed;/* Invalid data. */
  2068. /* Not completed, get following data. */
  2069. ds->state = ST_RD_PT_4;
  2070. return (ARCHIVE_OK);
  2071. }
  2072. if (!lzh_make_huffman_table(&(ds->pt)))
  2073. goto failed;/* Invalid data */
  2074. if (ds->reading_position) {
  2075. ds->state = ST_GET_LITERAL;
  2076. break;
  2077. }
  2078. /* FALL THROUGH */
  2079. case ST_RD_LITERAL_1:
  2080. if (!lzh_br_read_ahead(strm, br, ds->lt.len_bits)) {
  2081. if (last)
  2082. goto failed;/* Truncated data. */
  2083. ds->state = ST_RD_LITERAL_1;
  2084. return (ARCHIVE_OK);
  2085. }
  2086. ds->lt.len_avail = lzh_br_bits(br, ds->lt.len_bits);
  2087. lzh_br_consume(br, ds->lt.len_bits);
  2088. /* FALL THROUGH */
  2089. case ST_RD_LITERAL_2:
  2090. if (ds->lt.len_avail == 0) {
  2091. /* There is no bitlen. */
  2092. if (!lzh_br_read_ahead(strm, br,
  2093. ds->lt.len_bits)) {
  2094. if (last)
  2095. goto failed;/* Truncated data.*/
  2096. ds->state = ST_RD_LITERAL_2;
  2097. return (ARCHIVE_OK);
  2098. }
  2099. if (!lzh_make_fake_table(&(ds->lt),
  2100. lzh_br_bits(br, ds->lt.len_bits)))
  2101. goto failed;/* Invalid data */
  2102. lzh_br_consume(br, ds->lt.len_bits);
  2103. ds->state = ST_RD_POS_DATA_1;
  2104. break;
  2105. } else if (ds->lt.len_avail > ds->lt.len_size)
  2106. goto failed;/* Invalid data */
  2107. ds->loop = 0;
  2108. memset(ds->lt.freq, 0, sizeof(ds->lt.freq));
  2109. /* FALL THROUGH */
  2110. case ST_RD_LITERAL_3:
  2111. i = ds->loop;
  2112. while (i < ds->lt.len_avail) {
  2113. if (!lzh_br_read_ahead(strm, br,
  2114. ds->pt.max_bits)) {
  2115. if (last)
  2116. goto failed;/* Truncated data.*/
  2117. ds->loop = i;
  2118. ds->state = ST_RD_LITERAL_3;
  2119. return (ARCHIVE_OK);
  2120. }
  2121. rbits = lzh_br_bits(br, ds->pt.max_bits);
  2122. c = lzh_decode_huffman(&(ds->pt), rbits);
  2123. if (c > 2) {
  2124. /* Note: 'c' will never be more than
  2125. * eighteen since it's limited by
  2126. * PT_BITLEN_SIZE, which is being set
  2127. * to ds->pt.len_size through
  2128. * ds->literal_pt_len_size. */
  2129. lzh_br_consume(br, ds->pt.bitlen[c]);
  2130. c -= 2;
  2131. ds->lt.freq[c]++;
  2132. ds->lt.bitlen[i++] = c;
  2133. } else if (c == 0) {
  2134. lzh_br_consume(br, ds->pt.bitlen[c]);
  2135. ds->lt.bitlen[i++] = 0;
  2136. } else {
  2137. /* c == 1 or c == 2 */
  2138. int n = (c == 1)?4:9;
  2139. if (!lzh_br_read_ahead(strm, br,
  2140. ds->pt.bitlen[c] + n)) {
  2141. if (last) /* Truncated data. */
  2142. goto failed;
  2143. ds->loop = i;
  2144. ds->state = ST_RD_LITERAL_3;
  2145. return (ARCHIVE_OK);
  2146. }
  2147. lzh_br_consume(br, ds->pt.bitlen[c]);
  2148. c = lzh_br_bits(br, n);
  2149. lzh_br_consume(br, n);
  2150. c += (n == 4)?3:20;
  2151. if (i + c > ds->lt.len_avail)
  2152. goto failed;/* Invalid data */
  2153. memset(&(ds->lt.bitlen[i]), 0, c);
  2154. i += c;
  2155. }
  2156. }
  2157. if (i > ds->lt.len_avail ||
  2158. !lzh_make_huffman_table(&(ds->lt)))
  2159. goto failed;/* Invalid data */
  2160. /* FALL THROUGH */
  2161. case ST_RD_POS_DATA_1:
  2162. /*
  2163. * Read a position table compressed in huffman
  2164. * coding.
  2165. */
  2166. ds->pt.len_size = ds->pos_pt_len_size;
  2167. ds->pt.len_bits = ds->pos_pt_len_bits;
  2168. ds->reading_position = 1;
  2169. ds->state = ST_RD_PT_1;
  2170. break;
  2171. case ST_GET_LITERAL:
  2172. return (100);
  2173. }
  2174. }
  2175. failed:
  2176. return (ds->error = ARCHIVE_FAILED);
  2177. }
  2178. static int
  2179. lzh_decode_blocks(struct lzh_stream *strm, int last)
  2180. {
  2181. struct lzh_dec *ds = strm->ds;
  2182. struct lzh_br bre = ds->br;
  2183. struct huffman *lt = &(ds->lt);
  2184. struct huffman *pt = &(ds->pt);
  2185. unsigned char *w_buff = ds->w_buff;
  2186. unsigned char *lt_bitlen = lt->bitlen;
  2187. unsigned char *pt_bitlen = pt->bitlen;
  2188. int blocks_avail = ds->blocks_avail, c = 0;
  2189. int copy_len = ds->copy_len, copy_pos = ds->copy_pos;
  2190. int w_pos = ds->w_pos, w_mask = ds->w_mask, w_size = ds->w_size;
  2191. int lt_max_bits = lt->max_bits, pt_max_bits = pt->max_bits;
  2192. int state = ds->state;
  2193. for (;;) {
  2194. switch (state) {
  2195. case ST_GET_LITERAL:
  2196. for (;;) {
  2197. if (blocks_avail == 0) {
  2198. /* We have decoded all blocks.
  2199. * Let's handle next blocks. */
  2200. ds->state = ST_RD_BLOCK;
  2201. ds->br = bre;
  2202. ds->blocks_avail = 0;
  2203. ds->w_pos = w_pos;
  2204. ds->copy_pos = 0;
  2205. return (100);
  2206. }
  2207. /* lzh_br_read_ahead() always try to fill the
  2208. * cache buffer up. In specific situation we
  2209. * are close to the end of the data, the cache
  2210. * buffer will not be full and thus we have to
  2211. * determine if the cache buffer has some bits
  2212. * as much as we need after lzh_br_read_ahead()
  2213. * failed. */
  2214. if (!lzh_br_read_ahead(strm, &bre,
  2215. lt_max_bits)) {
  2216. if (!last)
  2217. goto next_data;
  2218. /* Remaining bits are less than
  2219. * maximum bits(lt.max_bits) but maybe
  2220. * it still remains as much as we need,
  2221. * so we should try to use it with
  2222. * dummy bits. */
  2223. c = lzh_decode_huffman(lt,
  2224. lzh_br_bits_forced(&bre,
  2225. lt_max_bits));
  2226. lzh_br_consume(&bre, lt_bitlen[c]);
  2227. if (!lzh_br_has(&bre, 0))
  2228. goto failed;/* Over read. */
  2229. } else {
  2230. c = lzh_decode_huffman(lt,
  2231. lzh_br_bits(&bre, lt_max_bits));
  2232. lzh_br_consume(&bre, lt_bitlen[c]);
  2233. }
  2234. blocks_avail--;
  2235. if (c > UCHAR_MAX)
  2236. /* Current block is a match data. */
  2237. break;
  2238. /*
  2239. * 'c' is exactly a literal code.
  2240. */
  2241. /* Save a decoded code to reference it
  2242. * afterward. */
  2243. w_buff[w_pos] = c;
  2244. if (++w_pos >= w_size) {
  2245. w_pos = 0;
  2246. lzh_emit_window(strm, w_size);
  2247. goto next_data;
  2248. }
  2249. }
  2250. /* 'c' is the length of a match pattern we have
  2251. * already extracted, which has be stored in
  2252. * window(ds->w_buff). */
  2253. copy_len = c - (UCHAR_MAX + 1) + MINMATCH;
  2254. /* FALL THROUGH */
  2255. case ST_GET_POS_1:
  2256. /*
  2257. * Get a reference position.
  2258. */
  2259. if (!lzh_br_read_ahead(strm, &bre, pt_max_bits)) {
  2260. if (!last) {
  2261. state = ST_GET_POS_1;
  2262. ds->copy_len = copy_len;
  2263. goto next_data;
  2264. }
  2265. copy_pos = lzh_decode_huffman(pt,
  2266. lzh_br_bits_forced(&bre, pt_max_bits));
  2267. lzh_br_consume(&bre, pt_bitlen[copy_pos]);
  2268. if (!lzh_br_has(&bre, 0))
  2269. goto failed;/* Over read. */
  2270. } else {
  2271. copy_pos = lzh_decode_huffman(pt,
  2272. lzh_br_bits(&bre, pt_max_bits));
  2273. lzh_br_consume(&bre, pt_bitlen[copy_pos]);
  2274. }
  2275. /* FALL THROUGH */
  2276. case ST_GET_POS_2:
  2277. if (copy_pos > 1) {
  2278. /* We need an additional adjustment number to
  2279. * the position. */
  2280. int p = copy_pos - 1;
  2281. if (!lzh_br_read_ahead(strm, &bre, p)) {
  2282. if (last)
  2283. goto failed;/* Truncated data.*/
  2284. state = ST_GET_POS_2;
  2285. ds->copy_len = copy_len;
  2286. ds->copy_pos = copy_pos;
  2287. goto next_data;
  2288. }
  2289. copy_pos = (1 << p) + lzh_br_bits(&bre, p);
  2290. lzh_br_consume(&bre, p);
  2291. }
  2292. /* The position is actually a distance from the last
  2293. * code we had extracted and thus we have to convert
  2294. * it to a position of the window. */
  2295. copy_pos = (w_pos - copy_pos - 1) & w_mask;
  2296. /* FALL THROUGH */
  2297. case ST_COPY_DATA:
  2298. /*
  2299. * Copy `copy_len' bytes as extracted data from
  2300. * the window into the output buffer.
  2301. */
  2302. for (;;) {
  2303. int l;
  2304. l = copy_len;
  2305. if (copy_pos > w_pos) {
  2306. if (l > w_size - copy_pos)
  2307. l = w_size - copy_pos;
  2308. } else {
  2309. if (l > w_size - w_pos)
  2310. l = w_size - w_pos;
  2311. }
  2312. if ((copy_pos + l < w_pos)
  2313. || (w_pos + l < copy_pos)) {
  2314. /* No overlap. */
  2315. memcpy(w_buff + w_pos,
  2316. w_buff + copy_pos, l);
  2317. } else {
  2318. const unsigned char *s;
  2319. unsigned char *d;
  2320. int li;
  2321. d = w_buff + w_pos;
  2322. s = w_buff + copy_pos;
  2323. for (li = 0; li < l-1;) {
  2324. d[li] = s[li];li++;
  2325. d[li] = s[li];li++;
  2326. }
  2327. if (li < l)
  2328. d[li] = s[li];
  2329. }
  2330. w_pos += l;
  2331. if (w_pos == w_size) {
  2332. w_pos = 0;
  2333. lzh_emit_window(strm, w_size);
  2334. if (copy_len <= l)
  2335. state = ST_GET_LITERAL;
  2336. else {
  2337. state = ST_COPY_DATA;
  2338. ds->copy_len = copy_len - l;
  2339. ds->copy_pos =
  2340. (copy_pos + l) & w_mask;
  2341. }
  2342. goto next_data;
  2343. }
  2344. if (copy_len <= l)
  2345. /* A copy of current pattern ended. */
  2346. break;
  2347. copy_len -= l;
  2348. copy_pos = (copy_pos + l) & w_mask;
  2349. }
  2350. state = ST_GET_LITERAL;
  2351. break;
  2352. }
  2353. }
  2354. failed:
  2355. return (ds->error = ARCHIVE_FAILED);
  2356. next_data:
  2357. ds->br = bre;
  2358. ds->blocks_avail = blocks_avail;
  2359. ds->state = state;
  2360. ds->w_pos = w_pos;
  2361. return (ARCHIVE_OK);
  2362. }
  2363. static int
  2364. lzh_huffman_init(struct huffman *hf, size_t len_size, int tbl_bits)
  2365. {
  2366. int bits;
  2367. if (hf->bitlen == NULL) {
  2368. hf->bitlen = malloc(len_size * sizeof(hf->bitlen[0]));
  2369. if (hf->bitlen == NULL)
  2370. return (ARCHIVE_FATAL);
  2371. }
  2372. if (hf->tbl == NULL) {
  2373. if (tbl_bits < HTBL_BITS)
  2374. bits = tbl_bits;
  2375. else
  2376. bits = HTBL_BITS;
  2377. hf->tbl = malloc(((size_t)1 << bits) * sizeof(hf->tbl[0]));
  2378. if (hf->tbl == NULL)
  2379. return (ARCHIVE_FATAL);
  2380. }
  2381. if (hf->tree == NULL && tbl_bits > HTBL_BITS) {
  2382. hf->tree_avail = 1 << (tbl_bits - HTBL_BITS + 4);
  2383. hf->tree = malloc(hf->tree_avail * sizeof(hf->tree[0]));
  2384. if (hf->tree == NULL)
  2385. return (ARCHIVE_FATAL);
  2386. }
  2387. hf->len_size = (int)len_size;
  2388. hf->tbl_bits = tbl_bits;
  2389. return (ARCHIVE_OK);
  2390. }
  2391. static void
  2392. lzh_huffman_free(struct huffman *hf)
  2393. {
  2394. free(hf->bitlen);
  2395. free(hf->tbl);
  2396. free(hf->tree);
  2397. }
  2398. static const char bitlen_tbl[0x400] = {
  2399. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2400. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2401. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2402. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2403. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2404. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2405. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2406. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2407. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2408. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2409. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2410. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2411. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2412. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2413. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2414. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2415. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2416. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2417. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2418. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2419. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2420. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2421. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2422. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2423. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2424. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2425. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2426. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2427. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2428. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2429. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2430. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2431. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2432. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2433. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2434. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2435. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2436. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2437. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2438. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2439. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2440. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2441. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2442. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2443. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2444. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2445. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2446. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  2447. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2448. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2449. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2450. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2451. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2452. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2453. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2454. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  2455. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
  2456. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
  2457. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
  2458. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
  2459. 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  2460. 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  2461. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2462. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 0
  2463. };
  2464. static int
  2465. lzh_read_pt_bitlen(struct lzh_stream *strm, int start, int end)
  2466. {
  2467. struct lzh_dec *ds = strm->ds;
  2468. struct lzh_br *br = &(ds->br);
  2469. int c, i;
  2470. for (i = start; i < end; ) {
  2471. /*
  2472. * bit pattern the number we need
  2473. * 000 -> 0
  2474. * 001 -> 1
  2475. * 010 -> 2
  2476. * ...
  2477. * 110 -> 6
  2478. * 1110 -> 7
  2479. * 11110 -> 8
  2480. * ...
  2481. * 1111111111110 -> 16
  2482. */
  2483. if (!lzh_br_read_ahead(strm, br, 3))
  2484. return (i);
  2485. if ((c = lzh_br_bits(br, 3)) == 7) {
  2486. if (!lzh_br_read_ahead(strm, br, 13))
  2487. return (i);
  2488. c = bitlen_tbl[lzh_br_bits(br, 13) & 0x3FF];
  2489. if (c)
  2490. lzh_br_consume(br, c - 3);
  2491. else
  2492. return (-1);/* Invalid data. */
  2493. } else
  2494. lzh_br_consume(br, 3);
  2495. ds->pt.bitlen[i++] = c;
  2496. ds->pt.freq[c]++;
  2497. }
  2498. return (i);
  2499. }
  2500. static int
  2501. lzh_make_fake_table(struct huffman *hf, uint16_t c)
  2502. {
  2503. if (c >= hf->len_size)
  2504. return (0);
  2505. hf->tbl[0] = c;
  2506. hf->max_bits = 0;
  2507. hf->shift_bits = 0;
  2508. hf->bitlen[hf->tbl[0]] = 0;
  2509. return (1);
  2510. }
  2511. /*
  2512. * Make a huffman coding table.
  2513. */
  2514. static int
  2515. lzh_make_huffman_table(struct huffman *hf)
  2516. {
  2517. uint16_t *tbl;
  2518. const unsigned char *bitlen;
  2519. int bitptn[17], weight[17];
  2520. int i, maxbits = 0, ptn, tbl_size, w;
  2521. int diffbits, len_avail;
  2522. /*
  2523. * Initialize bit patterns.
  2524. */
  2525. ptn = 0;
  2526. for (i = 1, w = 1 << 15; i <= 16; i++, w >>= 1) {
  2527. bitptn[i] = ptn;
  2528. weight[i] = w;
  2529. if (hf->freq[i]) {
  2530. ptn += hf->freq[i] * w;
  2531. maxbits = i;
  2532. }
  2533. }
  2534. if (ptn != 0x10000 || maxbits > hf->tbl_bits)
  2535. return (0);/* Invalid */
  2536. hf->max_bits = maxbits;
  2537. /*
  2538. * Cut out extra bits which we won't house in the table.
  2539. * This preparation reduces the same calculation in the for-loop
  2540. * making the table.
  2541. */
  2542. if (maxbits < 16) {
  2543. int ebits = 16 - maxbits;
  2544. for (i = 1; i <= maxbits; i++) {
  2545. bitptn[i] >>= ebits;
  2546. weight[i] >>= ebits;
  2547. }
  2548. }
  2549. if (maxbits > HTBL_BITS) {
  2550. unsigned htbl_max;
  2551. uint16_t *p;
  2552. diffbits = maxbits - HTBL_BITS;
  2553. for (i = 1; i <= HTBL_BITS; i++) {
  2554. bitptn[i] >>= diffbits;
  2555. weight[i] >>= diffbits;
  2556. }
  2557. htbl_max = bitptn[HTBL_BITS] +
  2558. weight[HTBL_BITS] * hf->freq[HTBL_BITS];
  2559. p = &(hf->tbl[htbl_max]);
  2560. while (p < &hf->tbl[1U<<HTBL_BITS])
  2561. *p++ = 0;
  2562. } else
  2563. diffbits = 0;
  2564. hf->shift_bits = diffbits;
  2565. /*
  2566. * Make the table.
  2567. */
  2568. tbl_size = 1 << HTBL_BITS;
  2569. tbl = hf->tbl;
  2570. bitlen = hf->bitlen;
  2571. len_avail = hf->len_avail;
  2572. hf->tree_used = 0;
  2573. for (i = 0; i < len_avail; i++) {
  2574. uint16_t *p;
  2575. int len, cnt;
  2576. uint16_t bit;
  2577. int extlen;
  2578. struct htree_t *ht;
  2579. if (bitlen[i] == 0)
  2580. continue;
  2581. /* Get a bit pattern */
  2582. len = bitlen[i];
  2583. ptn = bitptn[len];
  2584. cnt = weight[len];
  2585. if (len <= HTBL_BITS) {
  2586. /* Calculate next bit pattern */
  2587. if ((bitptn[len] = ptn + cnt) > tbl_size)
  2588. return (0);/* Invalid */
  2589. /* Update the table */
  2590. p = &(tbl[ptn]);
  2591. if (cnt > 7) {
  2592. uint16_t *pc;
  2593. cnt -= 8;
  2594. pc = &p[cnt];
  2595. pc[0] = (uint16_t)i;
  2596. pc[1] = (uint16_t)i;
  2597. pc[2] = (uint16_t)i;
  2598. pc[3] = (uint16_t)i;
  2599. pc[4] = (uint16_t)i;
  2600. pc[5] = (uint16_t)i;
  2601. pc[6] = (uint16_t)i;
  2602. pc[7] = (uint16_t)i;
  2603. if (cnt > 7) {
  2604. cnt -= 8;
  2605. memcpy(&p[cnt], pc,
  2606. 8 * sizeof(uint16_t));
  2607. pc = &p[cnt];
  2608. while (cnt > 15) {
  2609. cnt -= 16;
  2610. memcpy(&p[cnt], pc,
  2611. 16 * sizeof(uint16_t));
  2612. }
  2613. }
  2614. if (cnt)
  2615. memcpy(p, pc, cnt * sizeof(uint16_t));
  2616. } else {
  2617. while (cnt > 1) {
  2618. p[--cnt] = (uint16_t)i;
  2619. p[--cnt] = (uint16_t)i;
  2620. }
  2621. if (cnt)
  2622. p[--cnt] = (uint16_t)i;
  2623. }
  2624. continue;
  2625. }
  2626. /*
  2627. * A bit length is too big to be housed to a direct table,
  2628. * so we use a tree model for its extra bits.
  2629. */
  2630. bitptn[len] = ptn + cnt;
  2631. bit = 1U << (diffbits -1);
  2632. extlen = len - HTBL_BITS;
  2633. p = &(tbl[ptn >> diffbits]);
  2634. if (*p == 0) {
  2635. *p = len_avail + hf->tree_used;
  2636. ht = &(hf->tree[hf->tree_used++]);
  2637. if (hf->tree_used > hf->tree_avail)
  2638. return (0);/* Invalid */
  2639. ht->left = 0;
  2640. ht->right = 0;
  2641. } else {
  2642. if (*p < len_avail ||
  2643. *p >= (len_avail + hf->tree_used))
  2644. return (0);/* Invalid */
  2645. ht = &(hf->tree[*p - len_avail]);
  2646. }
  2647. while (--extlen > 0) {
  2648. if (ptn & bit) {
  2649. if (ht->left < len_avail) {
  2650. ht->left = len_avail + hf->tree_used;
  2651. ht = &(hf->tree[hf->tree_used++]);
  2652. if (hf->tree_used > hf->tree_avail)
  2653. return (0);/* Invalid */
  2654. ht->left = 0;
  2655. ht->right = 0;
  2656. } else {
  2657. ht = &(hf->tree[ht->left - len_avail]);
  2658. }
  2659. } else {
  2660. if (ht->right < len_avail) {
  2661. ht->right = len_avail + hf->tree_used;
  2662. ht = &(hf->tree[hf->tree_used++]);
  2663. if (hf->tree_used > hf->tree_avail)
  2664. return (0);/* Invalid */
  2665. ht->left = 0;
  2666. ht->right = 0;
  2667. } else {
  2668. ht = &(hf->tree[ht->right - len_avail]);
  2669. }
  2670. }
  2671. bit >>= 1;
  2672. }
  2673. if (ptn & bit) {
  2674. if (ht->left != 0)
  2675. return (0);/* Invalid */
  2676. ht->left = (uint16_t)i;
  2677. } else {
  2678. if (ht->right != 0)
  2679. return (0);/* Invalid */
  2680. ht->right = (uint16_t)i;
  2681. }
  2682. }
  2683. return (1);
  2684. }
  2685. static int
  2686. lzh_decode_huffman_tree(struct huffman *hf, unsigned rbits, int c)
  2687. {
  2688. struct htree_t *ht;
  2689. int extlen;
  2690. ht = hf->tree;
  2691. extlen = hf->shift_bits;
  2692. while (c >= hf->len_avail) {
  2693. c -= hf->len_avail;
  2694. if (extlen-- <= 0 || c >= hf->tree_used)
  2695. return (0);
  2696. if (rbits & (1U << extlen))
  2697. c = ht[c].left;
  2698. else
  2699. c = ht[c].right;
  2700. }
  2701. return (c);
  2702. }
  2703. static inline int
  2704. lzh_decode_huffman(struct huffman *hf, unsigned rbits)
  2705. {
  2706. int c;
  2707. /*
  2708. * At first search an index table for a bit pattern.
  2709. * If it fails, search a huffman tree for.
  2710. */
  2711. c = hf->tbl[rbits >> hf->shift_bits];
  2712. if (c < hf->len_avail || hf->len_avail == 0)
  2713. return (c);
  2714. /* This bit pattern needs to be found out at a huffman tree. */
  2715. return (lzh_decode_huffman_tree(hf, rbits, c));
  2716. }