archive_read_support_format_lha.c 83 KB

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