pngfix.c 127 KB

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