pngfix.c 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049
  1. /* pngfix.c
  2. *
  3. * Last changed in libpng 1.6.31 [July 27, 2017]
  4. * Copyright (c) 2014-2017 John Cunningham Bowler
  5. *
  6. * This code is released under the libpng license.
  7. * For conditions of distribution and use, see the disclaimer
  8. * and license in png.h
  9. *
  10. * Tool to check and fix the zlib inflate 'too far back' problem.
  11. * See the usage message for more information.
  12. */
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <ctype.h>
  17. #include <limits.h>
  18. #include <errno.h>
  19. #include <assert.h>
  20. #define implies(x,y) assert(!(x) || (y))
  21. #ifdef __GNUC__
  22. /* This is used to fix the error:
  23. *
  24. * pngfix.c:
  25. * In function 'zlib_advance':
  26. * pngfix.c:181:13: error: assuming signed overflow does not
  27. * occur when simplifying conditional to constant [-Werror=strict-overflow]
  28. */
  29. # define FIX_GCC volatile
  30. #else
  31. # define FIX_GCC
  32. #endif
  33. #define PROGRAM_NAME "pngfix"
  34. /* Define the following to use this program against your installed libpng,
  35. * rather than the one being built here:
  36. */
  37. #ifdef PNG_FREESTANDING_TESTS
  38. # include <png.h>
  39. #else
  40. # include "../../png.h"
  41. #endif
  42. #if PNG_LIBPNG_VER < 10603 /* 1.6.3 */
  43. # error "pngfix will not work with libpng prior to 1.6.3"
  44. #endif
  45. #ifdef PNG_SETJMP_SUPPORTED
  46. #include <setjmp.h>
  47. #if defined(PNG_READ_SUPPORTED) && defined(PNG_EASY_ACCESS_SUPPORTED) &&\
  48. (defined(PNG_READ_DEINTERLACE_SUPPORTED) ||\
  49. defined(PNG_READ_INTERLACING_SUPPORTED))
  50. /* zlib.h defines the structure z_stream, an instance of which is included
  51. * in this structure and is required for decompressing the LZ compressed
  52. * data in PNG files.
  53. */
  54. #ifndef ZLIB_CONST
  55. /* We must ensure that zlib uses 'const' in declarations. */
  56. # define ZLIB_CONST
  57. #endif
  58. #include <zlib.h>
  59. #ifdef const
  60. /* zlib.h sometimes #defines const to nothing, undo this. */
  61. # undef const
  62. #endif
  63. /* zlib.h has mediocre z_const use before 1.2.6, this stuff is for compatibility
  64. * with older builds.
  65. */
  66. #if ZLIB_VERNUM < 0x1260
  67. # define PNGZ_MSG_CAST(s) constcast(char*,s)
  68. # define PNGZ_INPUT_CAST(b) constcast(png_bytep,b)
  69. #else
  70. # define PNGZ_MSG_CAST(s) (s)
  71. # define PNGZ_INPUT_CAST(b) (b)
  72. #endif
  73. #ifndef PNG_MAXIMUM_INFLATE_WINDOW
  74. # error "pngfix not supported in this libpng version"
  75. #endif
  76. #if ZLIB_VERNUM >= 0x1240
  77. /* Copied from pngpriv.h */
  78. #ifdef __cplusplus
  79. # define voidcast(type, value) static_cast<type>(value)
  80. # define constcast(type, value) const_cast<type>(value)
  81. # define aligncast(type, value) \
  82. static_cast<type>(static_cast<void*>(value))
  83. # define aligncastconst(type, value) \
  84. static_cast<type>(static_cast<const void*>(value))
  85. #else
  86. # define voidcast(type, value) (value)
  87. # define constcast(type, value) ((type)(value))
  88. # define aligncast(type, value) ((void*)(value))
  89. # define aligncastconst(type, value) ((const void*)(value))
  90. #endif /* __cplusplus */
  91. #if PNG_LIBPNG_VER < 10700
  92. /* Chunk tags (copied from pngpriv.h) */
  93. #define PNG_32b(b,s) ((png_uint_32)(b) << (s))
  94. #define PNG_U32(b1,b2,b3,b4) \
  95. (PNG_32b(b1,24) | PNG_32b(b2,16) | PNG_32b(b3,8) | PNG_32b(b4,0))
  96. /* Constants for known chunk types. */
  97. #define png_IDAT PNG_U32( 73, 68, 65, 84)
  98. #define png_IEND PNG_U32( 73, 69, 78, 68)
  99. #define png_IHDR PNG_U32( 73, 72, 68, 82)
  100. #define png_PLTE PNG_U32( 80, 76, 84, 69)
  101. #define png_bKGD PNG_U32( 98, 75, 71, 68)
  102. #define png_cHRM PNG_U32( 99, 72, 82, 77)
  103. #define png_fRAc PNG_U32(102, 82, 65, 99) /* registered, not defined */
  104. #define png_gAMA PNG_U32(103, 65, 77, 65)
  105. #define png_gIFg PNG_U32(103, 73, 70, 103)
  106. #define png_gIFt PNG_U32(103, 73, 70, 116) /* deprecated */
  107. #define png_gIFx PNG_U32(103, 73, 70, 120)
  108. #define png_hIST PNG_U32(104, 73, 83, 84)
  109. #define png_iCCP PNG_U32(105, 67, 67, 80)
  110. #define png_iTXt PNG_U32(105, 84, 88, 116)
  111. #define png_oFFs PNG_U32(111, 70, 70, 115)
  112. #define png_pCAL PNG_U32(112, 67, 65, 76)
  113. #define png_pHYs PNG_U32(112, 72, 89, 115)
  114. #define png_sBIT PNG_U32(115, 66, 73, 84)
  115. #define png_sCAL PNG_U32(115, 67, 65, 76)
  116. #define png_sPLT PNG_U32(115, 80, 76, 84)
  117. #define png_sRGB PNG_U32(115, 82, 71, 66)
  118. #define png_sTER PNG_U32(115, 84, 69, 82)
  119. #define png_tEXt PNG_U32(116, 69, 88, 116)
  120. #define png_tIME PNG_U32(116, 73, 77, 69)
  121. #define png_tRNS PNG_U32(116, 82, 78, 83)
  122. #define png_zTXt PNG_U32(122, 84, 88, 116)
  123. #endif
  124. /* The 8-byte signature as a pair of 32-bit quantities */
  125. #define sig1 PNG_U32(137, 80, 78, 71)
  126. #define sig2 PNG_U32( 13, 10, 26, 10)
  127. /* Is the chunk critical? */
  128. #define CRITICAL(chunk) (((chunk) & PNG_U32(32,0,0,0)) == 0)
  129. /* Is it safe to copy? */
  130. #define SAFE_TO_COPY(chunk) (((chunk) & PNG_U32(0,0,0,32)) != 0)
  131. /* Fix ups for builds with limited read support */
  132. #ifndef PNG_ERROR_TEXT_SUPPORTED
  133. # define png_error(a,b) png_err(a)
  134. #endif
  135. /********************************* UTILITIES **********************************/
  136. /* UNREACHED is a value to cause an assert to fail. Because of the way the
  137. * assert macro is written the string "UNREACHED" is produced in the error
  138. * message.
  139. */
  140. #define UNREACHED 0
  141. /* 80-bit number handling - a PNG image can be up to (2^31-1)x(2^31-1) 8-byte
  142. * (16-bit RGBA) pixels in size; that's less than 2^65 bytes or 2^68 bits, so
  143. * arithmetic of 80-bit numbers is sufficient. This representation uses an
  144. * arbitrary length array of png_uint_16 digits (0..65535). The representation
  145. * is little endian.
  146. *
  147. * The arithmetic functions take zero to two uarb values together with the
  148. * number of digits in those values and write the result to the given uarb
  149. * (always the first argument) returning the number of digits in the result.
  150. * If the result is negative the return value is also negative (this would
  151. * normally be an error).
  152. */
  153. typedef png_uint_16 udigit; /* A 'unum' is an array of these */
  154. typedef png_uint_16p uarb;
  155. typedef png_const_uint_16p uarbc;
  156. #define UDIGITS(unum) ((sizeof unum)/(sizeof (udigit))
  157. /* IMPORTANT: only apply this to an array, applied to a pointer the result
  158. * will typically be '2', which is not useful.
  159. */
  160. static int
  161. uarb_set(uarb result, png_alloc_size_t val)
  162. /* Set (initialize) 'result' to 'val'. The size required for 'result' must
  163. * be determined by the caller from a knowledge of the maximum for 'val'.
  164. */
  165. {
  166. int ndigits = 0;
  167. while (val > 0)
  168. {
  169. result[ndigits++] = (png_uint_16)(val & 0xffff);
  170. val >>= 16;
  171. }
  172. return ndigits;
  173. }
  174. static int
  175. uarb_copy(uarb to, uarb from, int idigits)
  176. /* Copy a uarb, may reduce the digit count */
  177. {
  178. int d, odigits;
  179. for (d=odigits=0; d<idigits; ++d)
  180. if ((to[d] = from[d]) != 0)
  181. odigits = d+1;
  182. return odigits;
  183. }
  184. static int
  185. uarb_inc(uarb num, int in_digits, png_int_32 add)
  186. /* This is a signed 32-bit add, except that to avoid overflow the value added
  187. * or subtracted must be no more than 2^31-65536. A negative result
  188. * indicates a negative number (which is an error below). The size of
  189. * 'num' should be max(in_digits+1,2) for arbitrary 'add' but can be just
  190. * in_digits+1 if add is known to be in the range -65535..65535.
  191. */
  192. {
  193. FIX_GCC int out_digits = 0;
  194. while (out_digits < in_digits)
  195. {
  196. add += num[out_digits];
  197. num[out_digits++] = (png_uint_16)(add & 0xffff);
  198. add >>= 16;
  199. }
  200. while (add != 0 && add != (-1))
  201. {
  202. num[out_digits++] = (png_uint_16)(add & 0xffff);
  203. add >>= 16;
  204. }
  205. if (add == 0)
  206. {
  207. while (out_digits > 0 && num[out_digits-1] == 0)
  208. --out_digits;
  209. return out_digits; /* may be 0 */
  210. }
  211. else /* negative result */
  212. {
  213. while (out_digits > 1 && num[out_digits-1] == 0xffff)
  214. --out_digits;
  215. return -out_digits;
  216. }
  217. }
  218. static int
  219. uarb_add32(uarb num, int in_digits, png_uint_32 add)
  220. /* As above but this works with any 32-bit value and only does 'add' */
  221. {
  222. if (in_digits > 0)
  223. {
  224. in_digits = uarb_inc(num, in_digits, add & 0xffff);
  225. return uarb_inc(num+1, in_digits-1, add >> 16)+1;
  226. }
  227. return uarb_set(num, add);
  228. }
  229. static int
  230. uarb_mult_digit(uarb acc, int a_digits, uarb num, FIX_GCC int n_digits,
  231. png_uint_16 val)
  232. /* Primitive one-digit multiply - 'val' must be 0..65535. Note that this
  233. * primitive is a multiply and accumulate - the result of *num * val is added
  234. * to *acc.
  235. *
  236. * This is a one-digit multiply, so the product may be up to one digit longer
  237. * than 'num', however the add to 'acc' means that the caller must ensure
  238. * that 'acc' is at least one digit longer than this *and* at least one digit
  239. * longer than the current length of 'acc'. (Or the caller must otherwise
  240. * ensure 'adigits' is adequate from knowledge of the values.)
  241. */
  242. {
  243. /* The digits in *acc, *num and val are in the range 0..65535, so the
  244. * result below is at most (65535*65535)+2*65635 = 65535*(65535+2), which is
  245. * exactly 0xffffffff.
  246. */
  247. if (val > 0 && n_digits > 0) /* Else the product is 0 */
  248. {
  249. png_uint_32 carry = 0;
  250. int out_digits = 0;
  251. while (out_digits < n_digits || carry > 0)
  252. {
  253. if (out_digits < a_digits)
  254. carry += acc[out_digits];
  255. if (out_digits < n_digits)
  256. carry += (png_uint_32)num[out_digits] * val;
  257. acc[out_digits++] = (png_uint_16)(carry & 0xffff);
  258. carry >>= 16;
  259. }
  260. /* So carry is 0 and all the input digits have been consumed. This means
  261. * that it is possible to skip any remaining digits in acc.
  262. */
  263. if (out_digits > a_digits)
  264. return out_digits;
  265. }
  266. return a_digits;
  267. }
  268. static int
  269. uarb_mult32(uarb acc, int a_digits, uarb num, int n_digits, png_uint_32 val)
  270. /* calculate acc += num * val, 'val' may be any 32-bit value, 'acc' and 'num'
  271. * may be any value, returns the number of digits in 'acc'.
  272. */
  273. {
  274. if (n_digits > 0 && val > 0)
  275. {
  276. a_digits = uarb_mult_digit(acc, a_digits, num, n_digits,
  277. (png_uint_16)(val & 0xffff));
  278. val >>= 16;
  279. if (val > 0)
  280. a_digits = uarb_mult_digit(acc+1, a_digits-1, num, n_digits,
  281. (png_uint_16)val) + 1;
  282. /* Because n_digits and val are >0 the following must be true: */
  283. assert(a_digits > 0);
  284. }
  285. return a_digits;
  286. }
  287. static int
  288. uarb_shift(uarb inout, int ndigits, unsigned int right_shift)
  289. /* Shift inout right by right_shift bits, right_shift must be in the range
  290. * 1..15
  291. */
  292. {
  293. FIX_GCC int i = ndigits;
  294. png_uint_16 carry = 0;
  295. assert(right_shift >= 1 && right_shift <= 15);
  296. while (--i >= 0)
  297. {
  298. png_uint_16 temp = (png_uint_16)(carry | (inout[i] >> right_shift));
  299. /* Bottom bits to top bits of carry */
  300. carry = (png_uint_16)((inout[i] << (16-right_shift)) & 0xffff);
  301. inout[i] = temp;
  302. /* The shift may reduce ndigits */
  303. if (i == ndigits-1 && temp == 0)
  304. ndigits = i;
  305. }
  306. return ndigits;
  307. }
  308. static int
  309. uarb_cmp(uarb a, int adigits, uarb b, int bdigits)
  310. /* Return -1/0/+1 according as a<b/a==b/a>b */
  311. {
  312. if (adigits < bdigits)
  313. return -1;
  314. if (adigits > bdigits)
  315. return 1;
  316. while (adigits-- > 0)
  317. if (a[adigits] < b[adigits])
  318. return -1;
  319. else if (a[adigits] > b[adigits])
  320. return 1;
  321. return 0;
  322. }
  323. #if 0 /*UNUSED*/
  324. static int
  325. uarb_eq32(uarb num, int digits, png_uint_32 val)
  326. /* Return true if the uarb is equal to 'val' */
  327. {
  328. switch (digits)
  329. {
  330. case 0: return val == 0;
  331. case 1: return val == num[0];
  332. case 2: return (val & 0xffff) == num[0] && (val >> 16) == num[1];
  333. default: return 0;
  334. }
  335. }
  336. #endif
  337. static void
  338. uarb_printx(uarb num, int digits, FILE *out)
  339. /* Print 'num' as a hexadecimal number (easier than decimal!) */
  340. {
  341. while (digits > 0)
  342. if (num[--digits] > 0)
  343. {
  344. fprintf(out, "0x%x", num[digits]);
  345. while (digits > 0)
  346. fprintf(out, "%.4x", num[--digits]);
  347. }
  348. else if (digits == 0) /* the number is 0 */
  349. fputs("0x0", out);
  350. }
  351. static void
  352. uarb_print(uarb num, int digits, FILE *out)
  353. /* Prints 'num' as a decimal if it will fit in an unsigned long, else as a
  354. * hexadecimal number. Notice that the results vary for images over 4GByte
  355. * in a system dependent way, and the hexadecimal form doesn't work very well
  356. * in awk script input.
  357. *
  358. *
  359. * TODO: write uarb_div10
  360. */
  361. {
  362. if (digits * sizeof (udigit) > sizeof (unsigned long))
  363. uarb_printx(num, digits, out);
  364. else
  365. {
  366. unsigned long n = 0;
  367. while (digits > 0)
  368. n = (n << 16) + num[--digits];
  369. fprintf(out, "%lu", n);
  370. }
  371. }
  372. /* Generate random bytes. This uses a boring repeatable algorithm and it
  373. * is implemented here so that it gives the same set of numbers on every
  374. * architecture. It's a linear congruential generator (Knuth or Sedgewick
  375. * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
  376. * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
  377. * Generation.)
  378. *
  379. * (Copied from contrib/libtests/pngvalid.c)
  380. */
  381. static void
  382. make_random_bytes(png_uint_32* seed, void* pv, size_t size)
  383. {
  384. png_uint_32 u0 = seed[0], u1 = seed[1];
  385. png_bytep bytes = voidcast(png_bytep, pv);
  386. /* There are thirty-three bits; the next bit in the sequence is bit-33 XOR
  387. * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
  388. */
  389. size_t i;
  390. for (i=0; i<size; ++i)
  391. {
  392. /* First generate 8 new bits then shift them in at the end. */
  393. png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
  394. u1 <<= 8;
  395. u1 |= u0 >> 24;
  396. u0 <<= 8;
  397. u0 |= u;
  398. *bytes++ = (png_byte)u;
  399. }
  400. seed[0] = u0;
  401. seed[1] = u1;
  402. }
  403. /* Clear an object to a random value. */
  404. static void
  405. clear(void *pv, size_t size)
  406. {
  407. static png_uint_32 clear_seed[2] = { 0x12345678, 0x9abcdef0 };
  408. make_random_bytes(clear_seed, pv, size);
  409. }
  410. #define CLEAR(object) clear(&(object), sizeof (object))
  411. /* Copied from unreleased 1.7 code.
  412. *
  413. * CRC checking uses a local pre-built implementation of the Ethernet CRC32.
  414. * This is to avoid a function call to the zlib DLL and to optimize the
  415. * byte-by-byte case.
  416. */
  417. static png_uint_32 crc_table[256] =
  418. {
  419. 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
  420. 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
  421. 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
  422. 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
  423. 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
  424. 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
  425. 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
  426. 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
  427. 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
  428. 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
  429. 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
  430. 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
  431. 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
  432. 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
  433. 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
  434. 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
  435. 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
  436. 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
  437. 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
  438. 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
  439. 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
  440. 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
  441. 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
  442. 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
  443. 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
  444. 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
  445. 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
  446. 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
  447. 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
  448. 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
  449. 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
  450. 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
  451. 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
  452. 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
  453. 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
  454. 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
  455. 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
  456. 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
  457. 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
  458. 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
  459. 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
  460. 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
  461. 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
  462. 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
  463. 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
  464. 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
  465. 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
  466. 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
  467. 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
  468. 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
  469. 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
  470. 0x2d02ef8d
  471. };
  472. /* The CRC calculated here *IS* conditioned, the corresponding value used by
  473. * zlib and the result value is obtained by XORing with CRC_INIT, which is also
  474. * the first value that must be passed in (for the first byte) to crc_one_byte.
  475. */
  476. #define CRC_INIT 0xffffffff
  477. static png_uint_32
  478. crc_one_byte(png_uint_32 crc, int b)
  479. {
  480. return crc_table[(crc ^ b) & 0xff] ^ (crc >> 8);
  481. }
  482. static png_uint_32
  483. crc_init_4(png_uint_32 value)
  484. {
  485. /* This is an alternative to the algorithm used in zlib, which requires four
  486. * separate tables to parallelize the four byte operations, it only works for
  487. * a CRC of the first four bytes of the stream, but this is what happens in
  488. * the parser below where length+chunk-name is read and chunk-name used to
  489. * initialize the CRC. Notice that the calculation here avoids repeated
  490. * conditioning (xor with 0xffffffff) by storing the conditioned value.
  491. */
  492. png_uint_32 crc = crc_table[(~value >> 24)] ^ 0xffffff;
  493. crc = crc_table[(crc ^ (value >> 16)) & 0xff] ^ (crc >> 8);
  494. crc = crc_table[(crc ^ (value >> 8)) & 0xff] ^ (crc >> 8);
  495. return crc_table[(crc ^ value) & 0xff] ^ (crc >> 8);
  496. }
  497. static int
  498. chunk_type_valid(png_uint_32 c)
  499. /* Bit whacking approach to chunk name validation that is intended to avoid
  500. * branches. The cost is that it uses a lot of 32-bit constants, which might
  501. * be bad on some architectures.
  502. */
  503. {
  504. png_uint_32 t;
  505. /* Remove bit 5 from all but the reserved byte; this means every
  506. * 8-bit unit must be in the range 65-90 to be valid. So bit 5
  507. * must be zero, bit 6 must be set and bit 7 zero.
  508. */
  509. c &= ~PNG_U32(32,32,0,32);
  510. t = (c & ~0x1f1f1f1f) ^ 0x40404040;
  511. /* Subtract 65 for each 8-bit quantity, this must not overflow
  512. * and each byte must then be in the range 0-25.
  513. */
  514. c -= PNG_U32(65,65,65,65);
  515. t |=c ;
  516. /* Subtract 26, handling the overflow which should set the top
  517. * three bits of each byte.
  518. */
  519. c -= PNG_U32(25,25,25,26);
  520. t |= ~c;
  521. return (t & 0xe0e0e0e0) == 0;
  522. }
  523. /**************************** CONTROL INFORMATION *****************************/
  524. /* Information about a sequence of IDAT chunks, the chunks have been re-synced
  525. * using sync_stream below and the new lengths are recorded here. Because the
  526. * number of chunks is unlimited this is handled using a linked list of these
  527. * structures.
  528. */
  529. struct IDAT_list
  530. {
  531. struct IDAT_list *next; /* Linked list */
  532. unsigned int length; /* Actual length of the array below */
  533. unsigned int count; /* Number of entries that are valid */
  534. # define IDAT_INIT_LENGTH 16
  535. png_uint_32 lengths[IDAT_INIT_LENGTH];
  536. };
  537. static void
  538. IDAT_list_init(struct IDAT_list *list)
  539. {
  540. CLEAR(*list);
  541. list->next = NULL;
  542. list->length = IDAT_INIT_LENGTH;
  543. }
  544. static size_t
  545. IDAT_list_size(struct IDAT_list *list, unsigned int length)
  546. /* Return the size in bytes of an IDAT_list of the given length. */
  547. {
  548. if (list != NULL)
  549. length = list->length;
  550. return sizeof *list - sizeof list->lengths +
  551. length * sizeof list->lengths[0];
  552. }
  553. static void
  554. IDAT_list_end(struct IDAT_list *IDAT_list)
  555. {
  556. struct IDAT_list *list = IDAT_list->next;
  557. CLEAR(*IDAT_list);
  558. while (list != NULL)
  559. {
  560. struct IDAT_list *next = list->next;
  561. clear(list, IDAT_list_size(list, 0));
  562. free(list);
  563. list = next;
  564. }
  565. }
  566. static struct IDAT_list *
  567. IDAT_list_extend(struct IDAT_list *tail)
  568. {
  569. /* Use the previous cached value if available. */
  570. struct IDAT_list *next = tail->next;
  571. if (next == NULL)
  572. {
  573. /* Insert a new, malloc'ed, block of IDAT information buffers, this
  574. * one twice as large as the previous one:
  575. */
  576. unsigned int length = 2 * tail->length;
  577. if (length < tail->length) /* arithmetic overflow */
  578. length = tail->length;
  579. next = voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length)));
  580. CLEAR(*next);
  581. /* The caller must handle this: */
  582. if (next == NULL)
  583. return NULL;
  584. next->next = NULL;
  585. next->length = length;
  586. tail->next = next;
  587. }
  588. return next;
  589. }
  590. /* GLOBAL CONTROL STRUCTURE */
  591. struct global
  592. {
  593. /* PUBLIC GLOBAL VARIABLES: OWNER INITIALIZE */
  594. unsigned int errors :1; /* print file errors to stderr */
  595. unsigned int warnings :1; /* print libpng warnings to stderr */
  596. unsigned int optimize_zlib :1; /* Run optimization search */
  597. unsigned int quiet :2; /* don't output summaries */
  598. unsigned int verbose :3; /* various internal tracking */
  599. unsigned int skip :3; /* Non-critical chunks to skip */
  600. # define SKIP_NONE 0
  601. # define SKIP_BAD_CRC 1 /* Chunks with a bad CRC */
  602. # define SKIP_UNSAFE 2 /* Chunks not safe to copy */
  603. # define SKIP_UNUSED 3 /* Chunks not used by libpng */
  604. # define SKIP_TRANSFORM 4 /* Chunks only used in transforms */
  605. # define SKIP_COLOR 5 /* Everything but tRNS, sBIT, gAMA and sRGB */
  606. # define SKIP_ALL 6 /* Everything but tRNS and sBIT */
  607. png_uint_32 idat_max; /* 0 to perform no re-chunking */
  608. int status_code; /* Accumulated status code */
  609. # define TOO_FAR_BACK 0x01 /* found a too-far-back error */
  610. # define CRC_ERROR 0x02 /* fixed an invalid CRC */
  611. # define STREAM_ERROR 0x04 /* damaged PNG stream (may be fixable) */
  612. # define TRUNCATED 0x08 /* truncated but still readable */
  613. # define FILE_ERROR 0x10 /* could not read the file */
  614. # define WRITE_ERROR 0x20 /* write error (this terminates the read) */
  615. # define INTERNAL_ERROR 0x40 /* internal limits/errors encountered */
  616. /* PUBLIC GLOBAL VARIABLES: USED INTERNALLY BY IDAT READ CODE */
  617. struct IDAT_list idat_cache; /* Cache of file IDAT information buffers */
  618. /* The structure is shared across all uses of this global control
  619. * structure to avoid reallocation between IDAT streams.
  620. */
  621. };
  622. static int
  623. global_end(struct global *global)
  624. {
  625. int rc;
  626. IDAT_list_end(&global->idat_cache);
  627. rc = global->status_code;
  628. CLEAR(*global);
  629. return rc;
  630. }
  631. static void
  632. global_init(struct global *global)
  633. /* Call this once (and only once) to initialize the control */
  634. {
  635. CLEAR(*global);
  636. /* Globals */
  637. global->errors = 0;
  638. global->warnings = 0;
  639. global->quiet = 0;
  640. global->verbose = 0;
  641. global->idat_max = 0; /* no re-chunking of IDAT */
  642. global->optimize_zlib = 0;
  643. global->skip = SKIP_NONE;
  644. global->status_code = 0;
  645. IDAT_list_init(&global->idat_cache);
  646. }
  647. static int
  648. skip_chunk_type(const struct global *global, png_uint_32 type)
  649. /* Return true if this chunk is to be skipped according to the --strip
  650. * option. This code needs to recognize all known ancillary chunks in order
  651. * to handle the --strip=unsafe option.
  652. */
  653. {
  654. /* Never strip critical chunks: */
  655. if (CRITICAL(type))
  656. return 0;
  657. switch (type)
  658. {
  659. /* Chunks that are treated as, effectively, critical because they affect
  660. * correct interpretation of the pixel values:
  661. */
  662. case png_tRNS: case png_sBIT:
  663. return 0;
  664. /* Chunks that specify gamma encoding which should therefore only be
  665. * removed if the user insists:
  666. */
  667. case png_gAMA: case png_sRGB:
  668. if (global->skip >= SKIP_ALL)
  669. return 1;
  670. return 0;
  671. /* Chunks that affect color interpretation - not used by libpng and rarely
  672. * used by applications, but technically still required for correct
  673. * interpretation of the image data:
  674. */
  675. case png_cHRM: case png_iCCP:
  676. if (global->skip >= SKIP_COLOR)
  677. return 1;
  678. return 0;
  679. /* Other chunks that are used by libpng in image transformations (as
  680. * opposed to known chunks that have get/set APIs but are not otherwise
  681. * used.)
  682. */
  683. case png_bKGD:
  684. if (global->skip >= SKIP_TRANSFORM)
  685. return 1;
  686. return 0;
  687. /* All other chunks that libpng knows about and affect neither image
  688. * interpretation nor libpng transforms - chunks that are effectively
  689. * unused by libpng even though libpng might recognize and store them.
  690. */
  691. case png_fRAc: case png_gIFg: case png_gIFt: case png_gIFx: case png_hIST:
  692. case png_iTXt: case png_oFFs: case png_pCAL: case png_pHYs: case png_sCAL:
  693. case png_sPLT: case png_sTER: case png_tEXt: case png_tIME: case png_zTXt:
  694. if (global->skip >= SKIP_UNUSED)
  695. return 1;
  696. return 0;
  697. /* Chunks that libpng does not know about (notice that this depends on the
  698. * list above including all known chunks!) The decision here depends on
  699. * whether the safe-to-copy bit is set in the chunk type.
  700. */
  701. default:
  702. if (SAFE_TO_COPY(type))
  703. {
  704. if (global->skip >= SKIP_UNUSED) /* as above */
  705. return 1;
  706. }
  707. else if (global->skip >= SKIP_UNSAFE)
  708. return 1;
  709. return 0;
  710. }
  711. }
  712. /* PER-FILE CONTROL STRUCTURE */
  713. struct chunk;
  714. struct IDAT;
  715. struct file
  716. {
  717. /* ANCESTORS */
  718. struct global *global;
  719. /* PUBLIC PER-FILE VARIABLES: CALLER INITIALIZE */
  720. const char * file_name;
  721. const char * out_name; /* Name of output file (if required) */
  722. /* PUBLIC PER-FILE VARIABLES: SET BY PNG READ CODE */
  723. /* File specific result codes */
  724. int status_code; /* Set to a bit mask of the following: */
  725. int read_errno; /* Records a read error errno */
  726. int write_errno; /* Records a write error errno */
  727. /* IHDR information */
  728. png_uint_32 width;
  729. png_uint_32 height;
  730. png_byte bit_depth;
  731. png_byte color_type;
  732. png_byte compression_method;
  733. png_byte filter_method;
  734. png_byte interlace_method;
  735. udigit image_bytes[5];
  736. int image_digits;
  737. /* PROTECTED PER-FILE VARIABLES: USED BY THE READ CODE */
  738. FILE * file; /* Original PNG file */
  739. FILE * out; /* If a new one is being written */
  740. jmp_buf jmpbuf; /* Set while reading a PNG */
  741. /* PROTECTED CHUNK SPECIFIC VARIABLES: USED BY CHUNK CODE */
  742. /* The following variables are used during reading to record the length, type
  743. * and data position of the *next* chunk or, right at the start, the
  744. * signature (in length,type).
  745. *
  746. * When a chunk control structure is instantiated these values are copied
  747. * into the structure and can then be overritten with the data for the next
  748. * chunk.
  749. */
  750. fpos_t data_pos; /* Position of first byte of chunk data */
  751. png_uint_32 length; /* First word (length or signature start) */
  752. png_uint_32 type; /* Second word (type or signature end) */
  753. png_uint_32 crc; /* Running chunk CRC (used by read_chunk) */
  754. /* These counts are maintained by the read and write routines below and are
  755. * reset by the chunk handling code. They record the total number of bytes
  756. * read or written for the chunk, including the header (length,type) bytes.
  757. */
  758. png_uint_32 read_count; /* Count of bytes read (in the chunk) */
  759. png_uint_32 write_count; /* Count of bytes written (in the chunk) */
  760. int state; /* As defined here: */
  761. # define STATE_SIGNATURE 0 /* The signature is being written */
  762. # define STATE_CHUNKS 1 /* Non-IDAT chunks are being written */
  763. # define STATE_IDAT 2 /* An IDAT stream is being written */
  764. /* Two pointers used to enable clean-up in the event of fatal errors and to
  765. * hold state about the parser process (only one of each at present.)
  766. */
  767. struct chunk * chunk;
  768. struct IDAT * idat;
  769. /* Interface to allocate a new chunk or IDAT control structure. The result
  770. * is returned by setting one or other of the above variables. Note that the
  771. * relevant initializer is called by the allocator function. The alloc_ptr
  772. * is used only by the implementation of the allocate function.
  773. */
  774. void * alloc_ptr;
  775. void (*alloc)(struct file*,int idat);
  776. /* idat: allocate IDAT not chunk */
  777. };
  778. /* Valid longjmp (stop) codes are: */
  779. #define LIBPNG_WARNING_CODE 1 /* generic png_error */
  780. #define LIBPNG_ERROR_CODE 2 /* generic png_error */
  781. #define ZLIB_ERROR_CODE 3 /* generic zlib error */
  782. #define INVALID_ERROR_CODE 4 /* detected an invalid PNG */
  783. #define READ_ERROR_CODE 5 /* read failed */
  784. #define WRITE_ERROR_CODE 6 /* error in write */
  785. #define UNEXPECTED_ERROR_CODE 7 /* unexpected (internal?) error */
  786. static void
  787. emit_string(const char *str, FILE *out)
  788. /* Print a string with spaces replaced by '_' and non-printing characters by
  789. * an octal escape.
  790. */
  791. {
  792. for (; *str; ++str)
  793. if (isgraph(UCHAR_MAX & *str))
  794. putc(*str, out);
  795. else if (isspace(UCHAR_MAX & *str))
  796. putc('_', out);
  797. else
  798. fprintf(out, "\\%.3o", *str);
  799. }
  800. static const char *
  801. strcode(int code)
  802. {
  803. switch (code)
  804. {
  805. case LIBPNG_WARNING_CODE: return "warning";
  806. case LIBPNG_ERROR_CODE: return "libpng";
  807. case ZLIB_ERROR_CODE: return "zlib";
  808. case INVALID_ERROR_CODE: return "invalid";
  809. case READ_ERROR_CODE: return "read";
  810. case WRITE_ERROR_CODE: return "write";
  811. case UNEXPECTED_ERROR_CODE: return "unexpected";
  812. default: return "INVALID";
  813. }
  814. }
  815. static void
  816. emit_error(struct file *file, int code, const char *what)
  817. /* Generic error message routine, takes a 'stop' code but can be used
  818. * elsewhere. Always outputs a message.
  819. */
  820. {
  821. const char *reason;
  822. int err = 0;
  823. switch (code)
  824. {
  825. case LIBPNG_WARNING_CODE: reason = "libpng warning:"; break;
  826. case LIBPNG_ERROR_CODE: reason = "libpng error:"; break;
  827. case ZLIB_ERROR_CODE: reason = "zlib error:"; break;
  828. case INVALID_ERROR_CODE: reason = "invalid"; break;
  829. case READ_ERROR_CODE: reason = "read failure:";
  830. err = file->read_errno;
  831. break;
  832. case WRITE_ERROR_CODE: reason = "write error";
  833. err = file->write_errno;
  834. break;
  835. case UNEXPECTED_ERROR_CODE: reason = "unexpected error:";
  836. err = file->read_errno;
  837. if (err == 0)
  838. err = file->write_errno;
  839. break;
  840. default: reason = "INVALID (internal error):"; break;
  841. }
  842. if (err != 0)
  843. fprintf(stderr, "%s: %s %s [%s]\n", file->file_name, reason, what,
  844. strerror(err));
  845. else
  846. fprintf(stderr, "%s: %s %s\n", file->file_name, reason, what);
  847. }
  848. static void chunk_end(struct chunk **);
  849. static void IDAT_end(struct IDAT **);
  850. static int
  851. file_end(struct file *file)
  852. {
  853. int rc;
  854. /* If either of the chunk pointers are set end them here, the IDAT structure
  855. * must be deallocated first as it may deallocate the chunk structure.
  856. */
  857. if (file->idat != NULL)
  858. IDAT_end(&file->idat);
  859. if (file->chunk != NULL)
  860. chunk_end(&file->chunk);
  861. rc = file->status_code;
  862. if (file->file != NULL)
  863. (void)fclose(file->file);
  864. if (file->out != NULL)
  865. {
  866. /* NOTE: this is bitwise |, all the following functions must execute and
  867. * must succeed.
  868. */
  869. if (ferror(file->out) | fflush(file->out) | fclose(file->out))
  870. {
  871. perror(file->out_name);
  872. emit_error(file, READ_ERROR_CODE, "output write error");
  873. rc |= WRITE_ERROR;
  874. }
  875. }
  876. /* Accumulate the result codes */
  877. file->global->status_code |= rc;
  878. CLEAR(*file);
  879. return rc; /* status code: non-zero on read or write error */
  880. }
  881. static int
  882. file_init(struct file *file, struct global *global, const char *file_name,
  883. const char *out_name, void *alloc_ptr, void (*alloc)(struct file*,int))
  884. /* Initialize a file control structure. This will open the given files as
  885. * well. The status code returned is 0 on success, non zero (using the flags
  886. * above) on a file open error.
  887. */
  888. {
  889. CLEAR(*file);
  890. file->global = global;
  891. file->file_name = file_name;
  892. file->out_name = out_name;
  893. file->status_code = 0;
  894. file->read_errno = 0;
  895. file->write_errno = 0;
  896. file->file = NULL;
  897. file->out = NULL;
  898. /* jmpbuf is garbage: must be set by read_png */
  899. file->read_count = 0;
  900. file->state = STATE_SIGNATURE;
  901. file->chunk = NULL;
  902. file->idat = NULL;
  903. file->alloc_ptr = alloc_ptr;
  904. file->alloc = alloc;
  905. /* Open the files: */
  906. assert(file_name != NULL);
  907. file->file = fopen(file_name, "rb");
  908. if (file->file == NULL)
  909. {
  910. file->read_errno = errno;
  911. file->status_code |= FILE_ERROR;
  912. /* Always output: please give a readable file! */
  913. perror(file_name);
  914. return FILE_ERROR;
  915. }
  916. if (out_name != NULL)
  917. {
  918. file->out = fopen(out_name, "wb");
  919. if (file->out == NULL)
  920. {
  921. file->write_errno = errno;
  922. file->status_code |= WRITE_ERROR;
  923. perror(out_name);
  924. return WRITE_ERROR;
  925. }
  926. }
  927. return 0;
  928. }
  929. static void
  930. log_error(struct file *file, int code, const char *what)
  931. /* Like emit_error but checks the global 'errors' flag */
  932. {
  933. if (file->global->errors)
  934. emit_error(file, code, what);
  935. }
  936. static char
  937. type_char(png_uint_32 v)
  938. {
  939. /* In fact because chunk::chunk_type is validated prior to any call to this
  940. * function it will always return a-zA-Z, but the extra codes are just there
  941. * to help in finding internal (programming) errors. Note that the code only
  942. * ever considers the low 7 bits of the value (so it is not necessary for the
  943. * type_name function to mask of the byte.)
  944. */
  945. if (v & 32)
  946. return "!abcdefghijklmnopqrstuvwxyz56789"[(v-96)&31];
  947. else
  948. return "@ABCDEFGHIJKLMNOPQRSTUVWXYZ01234"[(v-64)&31];
  949. }
  950. static void
  951. type_name(png_uint_32 type, FILE *out)
  952. {
  953. putc(type_char(type >> 24), out);
  954. putc(type_char(type >> 16), out);
  955. putc(type_char(type >> 8), out);
  956. putc(type_char(type ), out);
  957. }
  958. static void
  959. type_sep(FILE *out)
  960. {
  961. putc(':', out);
  962. putc(' ', out);
  963. }
  964. static png_uint_32 current_type(struct file *file, int code);
  965. PNG_NORETURN static void
  966. stop(struct file *file, int code, const char *what)
  967. /* Return control when a PNG file cannot be read. This outputs an 'ERR'
  968. * summary line too.
  969. */
  970. {
  971. log_error(file, code, what);
  972. /* The chunk being read is typically identified by file->chunk or, if this is
  973. * NULL, by file->type. This may be wrong if libpng reads ahead, but this
  974. * only happens with IDAT where libpng reads the header then jumps around
  975. * finding errors in the previous chunks. We know that is happening because
  976. * we are at the start of the IDAT (i.e. no IDAT data has yet been written.)
  977. *
  978. * SUMMARY FORMAT (stop):
  979. *
  980. * IDAT ERR status code read-errno write-errno message file
  981. *
  982. * 'uncompressed' will be 0 if there was a problem in the IHDR. The errno
  983. * values are emit_string(strerror(errno)).
  984. */
  985. if (file->global->quiet < 2) /* need two quiets to stop this. */
  986. {
  987. png_uint_32 type;
  988. if (file->chunk != NULL)
  989. type = current_type(file, code); /* Gropes in struct chunk and IDAT */
  990. else
  991. type = file->type;
  992. if (type)
  993. type_name(type, stdout);
  994. else /* magic: an IDAT header, produces bogons for too many IDATs */
  995. fputs("HEAD", stdout); /* not a registered chunk! */
  996. printf(" ERR %.2x %s ", file->status_code, strcode(code));
  997. /* This only works one strerror at a time, because of the way strerror is
  998. * implemented.
  999. */
  1000. emit_string(strerror(file->read_errno), stdout);
  1001. putc(' ', stdout);
  1002. emit_string(strerror(file->write_errno), stdout);
  1003. putc(' ', stdout);
  1004. emit_string(what, stdout);
  1005. putc(' ', stdout);
  1006. fputs(file->file_name, stdout);
  1007. putc('\n', stdout);
  1008. }
  1009. file->status_code |= FILE_ERROR;
  1010. longjmp(file->jmpbuf, code);
  1011. }
  1012. PNG_NORETURN static void
  1013. stop_invalid(struct file *file, const char *what)
  1014. {
  1015. stop(file, INVALID_ERROR_CODE, what);
  1016. }
  1017. static void
  1018. type_message(struct file *file, png_uint_32 type, const char *what)
  1019. /* Error message for a chunk; the chunk name comes from 'type' */
  1020. {
  1021. if (file->global->errors)
  1022. {
  1023. fputs(file->file_name, stderr);
  1024. type_sep(stderr);
  1025. type_name(type, stderr);
  1026. type_sep(stderr);
  1027. fputs(what, stderr);
  1028. putc('\n', stderr);
  1029. }
  1030. }
  1031. /* Input file positioning - we jump around in the input file while reading
  1032. * stuff, these wrappers deal with the error handling.
  1033. */
  1034. static void
  1035. file_getpos(struct file *file, fpos_t *pos)
  1036. {
  1037. if (fgetpos(file->file, pos))
  1038. {
  1039. /* This is unexpected, so perror it */
  1040. perror(file->file_name);
  1041. stop(file, READ_ERROR_CODE, "fgetpos");
  1042. }
  1043. }
  1044. static void
  1045. file_setpos(struct file *file, const fpos_t *pos)
  1046. {
  1047. if (fsetpos(file->file, pos))
  1048. {
  1049. perror(file->file_name);
  1050. stop(file, READ_ERROR_CODE, "fsetpos");
  1051. }
  1052. }
  1053. static void
  1054. getpos(struct file *file)
  1055. /* Get the current position and store it in 'data_pos'. The corresponding
  1056. * setpos() function is chunk specific because it uses the copy of the
  1057. * position for the specific chunk.
  1058. */
  1059. {
  1060. file_getpos(file, &file->data_pos);
  1061. }
  1062. /* Read utility - read a single byte, returns a value in the range 0..255 or EOF
  1063. * on a read error. In the latter case status_code and read_errno are updated
  1064. * appropriately.
  1065. */
  1066. static int
  1067. read_byte(struct file *file)
  1068. {
  1069. int ch = getc(file->file);
  1070. if (ch >= 0 && ch <= 255)
  1071. {
  1072. ++(file->read_count);
  1073. return ch;
  1074. }
  1075. else if (ch != EOF)
  1076. {
  1077. file->status_code |= INTERNAL_ERROR;
  1078. file->read_errno = ERANGE; /* out of range character */
  1079. /* This is very unexpected; an error message is always output: */
  1080. emit_error(file, UNEXPECTED_ERROR_CODE, "file read");
  1081. }
  1082. # ifdef EINTR
  1083. else if (errno == EINTR) /* Interrupted, try again */
  1084. {
  1085. errno = 0;
  1086. return read_byte(file);
  1087. }
  1088. # endif
  1089. else
  1090. {
  1091. /* An error, it doesn't really matter what the error is but it gets
  1092. * recorded anyway.
  1093. */
  1094. if (ferror(file->file))
  1095. file->read_errno = errno;
  1096. else if (feof(file->file))
  1097. file->read_errno = 0; /* I.e. a regular EOF, no error */
  1098. else /* unexpected */
  1099. file->read_errno = EDOM;
  1100. }
  1101. /* 'TRUNCATED' is used for all cases of failure to read a byte, because of
  1102. * the way libpng works a byte read is never attempted unless the byte is
  1103. * expected to be there, so EOF should not occur.
  1104. */
  1105. file->status_code |= TRUNCATED;
  1106. return EOF;
  1107. }
  1108. static png_byte
  1109. reread_byte(struct file *file)
  1110. /* Read a byte when an error is not expected to happen because the byte has
  1111. * been read before without error.
  1112. */
  1113. {
  1114. int ch = getc(file->file);
  1115. if (errno != 0)
  1116. file->read_errno = errno;
  1117. if (ch < 0 || ch > 255)
  1118. stop(file, UNEXPECTED_ERROR_CODE, "reread");
  1119. return (png_byte)ch;
  1120. }
  1121. static png_uint_32
  1122. reread_4(struct file *file)
  1123. /* The same but for a four byte quantity */
  1124. {
  1125. png_uint_32 result = 0;
  1126. int i = 0;
  1127. while (++i <= 4)
  1128. result = (result << 8) + reread_byte(file);
  1129. return result;
  1130. }
  1131. static void
  1132. skip_12(struct file *file)
  1133. /* Skip exactly 12 bytes in the input stream - used to skip a CRC and chunk
  1134. * header that has been read before.
  1135. */
  1136. {
  1137. /* Since the chunks were read before this shouldn't fail: */
  1138. if (fseek(file->file, 12, SEEK_CUR) != 0)
  1139. {
  1140. if (errno != 0)
  1141. file->read_errno = errno;
  1142. stop(file, UNEXPECTED_ERROR_CODE, "reskip");
  1143. }
  1144. }
  1145. static void
  1146. write_byte(struct file *file, int b)
  1147. /* Write one byte to the output - this causes a fatal error if the write
  1148. * fails and the read of this PNG file immediately terminates. Just
  1149. * increments the write count if there is no output file.
  1150. */
  1151. {
  1152. if (file->out != NULL)
  1153. {
  1154. if (putc(b, file->out) != b)
  1155. {
  1156. file->write_errno = errno;
  1157. file->status_code |= WRITE_ERROR;
  1158. stop(file, WRITE_ERROR_CODE, "write byte");
  1159. }
  1160. }
  1161. ++(file->write_count);
  1162. }
  1163. /* Derivatives of the read/write functions. */
  1164. static unsigned int
  1165. read_4(struct file *file, png_uint_32 *pu)
  1166. /* Read four bytes, returns the number of bytes read successfully and, if all
  1167. * four bytes are read, assigns the result to *pu.
  1168. */
  1169. {
  1170. unsigned int i = 0;
  1171. png_uint_32 val = 0;
  1172. do
  1173. {
  1174. int ch = read_byte(file);
  1175. if (ch == EOF)
  1176. return i;
  1177. val = (val << 8) + ch;
  1178. } while (++i < 4);
  1179. *pu = val;
  1180. return i;
  1181. }
  1182. /* CRC handling - read but calculate the CRC while doing so. */
  1183. static int
  1184. crc_read_many(struct file *file, png_uint_32 length)
  1185. /* Reads 'length' bytes and updates the CRC, returns true on success, false
  1186. * if the input is truncated.
  1187. */
  1188. {
  1189. if (length > 0)
  1190. {
  1191. png_uint_32 crc = file->crc;
  1192. do
  1193. {
  1194. int ch = read_byte(file);
  1195. if (ch == EOF)
  1196. return 0; /* Truncated */
  1197. crc = crc_one_byte(crc, ch);
  1198. }
  1199. while (--length > 0);
  1200. file->crc = crc;
  1201. }
  1202. return 1; /* OK */
  1203. }
  1204. static int
  1205. calc_image_size(struct file *file)
  1206. /* Fill in the image_bytes field given the IHDR information, calls stop on
  1207. * error.
  1208. */
  1209. {
  1210. png_uint_16 pd = file->bit_depth;
  1211. switch (file->color_type)
  1212. {
  1213. default:
  1214. stop_invalid(file, "IHDR: colour type");
  1215. invalid_bit_depth:
  1216. stop_invalid(file, "IHDR: bit depth");
  1217. case 0: /* g */
  1218. if (pd != 1 && pd != 2 && pd != 4 && pd != 8 && pd != 16)
  1219. goto invalid_bit_depth;
  1220. break;
  1221. case 3:
  1222. if (pd != 1 && pd != 2 && pd != 4 && pd != 8)
  1223. goto invalid_bit_depth;
  1224. break;
  1225. case 2: /* rgb */
  1226. if (pd != 8 && pd != 16)
  1227. goto invalid_bit_depth;
  1228. pd = (png_uint_16)(pd * 3);
  1229. break;
  1230. case 4: /* ga */
  1231. if (pd != 8 && pd != 16)
  1232. goto invalid_bit_depth;
  1233. pd = (png_uint_16)(pd * 2);
  1234. break;
  1235. case 6: /* rgba */
  1236. if (pd != 8 && pd != 16)
  1237. goto invalid_bit_depth;
  1238. pd = (png_uint_16)(pd * 4);
  1239. break;
  1240. }
  1241. if (file->width < 1 || file->width > 0x7fffffff)
  1242. stop_invalid(file, "IHDR: width");
  1243. else if (file->height < 1 || file->height > 0x7fffffff)
  1244. stop_invalid(file, "IHDR: height");
  1245. else if (file->compression_method != 0)
  1246. stop_invalid(file, "IHDR: compression method");
  1247. else if (file->filter_method != 0)
  1248. stop_invalid(file, "IHDR: filter method");
  1249. else switch (file->interlace_method)
  1250. {
  1251. case PNG_INTERLACE_ADAM7:
  1252. /* Interlacing makes the image larger because of the replication of
  1253. * both the filter byte and the padding to a byte boundary.
  1254. */
  1255. {
  1256. int pass;
  1257. int image_digits = 0;
  1258. udigit row_width[2], row_bytes[3];
  1259. for (pass=0; pass<=6; ++pass)
  1260. {
  1261. png_uint_32 pw = PNG_PASS_COLS(file->width, pass);
  1262. if (pw > 0)
  1263. {
  1264. int digits;
  1265. /* calculate 1+((pw*pd+7)>>3) in row_bytes */
  1266. digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
  1267. row_width, uarb_set(row_width, pw), pd);
  1268. digits = uarb_shift(row_bytes, digits, 3);
  1269. digits = uarb_inc(row_bytes, digits, 1);
  1270. /* Add row_bytes * pass-height to the file image_bytes field
  1271. */
  1272. image_digits = uarb_mult32(file->image_bytes, image_digits,
  1273. row_bytes, digits,
  1274. PNG_PASS_ROWS(file->height, pass));
  1275. }
  1276. }
  1277. file->image_digits = image_digits;
  1278. }
  1279. break;
  1280. case PNG_INTERLACE_NONE:
  1281. {
  1282. int digits;
  1283. udigit row_width[2], row_bytes[3];
  1284. /* As above, but use image_width in place of the pass width: */
  1285. digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
  1286. row_width, uarb_set(row_width, file->width), pd);
  1287. digits = uarb_shift(row_bytes, digits, 3);
  1288. digits = uarb_inc(row_bytes, digits, 1);
  1289. /* Set row_bytes * image-height to the file image_bytes field */
  1290. file->image_digits = uarb_mult32(file->image_bytes, 0,
  1291. row_bytes, digits, file->height);
  1292. }
  1293. break;
  1294. default:
  1295. stop_invalid(file, "IHDR: interlace method");
  1296. }
  1297. assert(file->image_digits >= 1 && file->image_digits <= 5);
  1298. return 1;
  1299. }
  1300. /* PER-CHUNK CONTROL STRUCTURE
  1301. * This structure is instantiated for each chunk, except for the IDAT chunks
  1302. * where one chunk control structure is used for the whole of a single stream of
  1303. * IDAT chunks (see the IDAT control structure below).
  1304. */
  1305. struct chunk
  1306. {
  1307. /* ANCESTORS */
  1308. struct file * file;
  1309. struct global * global;
  1310. /* PUBLIC IDAT INFORMATION: SET BY THE ZLIB CODE */
  1311. udigit uncompressed_bytes[5];
  1312. int uncompressed_digits;
  1313. udigit compressed_bytes[5];
  1314. int compressed_digits;
  1315. /* PUBLIC PER-CHUNK INFORMATION: USED BY CHUNK READ CODE */
  1316. /* This information is filled in by chunk_init from the data in the file
  1317. * control structure, but chunk_length may be changed later.
  1318. */
  1319. fpos_t chunk_data_pos; /* Position of first byte of chunk data */
  1320. png_uint_32 chunk_length; /* From header (or modified below) */
  1321. png_uint_32 chunk_type; /* From header */
  1322. /* PUBLIC PER-CHUNK INFORMATION: FOR THE CHUNK WRITE CODE */
  1323. png_uint_32 write_crc; /* Output CRC (may differ from read_crc) */
  1324. png_uint_32 rewrite_offset; /* Count of bytes before rewrite. */
  1325. int rewrite_length; /* Number of bytes left to change */
  1326. png_byte rewrite_buffer[2]; /* Buffer of new byte values */
  1327. };
  1328. static void
  1329. chunk_message(struct chunk *chunk, const char *message)
  1330. {
  1331. type_message(chunk->file, chunk->chunk_type, message);
  1332. }
  1333. static void
  1334. chunk_end(struct chunk **chunk_var)
  1335. {
  1336. struct chunk *chunk = *chunk_var;
  1337. *chunk_var = NULL;
  1338. CLEAR(*chunk);
  1339. }
  1340. static void
  1341. chunk_init(struct chunk * const chunk, struct file * const file)
  1342. /* When a chunk is initialized the file length/type/pos are copied into the
  1343. * corresponding chunk fields and the new chunk is registered in the file
  1344. * structure. There can only be one chunk at a time.
  1345. *
  1346. * NOTE: this routine must onely be called from the file alloc routine!
  1347. */
  1348. {
  1349. assert(file->chunk == NULL);
  1350. CLEAR(*chunk);
  1351. chunk->file = file;
  1352. chunk->global = file->global;
  1353. chunk->chunk_data_pos = file->data_pos;
  1354. chunk->chunk_length = file->length;
  1355. chunk->chunk_type = file->type;
  1356. /* Compresssed/uncompressed size information (from the zlib control structure
  1357. * that is used to check the compressed data in a chunk.)
  1358. */
  1359. chunk->uncompressed_digits = 0;
  1360. chunk->compressed_digits = 0;
  1361. file->chunk = chunk;
  1362. }
  1363. static png_uint_32
  1364. current_type(struct file *file, int code)
  1365. /* Guess the actual chunk type that causes a stop() */
  1366. {
  1367. /* This may return png_IDAT for errors detected (late) in the header; that
  1368. * includes any inter-chunk consistency check that libpng performs. Assume
  1369. * that if the chunk_type is png_IDAT and the file write count is 8 this is
  1370. * what is happening.
  1371. */
  1372. if (file->chunk != NULL)
  1373. {
  1374. png_uint_32 type = file->chunk->chunk_type;
  1375. /* This is probably wrong for the excess IDATs case, because then libpng
  1376. * whines about too many of them (apparently in some cases erroneously)
  1377. * when the header is read.
  1378. */
  1379. if (code <= LIBPNG_ERROR_CODE && type == png_IDAT &&
  1380. file->write_count == 8)
  1381. type = 0; /* magic */
  1382. return type;
  1383. }
  1384. else
  1385. return file->type;
  1386. }
  1387. static void
  1388. setpos(struct chunk *chunk)
  1389. /* Reset the position to 'chunk_data_pos' - the start of the data for this
  1390. * chunk. As a side effect the read_count in the file is reset to 8, just
  1391. * after the length/type header.
  1392. */
  1393. {
  1394. chunk->file->read_count = 8;
  1395. file_setpos(chunk->file, &chunk->chunk_data_pos);
  1396. }
  1397. /* Specific chunk handling - called for each chunk header, all special chunk
  1398. * processing is initiated in these functions.
  1399. */
  1400. /* The next functions handle special processing for those chunks with LZ data,
  1401. * the data is identified and checked for validity. If there are problems which
  1402. * cannot be corrected the routines return false, otherwise true (although
  1403. * modification to the zlib header may be required.)
  1404. *
  1405. * The compressed data is in zlib format (RFC1950) and consequently has a
  1406. * minimum length of 7 bytes.
  1407. */
  1408. static int zlib_check(struct file *file, png_uint_32 offset);
  1409. static int
  1410. process_zTXt_iCCP(struct file *file)
  1411. /* zTXt and iCCP have exactly the same form - keyword, null, compression
  1412. * method then compressed data.
  1413. */
  1414. {
  1415. struct chunk *chunk = file->chunk;
  1416. png_uint_32 length;
  1417. png_uint_32 index = 0;
  1418. assert(chunk != NULL && file->idat == NULL);
  1419. length = chunk->chunk_length;
  1420. setpos(chunk);
  1421. while (length >= 9)
  1422. {
  1423. --length;
  1424. ++index;
  1425. if (reread_byte(file) == 0) /* keyword null terminator */
  1426. {
  1427. --length;
  1428. ++index;
  1429. (void)reread_byte(file); /* compression method */
  1430. return zlib_check(file, index);
  1431. }
  1432. }
  1433. chunk_message(chunk, "too short");
  1434. return 0; /* skip */
  1435. }
  1436. static int
  1437. process_iTXt(struct file *file)
  1438. {
  1439. /* Like zTXt but more fields. */
  1440. struct chunk *chunk = file->chunk;
  1441. png_uint_32 length;
  1442. png_uint_32 index = 0;
  1443. assert(chunk != NULL && file->idat == NULL);
  1444. length = chunk->chunk_length;
  1445. setpos(chunk);
  1446. while (length >= 5)
  1447. {
  1448. --length;
  1449. ++index;
  1450. if (reread_byte(file) == 0) /* keyword null terminator */
  1451. {
  1452. --length;
  1453. ++index;
  1454. if (reread_byte(file) == 0) /* uncompressed text */
  1455. return 1; /* nothing to check */
  1456. --length;
  1457. ++index;
  1458. (void)reread_byte(file); /* compression method */
  1459. /* Skip the language tag (null terminated). */
  1460. while (length >= 9)
  1461. {
  1462. --length;
  1463. ++index;
  1464. if (reread_byte(file) == 0) /* terminator */
  1465. {
  1466. /* Skip the translated keyword */
  1467. while (length >= 8)
  1468. {
  1469. --length;
  1470. ++index;
  1471. if (reread_byte(file) == 0) /* terminator */
  1472. return zlib_check(file, index);
  1473. }
  1474. }
  1475. }
  1476. /* Ran out of bytes in the compressed case. */
  1477. break;
  1478. }
  1479. }
  1480. log_error(file, INVALID_ERROR_CODE, "iTXt chunk length");
  1481. return 0; /* skip */
  1482. }
  1483. /* IDAT READ/WRITE CONTROL STRUCTURE */
  1484. struct IDAT
  1485. {
  1486. /* ANCESTORS */
  1487. struct file * file;
  1488. struct global * global;
  1489. /* PROTECTED IDAT INFORMATION: SET BY THE IDAT READ CODE */
  1490. struct IDAT_list *idat_list_head; /* START of the list of IDAT information */
  1491. struct IDAT_list *idat_list_tail; /* *END* of the list of IDAT information */
  1492. /* PROTECTED IDAT INFORMATION: USED BY THE IDAT WRITE CODE */
  1493. struct IDAT_list *idat_cur; /* Current list entry */
  1494. unsigned int idat_count; /* And the *current* index into the list */
  1495. png_uint_32 idat_index; /* Index of *next* input byte to write */
  1496. png_uint_32 idat_length; /* Cache of current chunk length */
  1497. };
  1498. /* NOTE: there is currently no IDAT_reset, so a stream cannot contain more than
  1499. * one IDAT sequence (i.e. MNG is not supported).
  1500. */
  1501. static void
  1502. IDAT_end(struct IDAT **idat_var)
  1503. {
  1504. struct IDAT *idat = *idat_var;
  1505. struct file *file = idat->file;
  1506. *idat_var = NULL;
  1507. CLEAR(*idat);
  1508. assert(file->chunk != NULL);
  1509. chunk_end(&file->chunk);
  1510. /* Regardless of why the IDAT was killed set the state back to CHUNKS (it may
  1511. * already be CHUNKS because the state isn't changed until process_IDAT
  1512. * returns; a stop will cause IDAT_end to be entered in state CHUNKS!)
  1513. */
  1514. file->state = STATE_CHUNKS;
  1515. }
  1516. static void
  1517. IDAT_init(struct IDAT * const idat, struct file * const file)
  1518. /* When the chunk is png_IDAT instantiate an IDAT control structure in place
  1519. * of a chunk control structure. The IDAT will instantiate a chunk control
  1520. * structure using the file alloc routine.
  1521. *
  1522. * NOTE: this routine must only be called from the file alloc routine!
  1523. */
  1524. {
  1525. assert(file->chunk == NULL);
  1526. assert(file->idat == NULL);
  1527. CLEAR(*idat);
  1528. idat->file = file;
  1529. idat->global = file->global;
  1530. /* Initialize the tail to the pre-allocated buffer and set the count to 0
  1531. * (empty.)
  1532. */
  1533. idat->global->idat_cache.count = 0;
  1534. idat->idat_list_head = idat->idat_list_tail = &idat->global->idat_cache;
  1535. /* Now the chunk. The allocator calls the initializer of the new chunk and
  1536. * stores the result in file->chunk:
  1537. */
  1538. file->alloc(file, 0/*chunk*/);
  1539. assert(file->chunk != NULL);
  1540. /* And store this for cleanup (and to check for double alloc or failure to
  1541. * free.)
  1542. */
  1543. file->idat = idat;
  1544. }
  1545. static png_uint_32
  1546. rechunk_length(struct IDAT *idat, int start)
  1547. /* Return the length for the next IDAT chunk, taking into account
  1548. * rechunking.
  1549. */
  1550. {
  1551. png_uint_32 len = idat->global->idat_max;
  1552. if (len == 0) /* use original chunk lengths */
  1553. {
  1554. const struct IDAT_list *cur;
  1555. unsigned int count;
  1556. if (start)
  1557. return idat->idat_length; /* use the cache */
  1558. /* Otherwise rechunk_length is called at the end of a chunk for the length
  1559. * of the next one.
  1560. */
  1561. cur = idat->idat_cur;
  1562. count = idat->idat_count;
  1563. assert(idat->idat_index == idat->idat_length &&
  1564. idat->idat_length == cur->lengths[count]);
  1565. /* Return length of the *next* chunk */
  1566. if (++count < cur->count)
  1567. return cur->lengths[count];
  1568. /* End of this list */
  1569. assert(cur != idat->idat_list_tail);
  1570. cur = cur->next;
  1571. assert(cur != NULL && cur->count > 0);
  1572. return cur->lengths[0];
  1573. }
  1574. else /* rechunking */
  1575. {
  1576. /* The chunk size is the lesser of file->idat_max and the number
  1577. * of remaining bytes.
  1578. */
  1579. png_uint_32 have = idat->idat_length - idat->idat_index;
  1580. if (len > have)
  1581. {
  1582. struct IDAT_list *cur = idat->idat_cur;
  1583. unsigned int j = idat->idat_count+1; /* the next IDAT in the list */
  1584. do
  1585. {
  1586. /* Add up the remaining bytes. This can't overflow because the
  1587. * individual lengths are always <= 0x7fffffff, so when we add two
  1588. * of them overflow is not possible.
  1589. */
  1590. assert(cur != NULL);
  1591. for (;;)
  1592. {
  1593. /* NOTE: IDAT_list::count here, not IDAT_list::length */
  1594. for (; j < cur->count; ++j)
  1595. {
  1596. have += cur->lengths[j];
  1597. if (len <= have)
  1598. return len;
  1599. }
  1600. /* If this was the end return the count of the available bytes */
  1601. if (cur == idat->idat_list_tail)
  1602. return have;
  1603. cur = cur->next;
  1604. j = 0;
  1605. }
  1606. }
  1607. while (len > have);
  1608. }
  1609. return len;
  1610. }
  1611. }
  1612. static int
  1613. process_IDAT(struct file *file)
  1614. /* Process the IDAT stream, this is the more complex than the preceding
  1615. * cases because the compressed data is spread across multiple IDAT chunks
  1616. * (typically). Rechunking of the data is not handled here; all this
  1617. * function does is establish whether the zlib header needs to be modified.
  1618. *
  1619. * Initially the function returns false, indicating that the chunk should not
  1620. * be written. It does this until the last IDAT chunk is passed in, then it
  1621. * checks the zlib data and returns true.
  1622. *
  1623. * It does not return false on a fatal error; it calls stop instead.
  1624. *
  1625. * The caller must have an instantiated (IDAT) control structure and it must
  1626. * have extent over the whole read of the IDAT stream. For a PNG this means
  1627. * the whole PNG read, for MNG it could have lesser extent.
  1628. */
  1629. {
  1630. struct IDAT_list *list;
  1631. assert(file->idat != NULL && file->chunk != NULL);
  1632. /* We need to first check the entire sequence of IDAT chunks to ensure the
  1633. * stream is in sync. Do this by building a list of all the chunks and
  1634. * recording the length of each because the length may have been fixed up by
  1635. * sync_stream below.
  1636. *
  1637. * At the end of the list of chunks, where the type of the next chunk is not
  1638. * png_IDAT, process the whole stream using the list data to check validity
  1639. * then return control to the start and rewrite everything.
  1640. */
  1641. list = file->idat->idat_list_tail;
  1642. if (list->count == list->length)
  1643. {
  1644. list = IDAT_list_extend(list);
  1645. if (list == NULL)
  1646. stop(file, READ_ERROR_CODE, "out of memory");
  1647. /* Move to the next block */
  1648. list->count = 0;
  1649. file->idat->idat_list_tail = list;
  1650. }
  1651. /* And fill in the next IDAT information buffer. */
  1652. list->lengths[(list->count)++] = file->chunk->chunk_length;
  1653. /* The type of the next chunk was recorded in the file control structure by
  1654. * the caller, if this is png_IDAT return 'skip' to the caller.
  1655. */
  1656. if (file->type == png_IDAT)
  1657. return 0; /* skip this for the moment */
  1658. /* This is the final IDAT chunk, so run the tests to check for the too far
  1659. * back error and possibly optimize the window bits. This means going back
  1660. * to the start of the first chunk data, which is stored in the original
  1661. * chunk allocation.
  1662. */
  1663. setpos(file->chunk);
  1664. if (zlib_check(file, 0))
  1665. {
  1666. struct IDAT *idat;
  1667. int cmp;
  1668. /* The IDAT stream was successfully uncompressed; see whether it
  1669. * contained the correct number of bytes of image data.
  1670. */
  1671. cmp = uarb_cmp(file->image_bytes, file->image_digits,
  1672. file->chunk->uncompressed_bytes, file->chunk->uncompressed_digits);
  1673. if (cmp < 0)
  1674. type_message(file, png_IDAT, "extra uncompressed data");
  1675. else if (cmp > 0)
  1676. stop(file, LIBPNG_ERROR_CODE, "IDAT: uncompressed data too small");
  1677. /* Return the stream to the start of the first IDAT chunk; the length
  1678. * is set in the write case below but the input chunk variables must be
  1679. * set (once) here:
  1680. */
  1681. setpos(file->chunk);
  1682. idat = file->idat;
  1683. idat->idat_cur = idat->idat_list_head;
  1684. idat->idat_length = idat->idat_cur->lengths[0];
  1685. idat->idat_count = 0; /* Count of chunks read in current list */
  1686. idat->idat_index = 0; /* Index into chunk data */
  1687. /* Update the chunk length to the correct value for the IDAT chunk: */
  1688. file->chunk->chunk_length = rechunk_length(idat, 1/*start*/);
  1689. /* Change the state to writing IDAT chunks */
  1690. file->state = STATE_IDAT;
  1691. return 1;
  1692. }
  1693. else /* Failure to decompress the IDAT stream; give up. */
  1694. stop(file, ZLIB_ERROR_CODE, "could not uncompress IDAT");
  1695. }
  1696. /* ZLIB CONTROL STRUCTURE */
  1697. struct zlib
  1698. {
  1699. /* ANCESTORS */
  1700. struct IDAT * idat; /* NOTE: May be NULL */
  1701. struct chunk * chunk;
  1702. struct file * file;
  1703. struct global *global;
  1704. /* GLOBAL ZLIB INFORMATION: SET BY THE CALLER */
  1705. png_uint_32 rewrite_offset;
  1706. /* GLOBAL ZLIB INFORMATION: SET BY THE ZLIB READ CODE */
  1707. udigit compressed_bytes[5];
  1708. int compressed_digits;
  1709. udigit uncompressed_bytes[5];
  1710. int uncompressed_digits;
  1711. int file_bits; /* window bits from the file */
  1712. int ok_bits; /* Set <16 on a successful read */
  1713. int cksum; /* Set on a checksum error */
  1714. /* PROTECTED ZLIB INFORMATION: USED BY THE ZLIB ROUTINES */
  1715. z_stream z;
  1716. png_uint_32 extra_bytes; /* Count of extra compressed bytes */
  1717. int state;
  1718. int rc; /* Last return code */
  1719. int window_bits; /* 0 if no change */
  1720. png_byte header[2];
  1721. };
  1722. static const char *
  1723. zlib_flevel(struct zlib *zlib)
  1724. {
  1725. switch (zlib->header[1] >> 6)
  1726. {
  1727. case 0: return "supfast";
  1728. case 1: return "stdfast";
  1729. case 2: return "default";
  1730. case 3: return "maximum";
  1731. default: assert(UNREACHED);
  1732. }
  1733. return "COMPILER BUG";
  1734. }
  1735. static const char *
  1736. zlib_rc(struct zlib *zlib)
  1737. /* Return a string for the zlib return code */
  1738. {
  1739. switch (zlib->rc)
  1740. {
  1741. case Z_OK: return "Z_OK";
  1742. case Z_STREAM_END: return "Z_STREAM_END";
  1743. case Z_NEED_DICT: return "Z_NEED_DICT";
  1744. case Z_ERRNO: return "Z_ERRNO";
  1745. case Z_STREAM_ERROR: return "Z_STREAM_ERROR";
  1746. case Z_DATA_ERROR: return "Z_DATA_ERROR";
  1747. case Z_MEM_ERROR: return "Z_MEM_ERROR";
  1748. case Z_BUF_ERROR: return "Z_BUF_ERROR";
  1749. case Z_VERSION_ERROR: return "Z_VERSION_ERROR";
  1750. default: return "Z_*INVALID_RC*";
  1751. }
  1752. }
  1753. static void
  1754. zlib_message(struct zlib *zlib, int unexpected)
  1755. /* Output a message given a zlib rc */
  1756. {
  1757. if (zlib->global->errors)
  1758. {
  1759. const char *reason = zlib->z.msg;
  1760. if (reason == NULL)
  1761. reason = "[no message]";
  1762. fputs(zlib->file->file_name, stderr);
  1763. type_sep(stderr);
  1764. type_name(zlib->chunk->chunk_type, stderr);
  1765. fprintf(stderr, ": %szlib error: %d (%s) (%s)\n",
  1766. unexpected ? "unexpected " : "", zlib->rc, zlib_rc(zlib), reason);
  1767. }
  1768. }
  1769. static void
  1770. zlib_end(struct zlib *zlib)
  1771. {
  1772. /* Output the summary line now; this ensures a summary line always gets
  1773. * output regardless of the manner of exit.
  1774. */
  1775. if (!zlib->global->quiet)
  1776. {
  1777. if (zlib->ok_bits < 16) /* stream was read ok */
  1778. {
  1779. const char *reason;
  1780. if (zlib->cksum)
  1781. reason = "CHK"; /* checksum error */
  1782. else if (zlib->ok_bits > zlib->file_bits)
  1783. reason = "TFB"; /* fixing a too-far-back error */
  1784. else if (zlib->ok_bits == zlib->file_bits)
  1785. reason = "OK ";
  1786. else
  1787. reason = "OPT"; /* optimizing window bits */
  1788. /* SUMMARY FORMAT (for a successful zlib inflate):
  1789. *
  1790. * IDAT reason flevel file-bits ok-bits compressed uncompressed file
  1791. */
  1792. type_name(zlib->chunk->chunk_type, stdout);
  1793. printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits,
  1794. zlib->ok_bits);
  1795. uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
  1796. putc(' ', stdout);
  1797. uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits,
  1798. stdout);
  1799. putc(' ', stdout);
  1800. fputs(zlib->file->file_name, stdout);
  1801. putc('\n', stdout);
  1802. }
  1803. else
  1804. {
  1805. /* This is a zlib read error; the chunk will be skipped. For an IDAT
  1806. * stream this will also cause a fatal read error (via stop()).
  1807. *
  1808. * SUMMARY FORMAT:
  1809. *
  1810. * IDAT SKP flevel file-bits z-rc compressed message file
  1811. *
  1812. * z-rc is the zlib failure code; message is the error message with
  1813. * spaces replaced by '-'. The compressed byte count indicates where
  1814. * in the zlib stream the error occurred.
  1815. */
  1816. type_name(zlib->chunk->chunk_type, stdout);
  1817. printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits,
  1818. zlib_rc(zlib));
  1819. uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
  1820. putc(' ', stdout);
  1821. emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout);
  1822. putc(' ', stdout);
  1823. fputs(zlib->file->file_name, stdout);
  1824. putc('\n', stdout);
  1825. }
  1826. }
  1827. if (zlib->state >= 0)
  1828. {
  1829. zlib->rc = inflateEnd(&zlib->z);
  1830. if (zlib->rc != Z_OK)
  1831. zlib_message(zlib, 1/*unexpected*/);
  1832. }
  1833. CLEAR(*zlib);
  1834. }
  1835. static int
  1836. zlib_reset(struct zlib *zlib, int window_bits)
  1837. /* Reinitializes a zlib with a different window_bits */
  1838. {
  1839. assert(zlib->state >= 0); /* initialized by zlib_init */
  1840. zlib->z.next_in = Z_NULL;
  1841. zlib->z.avail_in = 0;
  1842. zlib->z.next_out = Z_NULL;
  1843. zlib->z.avail_out = 0;
  1844. zlib->window_bits = window_bits;
  1845. zlib->compressed_digits = 0;
  1846. zlib->uncompressed_digits = 0;
  1847. zlib->state = 0; /* initialized, once */
  1848. zlib->rc = inflateReset2(&zlib->z, 0);
  1849. if (zlib->rc != Z_OK)
  1850. {
  1851. zlib_message(zlib, 1/*unexpected*/);
  1852. return 0;
  1853. }
  1854. return 1;
  1855. }
  1856. static int
  1857. zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk,
  1858. int window_bits, png_uint_32 offset)
  1859. /* Initialize a zlib_control; the result is true/false */
  1860. {
  1861. CLEAR(*zlib);
  1862. zlib->idat = idat;
  1863. zlib->chunk = chunk;
  1864. zlib->file = chunk->file;
  1865. zlib->global = chunk->global;
  1866. zlib->rewrite_offset = offset; /* never changed for this zlib */
  1867. /* *_out does not need to be set: */
  1868. zlib->z.next_in = Z_NULL;
  1869. zlib->z.avail_in = 0;
  1870. zlib->z.zalloc = Z_NULL;
  1871. zlib->z.zfree = Z_NULL;
  1872. zlib->z.opaque = Z_NULL;
  1873. zlib->state = -1;
  1874. zlib->window_bits = window_bits;
  1875. zlib->compressed_digits = 0;
  1876. zlib->uncompressed_digits = 0;
  1877. /* These values are sticky across reset (in addition to the stuff in the
  1878. * first block, which is actually constant.)
  1879. */
  1880. zlib->file_bits = 24;
  1881. zlib->ok_bits = 16; /* unset */
  1882. zlib->cksum = 0; /* set when a checksum error is detected */
  1883. /* '0' means use the header; inflateInit2 should always succeed because it
  1884. * does nothing apart from allocating the internal zstate.
  1885. */
  1886. zlib->rc = inflateInit2(&zlib->z, 0);
  1887. if (zlib->rc != Z_OK)
  1888. {
  1889. zlib_message(zlib, 1/*unexpected*/);
  1890. return 0;
  1891. }
  1892. else
  1893. {
  1894. zlib->state = 0; /* initialized */
  1895. return 1;
  1896. }
  1897. }
  1898. static int
  1899. max_window_bits(uarbc size, int ndigits)
  1900. /* Return the zlib stream window bits required for data of the given size. */
  1901. {
  1902. png_uint_16 cb;
  1903. if (ndigits > 1)
  1904. return 15;
  1905. cb = size[0];
  1906. if (cb > 16384) return 15;
  1907. if (cb > 8192) return 14;
  1908. if (cb > 4096) return 13;
  1909. if (cb > 2048) return 12;
  1910. if (cb > 1024) return 11;
  1911. if (cb > 512) return 10;
  1912. if (cb > 256) return 9;
  1913. return 8;
  1914. }
  1915. static int
  1916. zlib_advance(struct zlib *zlib, png_uint_32 nbytes)
  1917. /* Read nbytes compressed bytes; the stream will be initialized if required.
  1918. * Bytes are always being reread and errors are fatal. The return code is as
  1919. * follows:
  1920. *
  1921. * -1: saw the "too far back" error
  1922. * 0: ok, keep going
  1923. * 1: saw Z_STREAM_END (zlib->extra_bytes indicates too much data)
  1924. * 2: a zlib error that cannot be corrected (error message already
  1925. * output if required.)
  1926. */
  1927. # define ZLIB_TOO_FAR_BACK (-1)
  1928. # define ZLIB_OK 0
  1929. # define ZLIB_STREAM_END 1
  1930. # define ZLIB_FATAL 2
  1931. {
  1932. int state = zlib->state;
  1933. int endrc = ZLIB_OK;
  1934. png_uint_32 in_bytes = 0;
  1935. struct file *file = zlib->file;
  1936. assert(state >= 0);
  1937. while (in_bytes < nbytes && endrc == ZLIB_OK)
  1938. {
  1939. png_uint_32 out_bytes;
  1940. int flush;
  1941. png_byte bIn = reread_byte(file);
  1942. png_byte bOut;
  1943. switch (state)
  1944. {
  1945. case 0: /* first header byte */
  1946. {
  1947. int file_bits = 8+(bIn >> 4);
  1948. int new_bits = zlib->window_bits;
  1949. zlib->file_bits = file_bits;
  1950. /* Check against the existing value - it may not need to be
  1951. * changed. Note that a bogus file_bits is allowed through once,
  1952. * to see if it works, but the window_bits value is set to 15,
  1953. * the maximum.
  1954. */
  1955. if (new_bits == 0) /* no change */
  1956. zlib->window_bits = ((file_bits > 15) ? 15 : file_bits);
  1957. else if (new_bits != file_bits) /* rewrite required */
  1958. bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4));
  1959. }
  1960. zlib->header[0] = bIn;
  1961. zlib->state = state = 1;
  1962. break;
  1963. case 1: /* second header byte */
  1964. {
  1965. int b2 = bIn & 0xe0; /* top 3 bits */
  1966. /* The checksum calculation, on the first 11 bits: */
  1967. b2 += 0x1f - ((zlib->header[0] << 8) + b2) % 0x1f;
  1968. /* Update the checksum byte if required: */
  1969. if (bIn != b2)
  1970. {
  1971. /* If the first byte wasn't changed this indicates an error in
  1972. * the checksum calculation; signal this by setting 'cksum'.
  1973. */
  1974. if (zlib->file_bits == zlib->window_bits)
  1975. zlib->cksum = 1;
  1976. bIn = (png_byte)b2;
  1977. }
  1978. }
  1979. zlib->header[1] = bIn;
  1980. zlib->state = state = 2;
  1981. break;
  1982. default: /* After the header bytes */
  1983. break;
  1984. }
  1985. /* For some streams, perhaps only those compressed with 'superfast
  1986. * compression' (which results in a lot of copying) Z_BUF_ERROR can happen
  1987. * immediately after all output has been flushed on the next input byte.
  1988. * This is handled below when Z_BUF_ERROR is detected by adding an output
  1989. * byte.
  1990. */
  1991. zlib->z.next_in = &bIn;
  1992. zlib->z.avail_in = 1;
  1993. zlib->z.next_out = &bOut;
  1994. zlib->z.avail_out = 0; /* Initially */
  1995. /* Initially use Z_NO_FLUSH in an attempt to persuade zlib to look at this
  1996. * byte without confusing what is going on with output.
  1997. */
  1998. flush = Z_NO_FLUSH;
  1999. out_bytes = 0;
  2000. /* NOTE: expression 3 is only evaluated on 'continue', because of the
  2001. * 'break' at the end of this loop below.
  2002. */
  2003. for (;endrc == ZLIB_OK;
  2004. flush = Z_SYNC_FLUSH,
  2005. zlib->z.next_out = &bOut,
  2006. zlib->z.avail_out = 1,
  2007. ++out_bytes)
  2008. {
  2009. zlib->rc = inflate(&zlib->z, flush);
  2010. out_bytes -= zlib->z.avail_out;
  2011. switch (zlib->rc)
  2012. {
  2013. case Z_BUF_ERROR:
  2014. if (zlib->z.avail_out == 0)
  2015. continue; /* Try another output byte. */
  2016. if (zlib->z.avail_in == 0)
  2017. break; /* Try another input byte */
  2018. /* Both avail_out and avail_in are 1 yet zlib returned a code
  2019. * indicating no progress was possible. This is unexpected.
  2020. */
  2021. zlib_message(zlib, 1/*unexpected*/);
  2022. endrc = ZLIB_FATAL; /* stop processing */
  2023. break;
  2024. case Z_OK:
  2025. /* Zlib is supposed to have made progress: */
  2026. assert(zlib->z.avail_out == 0 || zlib->z.avail_in == 0);
  2027. continue;
  2028. case Z_STREAM_END:
  2029. /* This is the successful end. */
  2030. zlib->state = 3; /* end of stream */
  2031. endrc = ZLIB_STREAM_END;
  2032. break;
  2033. case Z_NEED_DICT:
  2034. zlib_message(zlib, 0/*stream error*/);
  2035. endrc = ZLIB_FATAL;
  2036. break;
  2037. case Z_DATA_ERROR:
  2038. /* The too far back error can be corrected, others cannot: */
  2039. if (zlib->z.msg != NULL &&
  2040. strcmp(zlib->z.msg, "invalid distance too far back") == 0)
  2041. {
  2042. endrc = ZLIB_TOO_FAR_BACK;
  2043. break;
  2044. }
  2045. /* FALLTHROUGH */
  2046. default:
  2047. zlib_message(zlib, 0/*stream error*/);
  2048. endrc = ZLIB_FATAL;
  2049. break;
  2050. } /* switch (inflate rc) */
  2051. /* Control gets here when further output is not possible; endrc may
  2052. * still be ZLIB_OK if more input is required.
  2053. */
  2054. break;
  2055. } /* for (output bytes) */
  2056. /* Keep a running count of output byte produced: */
  2057. zlib->uncompressed_digits = uarb_add32(zlib->uncompressed_bytes,
  2058. zlib->uncompressed_digits, out_bytes);
  2059. /* Keep going, the loop will terminate when endrc is no longer set to
  2060. * ZLIB_OK or all the input bytes have been consumed; meanwhile keep
  2061. * adding input bytes.
  2062. */
  2063. assert(zlib->z.avail_in == 0 || endrc != ZLIB_OK);
  2064. in_bytes += 1 - zlib->z.avail_in;
  2065. } /* while (input bytes) */
  2066. assert(in_bytes == nbytes || endrc != ZLIB_OK);
  2067. /* Update the running total of input bytes consumed */
  2068. zlib->compressed_digits = uarb_add32(zlib->compressed_bytes,
  2069. zlib->compressed_digits, in_bytes - zlib->z.avail_in);
  2070. /* At the end of the stream update the chunk with the accumulated
  2071. * information if it is an improvement:
  2072. */
  2073. if (endrc == ZLIB_STREAM_END && zlib->window_bits < zlib->ok_bits)
  2074. {
  2075. struct chunk *chunk = zlib->chunk;
  2076. chunk->uncompressed_digits = uarb_copy(chunk->uncompressed_bytes,
  2077. zlib->uncompressed_bytes, zlib->uncompressed_digits);
  2078. chunk->compressed_digits = uarb_copy(chunk->compressed_bytes,
  2079. zlib->compressed_bytes, zlib->compressed_digits);
  2080. chunk->rewrite_buffer[0] = zlib->header[0];
  2081. chunk->rewrite_buffer[1] = zlib->header[1];
  2082. if (zlib->window_bits != zlib->file_bits || zlib->cksum)
  2083. {
  2084. /* A rewrite is required */
  2085. chunk->rewrite_offset = zlib->rewrite_offset;
  2086. chunk->rewrite_length = 2;
  2087. }
  2088. else
  2089. {
  2090. chunk->rewrite_offset = 0;
  2091. chunk->rewrite_length = 0;
  2092. }
  2093. if (in_bytes < nbytes)
  2094. chunk_message(chunk, "extra compressed data");
  2095. zlib->extra_bytes = nbytes - in_bytes;
  2096. zlib->ok_bits = zlib->window_bits;
  2097. }
  2098. return endrc;
  2099. }
  2100. static int
  2101. zlib_run(struct zlib *zlib)
  2102. /* Like zlib_advance but also handles a stream of IDAT chunks. */
  2103. {
  2104. /* The 'extra_bytes' field is set by zlib_advance if there is extra
  2105. * compressed data in the chunk it handles (if it sees Z_STREAM_END before
  2106. * all the input data has been used.) This function uses the value to update
  2107. * the correct chunk length, so the problem should only ever be detected once
  2108. * for each chunk. zlib_advance outputs the error message, though see the
  2109. * IDAT specific check below.
  2110. */
  2111. zlib->extra_bytes = 0;
  2112. if (zlib->idat != NULL)
  2113. {
  2114. struct IDAT_list *list = zlib->idat->idat_list_head;
  2115. struct IDAT_list *last = zlib->idat->idat_list_tail;
  2116. int skip = 0;
  2117. /* 'rewrite_offset' is the offset of the LZ data within the chunk, for
  2118. * IDAT it should be 0:
  2119. */
  2120. assert(zlib->rewrite_offset == 0);
  2121. /* Process each IDAT_list in turn; the caller has left the stream
  2122. * positioned at the start of the first IDAT chunk data.
  2123. */
  2124. for (;;)
  2125. {
  2126. unsigned int count = list->count;
  2127. unsigned int i;
  2128. for (i = 0; i<count; ++i)
  2129. {
  2130. int rc;
  2131. if (skip > 0) /* Skip CRC and next IDAT header */
  2132. skip_12(zlib->file);
  2133. skip = 12; /* for the next time */
  2134. rc = zlib_advance(zlib, list->lengths[i]);
  2135. switch (rc)
  2136. {
  2137. case ZLIB_OK: /* keep going */
  2138. break;
  2139. case ZLIB_STREAM_END: /* stop */
  2140. /* There may be extra chunks; if there are and one of them is
  2141. * not zero length output the 'extra data' message. Only do
  2142. * this check if errors are being output.
  2143. */
  2144. if (zlib->global->errors && zlib->extra_bytes == 0)
  2145. {
  2146. struct IDAT_list *check = list;
  2147. int j = i+1, jcount = count;
  2148. for (;;)
  2149. {
  2150. for (; j<jcount; ++j)
  2151. if (check->lengths[j] > 0)
  2152. {
  2153. chunk_message(zlib->chunk,
  2154. "extra compressed data");
  2155. goto end_check;
  2156. }
  2157. if (check == last)
  2158. break;
  2159. check = check->next;
  2160. jcount = check->count;
  2161. j = 0;
  2162. }
  2163. }
  2164. end_check:
  2165. /* Terminate the list at the current position, reducing the
  2166. * length of the last IDAT too if required.
  2167. */
  2168. list->lengths[i] -= zlib->extra_bytes;
  2169. list->count = i+1;
  2170. zlib->idat->idat_list_tail = list;
  2171. /* FALLTHROUGH */
  2172. default:
  2173. return rc;
  2174. }
  2175. }
  2176. /* At the end of the compressed data and Z_STREAM_END was not seen. */
  2177. if (list == last)
  2178. return ZLIB_OK;
  2179. list = list->next;
  2180. }
  2181. }
  2182. else
  2183. {
  2184. struct chunk *chunk = zlib->chunk;
  2185. int rc;
  2186. assert(zlib->rewrite_offset < chunk->chunk_length);
  2187. rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset);
  2188. /* The extra bytes in the chunk are handled now by adjusting the chunk
  2189. * length to exclude them; the zlib data is always stored at the end of
  2190. * the PNG chunk (although clearly this is not necessary.) zlib_advance
  2191. * has already output a warning message.
  2192. */
  2193. chunk->chunk_length -= zlib->extra_bytes;
  2194. return rc;
  2195. }
  2196. }
  2197. static int /* global function; not a member function */
  2198. zlib_check(struct file *file, png_uint_32 offset)
  2199. /* Check the stream of zlib compressed data in either idat (if given) or (if
  2200. * not) chunk. In fact it is zlib_run that handles the difference in reading
  2201. * a single chunk and a list of IDAT chunks.
  2202. *
  2203. * In either case the input file must be positioned at the first byte of zlib
  2204. * compressed data (the first header byte).
  2205. *
  2206. * The return value is true on success, including the case where the zlib
  2207. * header may need to be rewritten, and false on an unrecoverable error.
  2208. *
  2209. * In the case of IDAT chunks 'offset' should be 0.
  2210. */
  2211. {
  2212. fpos_t start_pos;
  2213. struct zlib zlib;
  2214. /* Record the start of the LZ data to allow a re-read. */
  2215. file_getpos(file, &start_pos);
  2216. /* First test the existing (file) window bits: */
  2217. if (zlib_init(&zlib, file->idat, file->chunk, 0/*window bits*/, offset))
  2218. {
  2219. int min_bits, max_bits, rc;
  2220. /* The first run using the existing window bits. */
  2221. rc = zlib_run(&zlib);
  2222. switch (rc)
  2223. {
  2224. case ZLIB_TOO_FAR_BACK:
  2225. /* too far back error */
  2226. file->status_code |= TOO_FAR_BACK;
  2227. min_bits = zlib.window_bits + 1;
  2228. max_bits = 15;
  2229. break;
  2230. case ZLIB_STREAM_END:
  2231. if (!zlib.global->optimize_zlib &&
  2232. zlib.window_bits == zlib.file_bits && !zlib.cksum)
  2233. {
  2234. /* The trivial case where the stream is ok and optimization was
  2235. * not requested.
  2236. */
  2237. zlib_end(&zlib);
  2238. return 1;
  2239. }
  2240. max_bits = max_window_bits(zlib.uncompressed_bytes,
  2241. zlib.uncompressed_digits);
  2242. if (zlib.ok_bits < max_bits)
  2243. max_bits = zlib.ok_bits;
  2244. min_bits = 8;
  2245. /* cksum is set if there is an error in the zlib header checksum
  2246. * calculation in the original file (and this may be the only reason
  2247. * a rewrite is required). We can't rely on the file window bits in
  2248. * this case, so do the optimization anyway.
  2249. */
  2250. if (zlib.cksum)
  2251. chunk_message(zlib.chunk, "zlib checksum");
  2252. break;
  2253. case ZLIB_OK:
  2254. /* Truncated stream; unrecoverable, gets converted to ZLIB_FATAL */
  2255. zlib.z.msg = PNGZ_MSG_CAST("[truncated]");
  2256. zlib_message(&zlib, 0/*expected*/);
  2257. /* FALLTHROUGH */
  2258. default:
  2259. /* Unrecoverable error; skip the chunk; a zlib_message has already
  2260. * been output.
  2261. */
  2262. zlib_end(&zlib);
  2263. return 0;
  2264. }
  2265. /* Optimize window bits or fix a too-far-back error. min_bits and
  2266. * max_bits have been set appropriately, ok_bits records the bit value
  2267. * known to work.
  2268. */
  2269. while (min_bits < max_bits || max_bits < zlib.ok_bits/*if 16*/)
  2270. {
  2271. int test_bits = (min_bits + max_bits) >> 1;
  2272. if (zlib_reset(&zlib, test_bits))
  2273. {
  2274. file_setpos(file, &start_pos);
  2275. rc = zlib_run(&zlib);
  2276. switch (rc)
  2277. {
  2278. case ZLIB_TOO_FAR_BACK:
  2279. min_bits = test_bits+1;
  2280. if (min_bits > max_bits)
  2281. {
  2282. /* This happens when the stream really is damaged and it
  2283. * contains a distance code that addresses bytes before
  2284. * the start of the uncompressed data.
  2285. */
  2286. assert(test_bits == 15);
  2287. /* Output the error that wasn't output before: */
  2288. if (zlib.z.msg == NULL)
  2289. zlib.z.msg = PNGZ_MSG_CAST(
  2290. "invalid distance too far back");
  2291. zlib_message(&zlib, 0/*stream error*/);
  2292. zlib_end(&zlib);
  2293. return 0;
  2294. }
  2295. break;
  2296. case ZLIB_STREAM_END: /* success */
  2297. max_bits = test_bits;
  2298. break;
  2299. default:
  2300. /* A fatal error; this happens if a too-far-back error was
  2301. * hiding a more serious error, zlib_advance has already
  2302. * output a zlib_message.
  2303. */
  2304. zlib_end(&zlib);
  2305. return 0;
  2306. }
  2307. }
  2308. else /* inflateReset2 failed */
  2309. {
  2310. zlib_end(&zlib);
  2311. return 0;
  2312. }
  2313. }
  2314. /* The loop guarantees this */
  2315. assert(zlib.ok_bits == max_bits);
  2316. zlib_end(&zlib);
  2317. return 1;
  2318. }
  2319. else /* zlib initialization failed - skip the chunk */
  2320. {
  2321. zlib_end(&zlib);
  2322. return 0;
  2323. }
  2324. }
  2325. /***************************** LIBPNG CALLBACKS *******************************/
  2326. /* The strategy here is to run a regular libpng PNG file read but examine the
  2327. * input data (from the file) before passing it to libpng so as to be aware of
  2328. * the state we expect libpng to be in. Warning and error callbacks are also
  2329. * intercepted so that they can be quieted and interpreted. Interpretation
  2330. * depends on a somewhat risky string match for known error messages; let us
  2331. * hope that this can be fixed in the next version of libpng.
  2332. *
  2333. * The control structure is pointed to by the libpng error pointer. It contains
  2334. * that set of structures which must persist across multiple read callbacks,
  2335. * which is pretty much everything except the 'zlib' control structure.
  2336. *
  2337. * The file structure is instantiated in the caller of the per-file routine, but
  2338. * the per-file routine contains the chunk and IDAT control structures.
  2339. */
  2340. /* The three routines read_chunk, process_chunk and sync_stream can only be
  2341. * called via a call to read_chunk and only exit at a return from process_chunk.
  2342. * These routines could have been written as one confusing large routine,
  2343. * instead this code relies on the compiler to do tail call elimination. The
  2344. * possible calls are as follows:
  2345. *
  2346. * read_chunk
  2347. * -> sync_stream
  2348. * -> process_chunk
  2349. * -> process_chunk
  2350. * -> read_chunk
  2351. * returns
  2352. */
  2353. static void read_chunk(struct file *file);
  2354. static void
  2355. process_chunk(struct file *file, png_uint_32 file_crc, png_uint_32 next_length,
  2356. png_uint_32 next_type)
  2357. /* Called when the chunk data has been read, next_length and next_type
  2358. * will be set for the next chunk (or 0 if this is IEND).
  2359. *
  2360. * When this routine returns, chunk_length and chunk_type will be set for the
  2361. * next chunk to write because if a chunk is skipped this return calls back
  2362. * to read_chunk.
  2363. */
  2364. {
  2365. png_uint_32 type = file->type;
  2366. if (file->global->verbose > 1)
  2367. {
  2368. fputs(" ", stderr);
  2369. type_name(file->type, stderr);
  2370. fprintf(stderr, " %lu 0x%.8x 0x%.8x\n", (unsigned long)file->length,
  2371. file->crc ^ 0xffffffff, file_crc);
  2372. }
  2373. /* The basic structure seems correct but the CRC may not match, in this
  2374. * case assume that it is simply a bad CRC, either wrongly calculated or
  2375. * because of damaged stream data.
  2376. */
  2377. if ((file->crc ^ 0xffffffff) != file_crc)
  2378. {
  2379. /* The behavior is set by the 'skip' setting; if it is anything other
  2380. * than SKIP_BAD_CRC ignore the bad CRC and return the chunk, with a
  2381. * corrected CRC and possibly processed, to libpng. Otherwise skip the
  2382. * chunk, which will result in a fatal error if the chunk is critical.
  2383. */
  2384. file->status_code |= CRC_ERROR;
  2385. /* Ignore the bad CRC */
  2386. if (file->global->skip != SKIP_BAD_CRC)
  2387. type_message(file, type, "bad CRC");
  2388. /* This will cause an IEND with a bad CRC to stop */
  2389. else if (CRITICAL(type))
  2390. stop(file, READ_ERROR_CODE, "bad CRC in critical chunk");
  2391. else
  2392. {
  2393. type_message(file, type, "skipped: bad CRC");
  2394. /* NOTE: this cannot be reached for IEND because it is critical. */
  2395. goto skip_chunk;
  2396. }
  2397. }
  2398. /* Check for other 'skip' cases and handle these; these only apply to
  2399. * ancillary chunks (and not tRNS, which should probably have been a critical
  2400. * chunk.)
  2401. */
  2402. if (skip_chunk_type(file->global, type))
  2403. goto skip_chunk;
  2404. /* The chunk may still be skipped if problems are detected in the LZ data,
  2405. * however the LZ data check requires a chunk. Handle this by instantiating
  2406. * a chunk unless an IDAT is already instantiated (IDAT control structures
  2407. * instantiate their own chunk.)
  2408. */
  2409. if (type != png_IDAT)
  2410. file->alloc(file, 0/*chunk*/);
  2411. else if (file->idat == NULL)
  2412. file->alloc(file, 1/*IDAT*/);
  2413. else
  2414. {
  2415. /* The chunk length must be updated for process_IDAT */
  2416. assert(file->chunk != NULL);
  2417. assert(file->chunk->chunk_type == png_IDAT);
  2418. file->chunk->chunk_length = file->length;
  2419. }
  2420. /* Record the 'next' information too, now that the original values for
  2421. * this chunk have been copied. Notice that the IDAT chunks only make a
  2422. * copy of the position of the first chunk, this is fine - process_IDAT does
  2423. * not need the position of this chunk.
  2424. */
  2425. file->length = next_length;
  2426. file->type = next_type;
  2427. getpos(file);
  2428. /* Do per-type processing, note that if this code does not return from the
  2429. * function the chunk will be skipped. The rewrite is cancelled here so that
  2430. * it can be set in the per-chunk processing.
  2431. */
  2432. file->chunk->rewrite_length = 0;
  2433. file->chunk->rewrite_offset = 0;
  2434. switch (type)
  2435. {
  2436. default:
  2437. return;
  2438. case png_IHDR:
  2439. /* Read this now and update the control structure with the information
  2440. * it contains. The header is validated completely to ensure this is a
  2441. * PNG.
  2442. */
  2443. {
  2444. struct chunk *chunk = file->chunk;
  2445. if (chunk->chunk_length != 13)
  2446. stop_invalid(file, "IHDR length");
  2447. /* Read all the IHDR information and validate it. */
  2448. setpos(chunk);
  2449. file->width = reread_4(file);
  2450. file->height = reread_4(file);
  2451. file->bit_depth = reread_byte(file);
  2452. file->color_type = reread_byte(file);
  2453. file->compression_method = reread_byte(file);
  2454. file->filter_method = reread_byte(file);
  2455. file->interlace_method = reread_byte(file);
  2456. /* This validates all the fields, and calls stop_invalid if
  2457. * there is a problem.
  2458. */
  2459. calc_image_size(file);
  2460. }
  2461. return;
  2462. /* Ancillary chunks that require further processing: */
  2463. case png_zTXt: case png_iCCP:
  2464. if (process_zTXt_iCCP(file))
  2465. return;
  2466. chunk_end(&file->chunk);
  2467. file_setpos(file, &file->data_pos);
  2468. break;
  2469. case png_iTXt:
  2470. if (process_iTXt(file))
  2471. return;
  2472. chunk_end(&file->chunk);
  2473. file_setpos(file, &file->data_pos);
  2474. break;
  2475. case png_IDAT:
  2476. if (process_IDAT(file))
  2477. return;
  2478. /* First pass: */
  2479. assert(next_type == png_IDAT);
  2480. break;
  2481. }
  2482. /* Control reaches this point if the chunk must be skipped. For chunks other
  2483. * than IDAT this means that the zlib compressed data is fatally damanged and
  2484. * the chunk will not be passed to libpng. For IDAT it means that the end of
  2485. * the IDAT stream has not yet been reached and we must handle the next
  2486. * (IDAT) chunk. If the LZ data in an IDAT stream cannot be read 'stop' must
  2487. * be used to halt parsing of the PNG.
  2488. */
  2489. read_chunk(file);
  2490. return;
  2491. /* This is the generic code to skip the current chunk; simply jump to the
  2492. * next one.
  2493. */
  2494. skip_chunk:
  2495. file->length = next_length;
  2496. file->type = next_type;
  2497. getpos(file);
  2498. read_chunk(file);
  2499. }
  2500. static png_uint_32
  2501. get32(png_bytep buffer, int offset)
  2502. /* Read a 32-bit value from an 8-byte circular buffer (used only below).
  2503. */
  2504. {
  2505. return
  2506. (buffer[ offset & 7] << 24) +
  2507. (buffer[(offset+1) & 7] << 16) +
  2508. (buffer[(offset+2) & 7] << 8) +
  2509. (buffer[(offset+3) & 7] );
  2510. }
  2511. static void
  2512. sync_stream(struct file *file)
  2513. /* The stream seems to be messed up, attempt to resync from the current chunk
  2514. * header. Executes stop on a fatal error, otherwise calls process_chunk.
  2515. */
  2516. {
  2517. png_uint_32 file_crc;
  2518. file->status_code |= STREAM_ERROR;
  2519. if (file->global->verbose)
  2520. {
  2521. fputs(" SYNC ", stderr);
  2522. type_name(file->type, stderr);
  2523. putc('\n', stderr);
  2524. }
  2525. /* Return to the start of the chunk data */
  2526. file_setpos(file, &file->data_pos);
  2527. file->read_count = 8;
  2528. if (read_4(file, &file_crc) == 4) /* else completely truncated */
  2529. {
  2530. /* Ignore the recorded chunk length, proceed through the data looking for
  2531. * a leading sequence of bytes that match the CRC in the following four
  2532. * bytes. Each time a match is found check the next 8 bytes for a valid
  2533. * length, chunk-type pair.
  2534. */
  2535. png_uint_32 length;
  2536. png_uint_32 type = file->type;
  2537. png_uint_32 crc = crc_init_4(type);
  2538. png_byte buffer[8];
  2539. unsigned int nread = 0, nused = 0;
  2540. for (length=0; length <= 0x7fffffff; ++length)
  2541. {
  2542. int ch;
  2543. if ((crc ^ 0xffffffff) == file_crc)
  2544. {
  2545. /* A match on the CRC; for IEND this is sufficient, but for anything
  2546. * else expect a following chunk header.
  2547. */
  2548. if (type == png_IEND)
  2549. {
  2550. file->length = length;
  2551. process_chunk(file, file_crc, 0, 0);
  2552. return;
  2553. }
  2554. else
  2555. {
  2556. /* Need 8 bytes */
  2557. while (nread < 8+nused)
  2558. {
  2559. ch = read_byte(file);
  2560. if (ch == EOF)
  2561. goto truncated;
  2562. buffer[(nread++) & 7] = (png_byte)ch;
  2563. }
  2564. /* Prevent overflow */
  2565. nread -= nused & ~7;
  2566. nused -= nused & ~7; /* or, nused &= 7 ;-) */
  2567. /* Examine the 8 bytes for a valid chunk header. */
  2568. {
  2569. png_uint_32 next_length = get32(buffer, nused);
  2570. if (next_length < 0x7fffffff)
  2571. {
  2572. png_uint_32 next_type = get32(buffer, nused+4);
  2573. if (chunk_type_valid(next_type))
  2574. {
  2575. file->read_count -= 8;
  2576. process_chunk(file, file_crc, next_length, next_type);
  2577. return;
  2578. }
  2579. }
  2580. /* Not valid, keep going. */
  2581. }
  2582. }
  2583. }
  2584. /* This catches up with the circular buffer which gets filled above
  2585. * while checking a chunk header. This code is slightly tricky - if
  2586. * the chunk_type is IEND the buffer will never be used, if it is not
  2587. * the code will always read ahead exactly 8 bytes and pass this on to
  2588. * process_chunk. So the invariant that IEND leaves the file position
  2589. * after the IEND CRC and other chunk leave it after the *next* chunk
  2590. * header is not broken.
  2591. */
  2592. if (nread <= nused)
  2593. {
  2594. ch = read_byte(file);
  2595. if (ch == EOF)
  2596. goto truncated;
  2597. }
  2598. else
  2599. ch = buffer[(++nused) & 7];
  2600. crc = crc_one_byte(crc, file_crc >> 24);
  2601. file_crc = (file_crc << 8) + ch;
  2602. }
  2603. /* Control gets to here if when 0x7fffffff bytes (plus 8) have been read,
  2604. * ok, treat this as a damaged stream too:
  2605. */
  2606. }
  2607. truncated:
  2608. stop(file, READ_ERROR_CODE, "damaged PNG stream");
  2609. }
  2610. static void
  2611. read_chunk(struct file *file)
  2612. /* On entry file::data_pos must be set to the position of the first byte
  2613. * of the chunk data *and* the input file must be at this position. This
  2614. * routine (via process_chunk) instantiates a chunk or IDAT control structure
  2615. * based on file::length and file::type and also resets these fields and
  2616. * file::data_pos for the chunk after this one. For an IDAT chunk the whole
  2617. * stream of IDATs will be read, until something other than an IDAT is
  2618. * encountered, and the file fields will be set for the chunk after the end
  2619. * of the stream of IDATs.
  2620. *
  2621. * For IEND the file::type field will be set to 0, and nothing beyond the end
  2622. * of the IEND chunk will have been read.
  2623. */
  2624. {
  2625. png_uint_32 length = file->length;
  2626. png_uint_32 type = file->type;
  2627. /* After IEND file::type is set to 0, if libpng attempts to read
  2628. * more data at this point this is a bug in libpng.
  2629. */
  2630. if (type == 0)
  2631. stop(file, UNEXPECTED_ERROR_CODE, "read beyond IEND");
  2632. if (file->global->verbose > 2)
  2633. {
  2634. fputs(" ", stderr);
  2635. type_name(type, stderr);
  2636. fprintf(stderr, " %lu\n", (unsigned long)length);
  2637. }
  2638. /* Start the read_crc calculation with the chunk type, then read to the end
  2639. * of the chunk data (without processing it in any way) to check that it is
  2640. * all there and calculate the CRC.
  2641. */
  2642. file->crc = crc_init_4(type);
  2643. if (crc_read_many(file, length)) /* else it was truncated */
  2644. {
  2645. png_uint_32 file_crc; /* CRC read from file */
  2646. unsigned int nread = read_4(file, &file_crc);
  2647. if (nread == 4)
  2648. {
  2649. if (type != png_IEND) /* do not read beyond IEND */
  2650. {
  2651. png_uint_32 next_length;
  2652. nread += read_4(file, &next_length);
  2653. if (nread == 8 && next_length <= 0x7fffffff)
  2654. {
  2655. png_uint_32 next_type;
  2656. nread += read_4(file, &next_type);
  2657. if (nread == 12 && chunk_type_valid(next_type))
  2658. {
  2659. /* Adjust the read count back to the correct value for this
  2660. * chunk.
  2661. */
  2662. file->read_count -= 8;
  2663. process_chunk(file, file_crc, next_length, next_type);
  2664. return;
  2665. }
  2666. }
  2667. }
  2668. else /* IEND */
  2669. {
  2670. process_chunk(file, file_crc, 0, 0);
  2671. return;
  2672. }
  2673. }
  2674. }
  2675. /* Control gets to here if the stream seems invalid or damaged in some
  2676. * way. Either there was a problem reading all the expected data (this
  2677. * chunk's data, its CRC and the length and type of the next chunk) or the
  2678. * next chunk length/type are invalid. Notice that the cases that end up
  2679. * here all correspond to cases that would otherwise terminate the read of
  2680. * the PNG file.
  2681. */
  2682. sync_stream(file);
  2683. }
  2684. /* This returns a file* from a png_struct in an implementation specific way. */
  2685. static struct file *get_control(png_const_structrp png_ptr);
  2686. static void PNGCBAPI
  2687. error_handler(png_structp png_ptr, png_const_charp message)
  2688. {
  2689. stop(get_control(png_ptr), LIBPNG_ERROR_CODE, message);
  2690. }
  2691. static void PNGCBAPI
  2692. warning_handler(png_structp png_ptr, png_const_charp message)
  2693. {
  2694. struct file *file = get_control(png_ptr);
  2695. if (file->global->warnings)
  2696. emit_error(file, LIBPNG_WARNING_CODE, message);
  2697. }
  2698. /* Read callback - this is where the work gets done to check the stream before
  2699. * passing it to libpng
  2700. */
  2701. static void PNGCBAPI
  2702. read_callback(png_structp png_ptr, png_bytep buffer, size_t count)
  2703. /* Return 'count' bytes to libpng in 'buffer' */
  2704. {
  2705. struct file *file = get_control(png_ptr);
  2706. png_uint_32 type, length; /* For the chunk be *WRITTEN* */
  2707. struct chunk *chunk;
  2708. /* libpng should always ask for at least one byte */
  2709. if (count == 0)
  2710. stop(file, UNEXPECTED_ERROR_CODE, "read callback for 0 bytes");
  2711. /* The callback always reads ahead by 8 bytes - the signature or chunk header
  2712. * - these bytes are stored in chunk_length and chunk_type. This block is
  2713. * executed once for the signature and once for the first chunk right at the
  2714. * start.
  2715. */
  2716. if (file->read_count < 8)
  2717. {
  2718. assert(file->read_count == 0);
  2719. assert((file->status_code & TRUNCATED) == 0);
  2720. (void)read_4(file, &file->length);
  2721. if (file->read_count == 4)
  2722. (void)read_4(file, &file->type);
  2723. if (file->read_count < 8)
  2724. {
  2725. assert((file->status_code & TRUNCATED) != 0);
  2726. stop(file, READ_ERROR_CODE, "not a PNG (too short)");
  2727. }
  2728. if (file->state == STATE_SIGNATURE)
  2729. {
  2730. if (file->length != sig1 || file->type != sig2)
  2731. stop(file, LIBPNG_ERROR_CODE, "not a PNG (signature)");
  2732. /* Else write it (this is the initialization of write_count, prior to
  2733. * this it contains CLEAR garbage.)
  2734. */
  2735. file->write_count = 0;
  2736. }
  2737. else
  2738. {
  2739. assert(file->state == STATE_CHUNKS);
  2740. /* The first chunk must be a well formed IHDR (this could be relaxed to
  2741. * use the checks in process_chunk, but that seems unnecessary.)
  2742. */
  2743. if (file->length != 13 || file->type != png_IHDR)
  2744. stop(file, LIBPNG_ERROR_CODE, "not a PNG (IHDR)");
  2745. /* The position of the data must be stored too */
  2746. getpos(file);
  2747. }
  2748. }
  2749. /* Retrieve previous state (because the read callbacks are made pretty much
  2750. * byte-by-byte in the sequential reader prior to 1.7).
  2751. */
  2752. chunk = file->chunk;
  2753. if (chunk != NULL)
  2754. {
  2755. length = chunk->chunk_length;
  2756. type = chunk->chunk_type;
  2757. }
  2758. else
  2759. {
  2760. /* This is the signature case; for IDAT and other chunks these values will
  2761. * be overwritten when read_chunk is called below.
  2762. */
  2763. length = file->length;
  2764. type = file->type;
  2765. }
  2766. do
  2767. {
  2768. png_uint_32 b;
  2769. /* Complete the read of a chunk; as a side effect this also instantiates
  2770. * a chunk control structure and sets the file length/type/data_pos fields
  2771. * for the *NEXT* chunk header.
  2772. *
  2773. * NOTE: at an IDAT any following IDAT chunks will also be read and the
  2774. * next_ fields will refer to the chunk after the last IDAT.
  2775. *
  2776. * NOTE: read_chunk only returns when it has read a chunk that must now be
  2777. * written.
  2778. */
  2779. if (file->state != STATE_SIGNATURE && chunk == NULL)
  2780. {
  2781. assert(file->read_count == 8);
  2782. assert(file->idat == NULL);
  2783. read_chunk(file);
  2784. chunk = file->chunk;
  2785. assert(chunk != NULL);
  2786. /* Do the initialization that was not done before. */
  2787. length = chunk->chunk_length;
  2788. type = chunk->chunk_type;
  2789. /* And start writing the new chunk. */
  2790. file->write_count = 0;
  2791. }
  2792. /* The chunk_ fields describe a chunk that must be written, or hold the
  2793. * signature. Write the header first. In the signature case this
  2794. * rewrites the signature.
  2795. */
  2796. switch (file->write_count)
  2797. {
  2798. case 0: b = length >> 24; break;
  2799. case 1: b = length >> 16; break;
  2800. case 2: b = length >> 8; break;
  2801. case 3: b = length ; break;
  2802. case 4: b = type >> 24; break;
  2803. case 5: b = type >> 16; break;
  2804. case 6: b = type >> 8; break;
  2805. case 7: b = type ; break;
  2806. case 8:
  2807. /* The header has been written. If this is really the signature
  2808. * that's all that is required and we can go to normal chunk
  2809. * processing.
  2810. */
  2811. if (file->state == STATE_SIGNATURE)
  2812. {
  2813. /* The signature has been written, the tail call to read_callback
  2814. * below (it's just a goto to the start with a decent compiler)
  2815. * will read the IHDR header ahead and validate it.
  2816. */
  2817. assert(length == sig1 && type == sig2);
  2818. file->read_count = 0; /* Forces a header read */
  2819. file->state = STATE_CHUNKS; /* IHDR: checked above */
  2820. read_callback(png_ptr, buffer, count);
  2821. return;
  2822. }
  2823. else
  2824. {
  2825. assert(chunk != NULL);
  2826. /* Set up for write, notice that repositioning the input stream
  2827. * is only necessary if something is to be read from it. Also
  2828. * notice that for the IDAT stream this must only happen once -
  2829. * on the first IDAT - to get back to the start of the list and
  2830. * this is done inside process_IDAT:
  2831. */
  2832. chunk->write_crc = crc_init_4(type);
  2833. if (file->state != STATE_IDAT && length > 0)
  2834. setpos(chunk);
  2835. }
  2836. /* FALLTHROUGH */
  2837. default:
  2838. assert(chunk != NULL);
  2839. /* NOTE: the arithmetic below overflows and gives a large positive
  2840. * png_uint_32 value until the whole chunk data has been written.
  2841. */
  2842. switch (file->write_count - length)
  2843. {
  2844. /* Write the chunk data, normally this just comes from
  2845. * the file. The only exception is for that part of a
  2846. * chunk which is zlib data and which must be rewritten,
  2847. * and IDAT chunks which can be completely
  2848. * reconstructed.
  2849. */
  2850. default:
  2851. if (file->state == STATE_IDAT)
  2852. {
  2853. struct IDAT *idat = file->idat;
  2854. assert(idat != NULL);
  2855. /* Read an IDAT byte from the input stream of IDAT chunks.
  2856. * Because the IDAT stream can be re-chunked this stream is
  2857. * held in the struct IDAT members. The chunk members, in
  2858. * particular chunk_length (and therefore the length local)
  2859. * refer to the output chunk.
  2860. */
  2861. while (idat->idat_index >= idat->idat_length)
  2862. {
  2863. /* Advance one chunk */
  2864. struct IDAT_list *cur = idat->idat_cur;
  2865. assert(idat->idat_index == idat->idat_length);
  2866. assert(cur != NULL && cur->count > 0);
  2867. /* NOTE: IDAT_list::count here, not IDAT_list::length */
  2868. if (++(idat->idat_count) >= cur->count)
  2869. {
  2870. assert(idat->idat_count == cur->count);
  2871. /* Move on to the next IDAT_list: */
  2872. cur = cur->next;
  2873. /* This is an internal error - read beyond the end of
  2874. * the pre-calculated stream.
  2875. */
  2876. if (cur == NULL || cur->count == 0)
  2877. stop(file, UNEXPECTED_ERROR_CODE,
  2878. "read beyond end of IDAT");
  2879. idat->idat_count = 0;
  2880. idat->idat_cur = cur;
  2881. }
  2882. idat->idat_index = 0;
  2883. /* Zero length IDAT chunks are permitted, so the length
  2884. * here may be 0.
  2885. */
  2886. idat->idat_length = cur->lengths[idat->idat_count];
  2887. /* And skip 12 bytes to the next chunk data */
  2888. skip_12(file);
  2889. }
  2890. /* The index is always that of the next byte, the rest of
  2891. * the information is always the current IDAT chunk and the
  2892. * current list.
  2893. */
  2894. ++(idat->idat_index);
  2895. }
  2896. /* Read the byte from the stream. */
  2897. b = reread_byte(file);
  2898. /* If the byte must be rewritten handle that here */
  2899. if (chunk->rewrite_length > 0)
  2900. {
  2901. if (chunk->rewrite_offset > 0)
  2902. --(chunk->rewrite_offset);
  2903. else
  2904. {
  2905. b = chunk->rewrite_buffer[0];
  2906. memmove(chunk->rewrite_buffer, chunk->rewrite_buffer+1,
  2907. (sizeof chunk->rewrite_buffer)-
  2908. (sizeof chunk->rewrite_buffer[0]));
  2909. --(chunk->rewrite_length);
  2910. }
  2911. }
  2912. chunk->write_crc = crc_one_byte(chunk->write_crc, b);
  2913. break;
  2914. /* The CRC is written at:
  2915. *
  2916. * chunk_write == chunk_length+8..chunk_length+11
  2917. *
  2918. * so 8 to 11. The CRC is not (yet) conditioned.
  2919. */
  2920. case 8: b = chunk->write_crc >> 24; goto write_crc;
  2921. case 9: b = chunk->write_crc >> 16; goto write_crc;
  2922. case 10: b = chunk->write_crc >> 8; goto write_crc;
  2923. case 11:
  2924. /* This must happen before the chunk_end below: */
  2925. b = chunk->write_crc;
  2926. if (file->global->verbose > 2)
  2927. {
  2928. fputs(" ", stderr);
  2929. type_name(type, stderr);
  2930. fprintf(stderr, " %lu 0x%.8x\n", (unsigned long)length,
  2931. chunk->write_crc ^ 0xffffffff);
  2932. }
  2933. /* The IDAT stream is written without a call to read_chunk
  2934. * until the end is reached. rechunk_length() calculates the
  2935. * length of the output chunks. Control gets to this point at
  2936. * the end of an *output* chunk - the length calculated by
  2937. * rechunk_length. If this corresponds to the end of the
  2938. * input stream stop writing IDAT chunks, otherwise continue.
  2939. */
  2940. if (file->state == STATE_IDAT &&
  2941. (file->idat->idat_index < file->idat->idat_length ||
  2942. 1+file->idat->idat_count < file->idat->idat_cur->count ||
  2943. file->idat->idat_cur != file->idat->idat_list_tail))
  2944. {
  2945. /* Write another IDAT chunk. Call rechunk_length to
  2946. * calculate the length required.
  2947. */
  2948. length = chunk->chunk_length =
  2949. rechunk_length(file->idat, 0/*end*/);
  2950. assert(type == png_IDAT);
  2951. file->write_count = 0; /* for the new chunk */
  2952. --(file->write_count); /* fake out the increment below */
  2953. }
  2954. else
  2955. {
  2956. /* Entered at the end of a non-IDAT chunk and at the end of
  2957. * the IDAT stream. The rewrite should have been cleared.
  2958. */
  2959. if (chunk->rewrite_length > 0 || chunk->rewrite_offset > 0)
  2960. stop(file, UNEXPECTED_ERROR_CODE, "pending rewrite");
  2961. /* This is the last byte so reset chunk_read for the next
  2962. * chunk and move the input file to the position after the
  2963. * *next* chunk header if required.
  2964. */
  2965. file->read_count = 8;
  2966. file_setpos(file, &file->data_pos);
  2967. if (file->idat == NULL)
  2968. chunk_end(&file->chunk);
  2969. else
  2970. IDAT_end(&file->idat);
  2971. }
  2972. write_crc:
  2973. b ^= 0xff; /* conditioning */
  2974. break;
  2975. }
  2976. break;
  2977. }
  2978. /* Write one byte */
  2979. b &= 0xff;
  2980. *buffer++ = (png_byte)b;
  2981. --count;
  2982. write_byte(file, (png_byte)b); /* increments chunk_write */
  2983. }
  2984. while (count > 0);
  2985. }
  2986. /* Bundle the file and an uninitialized chunk and IDAT control structure
  2987. * together to allow implementation of the chunk/IDAT allocate routine.
  2988. */
  2989. struct control
  2990. {
  2991. struct file file;
  2992. struct chunk chunk;
  2993. struct IDAT idat;
  2994. };
  2995. static int
  2996. control_end(struct control *control)
  2997. {
  2998. return file_end(&control->file);
  2999. }
  3000. static struct file *
  3001. get_control(png_const_structrp png_ptr)
  3002. {
  3003. /* This just returns the (file*). The chunk and idat control structures
  3004. * don't always exist.
  3005. */
  3006. struct control *control = voidcast(struct control*,
  3007. png_get_error_ptr(png_ptr));
  3008. return &control->file;
  3009. }
  3010. static void
  3011. allocate(struct file *file, int allocate_idat)
  3012. {
  3013. struct control *control = voidcast(struct control*, file->alloc_ptr);
  3014. if (allocate_idat)
  3015. {
  3016. assert(file->idat == NULL);
  3017. IDAT_init(&control->idat, file);
  3018. }
  3019. else /* chunk */
  3020. {
  3021. assert(file->chunk == NULL);
  3022. chunk_init(&control->chunk, file);
  3023. }
  3024. }
  3025. static int
  3026. control_init(struct control *control, struct global *global,
  3027. const char *file_name, const char *out_name)
  3028. /* This wraps file_init(&control::file) and simply returns the result from
  3029. * file_init.
  3030. */
  3031. {
  3032. return file_init(&control->file, global, file_name, out_name, control,
  3033. allocate);
  3034. }
  3035. static int
  3036. read_png(struct control *control)
  3037. /* Read a PNG, return 0 on success else an error (status) code; a bit mask as
  3038. * defined for file::status_code as above.
  3039. */
  3040. {
  3041. png_structp png_ptr;
  3042. png_infop info_ptr = NULL;
  3043. volatile int rc;
  3044. png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
  3045. error_handler, warning_handler);
  3046. if (png_ptr == NULL)
  3047. {
  3048. /* This is not really expected. */
  3049. log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
  3050. control->file.status_code |= INTERNAL_ERROR;
  3051. return LIBPNG_ERROR_CODE;
  3052. }
  3053. rc = setjmp(control->file.jmpbuf);
  3054. if (rc == 0)
  3055. {
  3056. # ifdef PNG_SET_USER_LIMITS_SUPPORTED
  3057. /* Remove any limits on the size of PNG files that can be read,
  3058. * without this we may reject files based on built-in safety
  3059. * limits.
  3060. */
  3061. png_set_user_limits(png_ptr, 0x7fffffff, 0x7fffffff);
  3062. png_set_chunk_cache_max(png_ptr, 0);
  3063. png_set_chunk_malloc_max(png_ptr, 0);
  3064. # endif
  3065. png_set_read_fn(png_ptr, control, read_callback);
  3066. info_ptr = png_create_info_struct(png_ptr);
  3067. if (info_ptr == NULL)
  3068. png_error(png_ptr, "OOM allocating info structure");
  3069. if (control->file.global->verbose)
  3070. fprintf(stderr, " INFO\n");
  3071. png_read_info(png_ptr, info_ptr);
  3072. {
  3073. png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
  3074. int passes = png_set_interlace_handling(png_ptr);
  3075. int pass;
  3076. png_start_read_image(png_ptr);
  3077. for (pass = 0; pass < passes; ++pass)
  3078. {
  3079. png_uint_32 y = height;
  3080. /* NOTE: this skips asking libpng to return either version of
  3081. * the image row, but libpng still reads the rows.
  3082. */
  3083. while (y-- > 0)
  3084. png_read_row(png_ptr, NULL, NULL);
  3085. }
  3086. }
  3087. if (control->file.global->verbose)
  3088. fprintf(stderr, " END\n");
  3089. /* Make sure to read to the end of the file: */
  3090. png_read_end(png_ptr, info_ptr);
  3091. }
  3092. png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
  3093. return rc;
  3094. }
  3095. static int
  3096. one_file(struct global *global, const char *file_name, const char *out_name)
  3097. {
  3098. int rc;
  3099. struct control control;
  3100. if (global->verbose)
  3101. fprintf(stderr, "FILE %s -> %s\n", file_name,
  3102. out_name ? out_name : "<none>");
  3103. /* Although control_init can return a failure code the structure is always
  3104. * initialized, so control_end can be used to accumulate any status codes.
  3105. */
  3106. rc = control_init(&control, global, file_name, out_name);
  3107. if (rc == 0)
  3108. rc = read_png(&control);
  3109. rc |= control_end(&control);
  3110. return rc;
  3111. }
  3112. static void
  3113. usage(const char *prog)
  3114. {
  3115. /* ANSI C-90 limits strings to 509 characters, so use a string array: */
  3116. size_t i;
  3117. static const char *usage_string[] = {
  3118. " Tests, optimizes and optionally fixes the zlib header in PNG files.",
  3119. " Optionally, when fixing, strips ancillary chunks from the file.",
  3120. 0,
  3121. "OPTIONS",
  3122. " OPERATION",
  3123. " By default files are just checked for readability with a summary of the",
  3124. " of zlib issues founds for each compressed chunk and the IDAT stream in",
  3125. " the file.",
  3126. " --optimize (-o):",
  3127. " Find the smallest deflate window size for the compressed data.",
  3128. " --strip=[none|crc|unsafe|unused|transform|color|all]:",
  3129. " none (default): Retain all chunks.",
  3130. " crc: Remove chunks with a bad CRC.",
  3131. " unsafe: Remove chunks that may be unsafe to retain if the image data",
  3132. " is modified. This is set automatically if --max is given but",
  3133. " may be cancelled by a later --strip=none.",
  3134. " unused: Remove chunks not used by libpng when decoding an image.",
  3135. " This retains any chunks that might be used by libpng image",
  3136. " transformations.",
  3137. " transform: unused+bKGD.",
  3138. " color: transform+iCCP and cHRM.",
  3139. " all: color+gAMA and sRGB.",
  3140. " Only ancillary chunks are ever removed. In addition the tRNS and sBIT",
  3141. " chunks are never removed as they affect exact interpretation of the",
  3142. " image pixel values. The following known chunks are treated specially",
  3143. " by the above options:",
  3144. " gAMA, sRGB [all]: These specify the gamma encoding used for the pixel",
  3145. " values.",
  3146. " cHRM, iCCP [color]: These specify how colors are encoded. iCCP also",
  3147. " specifies the exact encoding of a pixel value; however, in",
  3148. " practice most programs will ignore it.",
  3149. " bKGD [transform]: This is used by libpng transforms."
  3150. " --max=<number>:",
  3151. " Use IDAT chunks sized <number>. If no number is given the IDAT",
  3152. " chunks will be the maximum size permitted; 2^31-1 bytes. If the option",
  3153. " is omitted the original chunk sizes will not be changed. When the",
  3154. " option is given --strip=unsafe is set automatically. This may be",
  3155. " cancelled if you know that all unknown unsafe-to-copy chunks really are",
  3156. " safe to copy across an IDAT size change. This is true of all chunks",
  3157. " that have ever been formally proposed as PNG extensions.",
  3158. " MESSAGES",
  3159. " By default the program only outputs summaries for each file.",
  3160. " --quiet (-q):",
  3161. " Do not output the summaries except for files that cannot be read. With",
  3162. " two --quiets these are not output either.",
  3163. " --errors (-e):",
  3164. " Output errors from libpng and the program (except too-far-back).",
  3165. " --warnings (-w):",
  3166. " Output warnings from libpng.",
  3167. " OUTPUT",
  3168. " By default nothing is written.",
  3169. " --out=<file>:",
  3170. " Write the optimized/corrected version of the next PNG to <file>. This",
  3171. " overrides the following two options",
  3172. " --suffix=<suffix>:",
  3173. " Set --out=<name><suffix> for all following files unless overridden on",
  3174. " a per-file basis by explicit --out.",
  3175. " --prefix=<prefix>:",
  3176. " Set --out=<prefix><name> for all the following files unless overridden",
  3177. " on a per-file basis by explicit --out.",
  3178. " These two options can be used together to produce a suffix and prefix.",
  3179. " INTERNAL OPTIONS",
  3180. #if 0 /*NYI*/
  3181. #ifdef PNG_MAXIMUM_INFLATE_WINDOW
  3182. " --test:",
  3183. " Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables",
  3184. " output as this would produce a broken file.",
  3185. #endif
  3186. #endif
  3187. 0,
  3188. "EXIT CODES",
  3189. " *** SUBJECT TO CHANGE ***",
  3190. " The program exit code is value in the range 0..127 holding a bit mask of",
  3191. " the following codes. Notice that the results for each file are combined",
  3192. " together - check one file at a time to get a meaningful error code!",
  3193. " 0x01: The zlib too-far-back error existed in at least one chunk.",
  3194. " 0x02: At least one chunk had a CRC error.",
  3195. " 0x04: A chunk length was incorrect.",
  3196. " 0x08: The file was truncated.",
  3197. " Errors less than 16 are potentially recoverable, for a single file if the",
  3198. " exit code is less than 16 the file could be read (with corrections if a",
  3199. " non-zero code is returned).",
  3200. " 0x10: The file could not be read, even with corrections.",
  3201. " 0x20: The output file could not be written.",
  3202. " 0x40: An unexpected, potentially internal, error occurred.",
  3203. " If the command line arguments are incorrect the program exits with exit",
  3204. " 255. Some older operating systems only support 7-bit exit codes, on those",
  3205. " systems it is suggested that this program is first tested by supplying",
  3206. " invalid arguments.",
  3207. 0,
  3208. "DESCRIPTION",
  3209. " " PROGRAM_NAME ":",
  3210. " checks each PNG file on the command line for errors. By default errors are",
  3211. " not output and the program just returns an exit code and prints a summary.",
  3212. " With the --quiet (-q) option the summaries are suppressed too and the",
  3213. " program only outputs unexpected errors (internal errors and file open",
  3214. " errors).",
  3215. " Various known problems in PNG files are fixed while the file is being read",
  3216. " The exit code says what problems were fixed. In particular the zlib error:",
  3217. 0,
  3218. " \"invalid distance too far back\"",
  3219. 0,
  3220. " caused by an incorrect optimization of a zlib stream is fixed in any",
  3221. " compressed chunk in which it is encountered. An integrity problem of the",
  3222. " PNG stream caused by a bug in libpng which wrote an incorrect chunk length",
  3223. " is also fixed. Chunk CRC errors are automatically fixed up.",
  3224. 0,
  3225. " Setting one of the \"OUTPUT\" options causes the possibly modified file to",
  3226. " be written to a new file.",
  3227. 0,
  3228. " Notice that some PNG files with the zlib optimization problem can still be",
  3229. " read by libpng under some circumstances. This program will still detect",
  3230. " and, if requested, correct the error.",
  3231. 0,
  3232. " The program will reliably process all files on the command line unless",
  3233. " either an invalid argument causes the usage message (this message) to be",
  3234. " produced or the program crashes.",
  3235. 0,
  3236. " The summary lines describe issues encountered with the zlib compressed",
  3237. " stream of a chunk. They have the following format, which is SUBJECT TO",
  3238. " CHANGE in the future:",
  3239. 0,
  3240. " chunk reason comp-level p1 p2 p3 p4 file",
  3241. 0,
  3242. " p1 through p4 vary according to the 'reason'. There are always 8 space",
  3243. " separated fields. Reasons specific formats are:",
  3244. 0,
  3245. " chunk ERR status code read-errno write-errno message file",
  3246. " chunk SKP comp-level file-bits zlib-rc compressed message file",
  3247. " chunk ??? comp-level file-bits ok-bits compressed uncompress file",
  3248. 0,
  3249. " The various fields are",
  3250. 0,
  3251. "$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem",
  3252. " is reported by libpng at the start of the IDAT stream.",
  3253. "$2 reason: One of:",
  3254. " CHK: A zlib header checksum was detected and fixed.",
  3255. " TFB: The zlib too far back error was detected and fixed.",
  3256. " OK : No errors were detected in the zlib stream and optimization",
  3257. " was not requested, or was not possible.",
  3258. " OPT: The zlib stream window bits value could be improved (and was).",
  3259. " SKP: The chunk was skipped because of a zlib issue (zlib-rc) with",
  3260. " explanation 'message'",
  3261. " ERR: The read of the file was aborted. The parameters explain why.",
  3262. "$3 status: For 'ERR' the accumulated status code from 'EXIT CODES' above.",
  3263. " This is printed as a 2 digit hexadecimal value",
  3264. " comp-level: The recorded compression level (FLEVEL) of a zlib stream",
  3265. " expressed as a string {supfast,stdfast,default,maximum}",
  3266. "$4 code: The file exit code; where stop was called, as a fairly terse",
  3267. " string {warning,libpng,zlib,invalid,read,write,unexpected}.",
  3268. " file-bits: The zlib window bits recorded in the file.",
  3269. "$5 read-errno: A system errno value from a read translated by strerror(3).",
  3270. " zlib-rc: A zlib return code as a string (see zlib.h).",
  3271. " ok-bits: The smallest zlib window bits value that works.",
  3272. "$6 write-errno:A system errno value from a write translated by strerror(3).",
  3273. " compressed: The count of compressed bytes in the zlib stream, when the",
  3274. " reason is 'SKP'; this is a count of the bytes read from the",
  3275. " stream when the fatal error was encountered.",
  3276. "$7 message: An error message (spaces replaced by _, as in all parameters),",
  3277. " uncompress: The count of bytes from uncompressing the zlib stream; this",
  3278. " may not be the same as the number of bytes in the image.",
  3279. "$8 file: The name of the file (this may contain spaces).",
  3280. };
  3281. fprintf(stderr, "Usage: %s {[options] png-file}\n", prog);
  3282. for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i)
  3283. {
  3284. if (usage_string[i] != 0)
  3285. fputs(usage_string[i], stderr);
  3286. fputc('\n', stderr);
  3287. }
  3288. exit(255);
  3289. }
  3290. int
  3291. main(int argc, const char **argv)
  3292. {
  3293. char temp_name[FILENAME_MAX+1];
  3294. const char * prog = *argv;
  3295. const char * outfile = NULL;
  3296. const char * suffix = NULL;
  3297. const char * prefix = NULL;
  3298. int done = 0; /* if at least one file is processed */
  3299. struct global global;
  3300. global_init(&global);
  3301. while (--argc > 0)
  3302. {
  3303. ++argv;
  3304. if (strcmp(*argv, "--debug") == 0)
  3305. {
  3306. /* To help debugging problems: */
  3307. global.errors = global.warnings = 1;
  3308. global.quiet = 0;
  3309. global.verbose = 7;
  3310. }
  3311. else if (strncmp(*argv, "--max=", 6) == 0)
  3312. {
  3313. global.idat_max = (png_uint_32)atol(6+*argv);
  3314. if (global.skip < SKIP_UNSAFE)
  3315. global.skip = SKIP_UNSAFE;
  3316. }
  3317. else if (strcmp(*argv, "--max") == 0)
  3318. {
  3319. global.idat_max = 0x7fffffff;
  3320. if (global.skip < SKIP_UNSAFE)
  3321. global.skip = SKIP_UNSAFE;
  3322. }
  3323. else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
  3324. global.optimize_zlib = 1;
  3325. else if (strncmp(*argv, "--out=", 6) == 0)
  3326. outfile = 6+*argv;
  3327. else if (strncmp(*argv, "--suffix=", 9) == 0)
  3328. suffix = 9+*argv;
  3329. else if (strncmp(*argv, "--prefix=", 9) == 0)
  3330. prefix = 9+*argv;
  3331. else if (strcmp(*argv, "--strip=none") == 0)
  3332. global.skip = SKIP_NONE;
  3333. else if (strcmp(*argv, "--strip=crc") == 0)
  3334. global.skip = SKIP_BAD_CRC;
  3335. else if (strcmp(*argv, "--strip=unsafe") == 0)
  3336. global.skip = SKIP_UNSAFE;
  3337. else if (strcmp(*argv, "--strip=unused") == 0)
  3338. global.skip = SKIP_UNUSED;
  3339. else if (strcmp(*argv, "--strip=transform") == 0)
  3340. global.skip = SKIP_TRANSFORM;
  3341. else if (strcmp(*argv, "--strip=color") == 0)
  3342. global.skip = SKIP_COLOR;
  3343. else if (strcmp(*argv, "--strip=all") == 0)
  3344. global.skip = SKIP_ALL;
  3345. else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
  3346. global.errors = 1;
  3347. else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
  3348. global.warnings = 1;
  3349. else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
  3350. {
  3351. if (global.quiet)
  3352. global.quiet = 2;
  3353. else
  3354. global.quiet = 1;
  3355. }
  3356. else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
  3357. ++global.verbose;
  3358. #if 0
  3359. /* NYI */
  3360. # ifdef PNG_MAXIMUM_INFLATE_WINDOW
  3361. else if (strcmp(*argv, "--test") == 0)
  3362. ++set_option;
  3363. # endif
  3364. #endif
  3365. else if ((*argv)[0] == '-')
  3366. usage(prog);
  3367. else
  3368. {
  3369. size_t outlen = strlen(*argv);
  3370. if (outfile == NULL) /* else this takes precedence */
  3371. {
  3372. /* Consider the prefix/suffix options */
  3373. if (prefix != NULL)
  3374. {
  3375. size_t prefixlen = strlen(prefix);
  3376. if (prefixlen+outlen > FILENAME_MAX)
  3377. {
  3378. fprintf(stderr, "%s: output file name too long: %s%s%s\n",
  3379. prog, prefix, *argv, suffix ? suffix : "");
  3380. global.status_code |= WRITE_ERROR;
  3381. continue;
  3382. }
  3383. memcpy(temp_name, prefix, prefixlen);
  3384. memcpy(temp_name+prefixlen, *argv, outlen);
  3385. outlen += prefixlen;
  3386. outfile = temp_name;
  3387. }
  3388. else if (suffix != NULL)
  3389. memcpy(temp_name, *argv, outlen);
  3390. temp_name[outlen] = 0;
  3391. if (suffix != NULL)
  3392. {
  3393. size_t suffixlen = strlen(suffix);
  3394. if (outlen+suffixlen > FILENAME_MAX)
  3395. {
  3396. fprintf(stderr, "%s: output file name too long: %s%s\n",
  3397. prog, *argv, suffix);
  3398. global.status_code |= WRITE_ERROR;
  3399. continue;
  3400. }
  3401. memcpy(temp_name+outlen, suffix, suffixlen);
  3402. outlen += suffixlen;
  3403. temp_name[outlen] = 0;
  3404. outfile = temp_name;
  3405. }
  3406. }
  3407. (void)one_file(&global, *argv, outfile);
  3408. ++done;
  3409. outfile = NULL;
  3410. }
  3411. }
  3412. if (!done)
  3413. usage(prog);
  3414. return global_end(&global);
  3415. }
  3416. #else /* ZLIB_VERNUM < 0x1240 */
  3417. int
  3418. main(void)
  3419. {
  3420. fprintf(stderr,
  3421. "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n",
  3422. ZLIB_VERNUM);
  3423. return 77;
  3424. }
  3425. #endif /* ZLIB_VERNUM */
  3426. #else /* No read support */
  3427. int
  3428. main(void)
  3429. {
  3430. fprintf(stderr, "pngfix does not work without read deinterlace support\n");
  3431. return 77;
  3432. }
  3433. #endif /* PNG_READ_SUPPORTED && PNG_EASY_ACCESS_SUPPORTED */
  3434. #else /* No setjmp support */
  3435. int
  3436. main(void)
  3437. {
  3438. fprintf(stderr, "pngfix does not work without setjmp support\n");
  3439. return 77;
  3440. }
  3441. #endif /* PNG_SETJMP_SUPPORTED */