xmlparse.c 281 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616
  1. /* ba4cdf9bdb534f355a9def4c9e25d20ee8e72f95b0a4d930be52e563f5080196 (2.6.3+)
  2. __ __ _
  3. ___\ \/ /_ __ __ _| |_
  4. / _ \\ /| '_ \ / _` | __|
  5. | __// \| |_) | (_| | |_
  6. \___/_/\_\ .__/ \__,_|\__|
  7. |_| XML parser
  8. Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
  9. Copyright (c) 2000 Clark Cooper <[email protected]>
  10. Copyright (c) 2000-2006 Fred L. Drake, Jr. <[email protected]>
  11. Copyright (c) 2001-2002 Greg Stein <[email protected]>
  12. Copyright (c) 2002-2016 Karl Waclawek <[email protected]>
  13. Copyright (c) 2005-2009 Steven Solie <[email protected]>
  14. Copyright (c) 2016 Eric Rahm <[email protected]>
  15. Copyright (c) 2016-2024 Sebastian Pipping <[email protected]>
  16. Copyright (c) 2016 Gaurav <[email protected]>
  17. Copyright (c) 2016 Thomas Beutlich <[email protected]>
  18. Copyright (c) 2016 Gustavo Grieco <[email protected]>
  19. Copyright (c) 2016 Pascal Cuoq <[email protected]>
  20. Copyright (c) 2016 Ed Schouten <[email protected]>
  21. Copyright (c) 2017-2022 Rhodri James <[email protected]>
  22. Copyright (c) 2017 Václav Slavík <[email protected]>
  23. Copyright (c) 2017 Viktor Szakats <[email protected]>
  24. Copyright (c) 2017 Chanho Park <[email protected]>
  25. Copyright (c) 2017 Rolf Eike Beer <[email protected]>
  26. Copyright (c) 2017 Hans Wennborg <[email protected]>
  27. Copyright (c) 2018 Anton Maklakov <[email protected]>
  28. Copyright (c) 2018 Benjamin Peterson <[email protected]>
  29. Copyright (c) 2018 Marco Maggi <[email protected]>
  30. Copyright (c) 2018 Mariusz Zaborski <[email protected]>
  31. Copyright (c) 2019 David Loffredo <[email protected]>
  32. Copyright (c) 2019-2020 Ben Wagner <[email protected]>
  33. Copyright (c) 2019 Vadim Zeitlin <[email protected]>
  34. Copyright (c) 2021 Donghee Na <[email protected]>
  35. Copyright (c) 2022 Samanta Navarro <[email protected]>
  36. Copyright (c) 2022 Jeffrey Walton <[email protected]>
  37. Copyright (c) 2022 Jann Horn <[email protected]>
  38. Copyright (c) 2022 Sean McBride <[email protected]>
  39. Copyright (c) 2023 Owain Davies <[email protected]>
  40. Copyright (c) 2023-2024 Sony Corporation / Snild Dolkow <[email protected]>
  41. Copyright (c) 2024 Berkay Eren Ürün <[email protected]>
  42. Licensed under the MIT license:
  43. Permission is hereby granted, free of charge, to any person obtaining
  44. a copy of this software and associated documentation files (the
  45. "Software"), to deal in the Software without restriction, including
  46. without limitation the rights to use, copy, modify, merge, publish,
  47. distribute, sublicense, and/or sell copies of the Software, and to permit
  48. persons to whom the Software is furnished to do so, subject to the
  49. following conditions:
  50. The above copyright notice and this permission notice shall be included
  51. in all copies or substantial portions of the Software.
  52. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  53. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  54. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  55. NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  56. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  57. OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  58. USE OR OTHER DEALINGS IN THE SOFTWARE.
  59. */
  60. #define XML_BUILDING_EXPAT 1
  61. #include "expat_config.h"
  62. #if ! defined(XML_GE) || (1 - XML_GE - 1 == 2) || (XML_GE < 0) || (XML_GE > 1)
  63. # error XML_GE (for general entities) must be defined, non-empty, either 1 or 0 (0 to disable, 1 to enable; 1 is a common default)
  64. #endif
  65. #if defined(XML_DTD) && XML_GE == 0
  66. # error Either undefine XML_DTD or define XML_GE to 1.
  67. #endif
  68. #if ! defined(XML_CONTEXT_BYTES) || (1 - XML_CONTEXT_BYTES - 1 == 2) \
  69. || (XML_CONTEXT_BYTES + 0 < 0)
  70. # error XML_CONTEXT_BYTES must be defined, non-empty and >=0 (0 to disable, >=1 to enable; 1024 is a common default)
  71. #endif
  72. #if defined(HAVE_SYSCALL_GETRANDOM)
  73. # if ! defined(_GNU_SOURCE)
  74. # define _GNU_SOURCE 1 /* syscall prototype */
  75. # endif
  76. #endif
  77. #ifdef _WIN32
  78. /* force stdlib to define rand_s() */
  79. # if ! defined(_CRT_RAND_S)
  80. # define _CRT_RAND_S
  81. # endif
  82. #endif
  83. #include <stdbool.h>
  84. #include <stddef.h>
  85. #include <string.h> /* memset(), memcpy() */
  86. #include <assert.h>
  87. #include <limits.h> /* UINT_MAX */
  88. #include <stdio.h> /* fprintf */
  89. #include <stdlib.h> /* getenv, rand_s */
  90. #include <stdint.h> /* uintptr_t */
  91. #include <math.h> /* isnan */
  92. #ifdef _WIN32
  93. # define getpid GetCurrentProcessId
  94. #else
  95. # include <sys/time.h> /* gettimeofday() */
  96. # include <sys/types.h> /* getpid() */
  97. # include <unistd.h> /* getpid() */
  98. # include <fcntl.h> /* O_RDONLY */
  99. # include <errno.h>
  100. #endif
  101. #ifdef _WIN32
  102. # include "winconfig.h"
  103. #endif
  104. #include "ascii.h"
  105. #include "expat.h"
  106. #include "siphash.h"
  107. #if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
  108. # if defined(HAVE_GETRANDOM)
  109. # include <sys/random.h> /* getrandom */
  110. # else
  111. # include <unistd.h> /* syscall */
  112. # include <sys/syscall.h> /* SYS_getrandom */
  113. # endif
  114. # if ! defined(GRND_NONBLOCK)
  115. # define GRND_NONBLOCK 0x0001
  116. # endif /* defined(GRND_NONBLOCK) */
  117. #endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
  118. #if defined(HAVE_LIBBSD) \
  119. && (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
  120. # include <bsd/stdlib.h>
  121. #endif
  122. #if defined(_WIN32) && ! defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
  123. # define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
  124. #endif
  125. #if ! defined(HAVE_GETRANDOM) && ! defined(HAVE_SYSCALL_GETRANDOM) \
  126. && ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) \
  127. && ! defined(XML_DEV_URANDOM) && ! defined(_WIN32) \
  128. && ! defined(XML_POOR_ENTROPY)
  129. # error You do not have support for any sources of high quality entropy \
  130. enabled. For end user security, that is probably not what you want. \
  131. \
  132. Your options include: \
  133. * Linux >=3.17 + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
  134. * Linux >=3.17 + glibc (including <2.25) (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
  135. * BSD / macOS >=10.7 / glibc >=2.36 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
  136. * BSD / macOS (including <10.7) / glibc >=2.36 (arc4random): HAVE_ARC4RANDOM, \
  137. * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
  138. * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
  139. * Linux (including <3.17) / BSD / macOS (including <10.7) / Solaris >=8 (/dev/urandom): XML_DEV_URANDOM, \
  140. * Windows >=Vista (rand_s): _WIN32. \
  141. \
  142. If insist on not using any of these, bypass this error by defining \
  143. XML_POOR_ENTROPY; you have been warned. \
  144. \
  145. If you have reasons to patch this detection code away or need changes \
  146. to the build system, please open a bug. Thank you!
  147. #endif
  148. #ifdef XML_UNICODE
  149. # define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
  150. # define XmlConvert XmlUtf16Convert
  151. # define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
  152. # define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
  153. # define XmlEncode XmlUtf16Encode
  154. # define MUST_CONVERT(enc, s) (! (enc)->isUtf16 || (((uintptr_t)(s)) & 1))
  155. typedef unsigned short ICHAR;
  156. #else
  157. # define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
  158. # define XmlConvert XmlUtf8Convert
  159. # define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
  160. # define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
  161. # define XmlEncode XmlUtf8Encode
  162. # define MUST_CONVERT(enc, s) (! (enc)->isUtf8)
  163. typedef char ICHAR;
  164. #endif
  165. #ifndef XML_NS
  166. # define XmlInitEncodingNS XmlInitEncoding
  167. # define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
  168. # undef XmlGetInternalEncodingNS
  169. # define XmlGetInternalEncodingNS XmlGetInternalEncoding
  170. # define XmlParseXmlDeclNS XmlParseXmlDecl
  171. #endif
  172. #ifdef XML_UNICODE
  173. # ifdef XML_UNICODE_WCHAR_T
  174. # define XML_T(x) (const wchar_t) x
  175. # define XML_L(x) L##x
  176. # else
  177. # define XML_T(x) (const unsigned short)x
  178. # define XML_L(x) x
  179. # endif
  180. #else
  181. # define XML_T(x) x
  182. # define XML_L(x) x
  183. #endif
  184. /* Round up n to be a multiple of sz, where sz is a power of 2. */
  185. #define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
  186. /* Do safe (NULL-aware) pointer arithmetic */
  187. #define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
  188. #define EXPAT_MIN(a, b) (((a) < (b)) ? (a) : (b))
  189. #include "internal.h"
  190. #include "xmltok.h"
  191. #include "xmlrole.h"
  192. typedef const XML_Char *KEY;
  193. typedef struct {
  194. KEY name;
  195. } NAMED;
  196. typedef struct {
  197. NAMED **v;
  198. unsigned char power;
  199. size_t size;
  200. size_t used;
  201. const XML_Memory_Handling_Suite *mem;
  202. } HASH_TABLE;
  203. static size_t keylen(KEY s);
  204. static void copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key);
  205. /* For probing (after a collision) we need a step size relative prime
  206. to the hash table size, which is a power of 2. We use double-hashing,
  207. since we can calculate a second hash value cheaply by taking those bits
  208. of the first hash value that were discarded (masked out) when the table
  209. index was calculated: index = hash & mask, where mask = table->size - 1.
  210. We limit the maximum step size to table->size / 4 (mask >> 2) and make
  211. it odd, since odd numbers are always relative prime to a power of 2.
  212. */
  213. #define SECOND_HASH(hash, mask, power) \
  214. ((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2))
  215. #define PROBE_STEP(hash, mask, power) \
  216. ((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
  217. typedef struct {
  218. NAMED **p;
  219. NAMED **end;
  220. } HASH_TABLE_ITER;
  221. #define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
  222. #define INIT_DATA_BUF_SIZE 1024
  223. #define INIT_ATTS_SIZE 16
  224. #define INIT_ATTS_VERSION 0xFFFFFFFF
  225. #define INIT_BLOCK_SIZE 1024
  226. #define INIT_BUFFER_SIZE 1024
  227. #define EXPAND_SPARE 24
  228. typedef struct binding {
  229. struct prefix *prefix;
  230. struct binding *nextTagBinding;
  231. struct binding *prevPrefixBinding;
  232. const struct attribute_id *attId;
  233. XML_Char *uri;
  234. int uriLen;
  235. int uriAlloc;
  236. } BINDING;
  237. typedef struct prefix {
  238. const XML_Char *name;
  239. BINDING *binding;
  240. } PREFIX;
  241. typedef struct {
  242. const XML_Char *str;
  243. const XML_Char *localPart;
  244. const XML_Char *prefix;
  245. int strLen;
  246. int uriLen;
  247. int prefixLen;
  248. } TAG_NAME;
  249. /* TAG represents an open element.
  250. The name of the element is stored in both the document and API
  251. encodings. The memory buffer 'buf' is a separately-allocated
  252. memory area which stores the name. During the XML_Parse()/
  253. XML_ParseBuffer() when the element is open, the memory for the 'raw'
  254. version of the name (in the document encoding) is shared with the
  255. document buffer. If the element is open across calls to
  256. XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to
  257. contain the 'raw' name as well.
  258. A parser reuses these structures, maintaining a list of allocated
  259. TAG objects in a free list.
  260. */
  261. typedef struct tag {
  262. struct tag *parent; /* parent of this element */
  263. const char *rawName; /* tagName in the original encoding */
  264. int rawNameLength;
  265. TAG_NAME name; /* tagName in the API encoding */
  266. char *buf; /* buffer for name components */
  267. char *bufEnd; /* end of the buffer */
  268. BINDING *bindings;
  269. } TAG;
  270. typedef struct {
  271. const XML_Char *name;
  272. const XML_Char *textPtr;
  273. int textLen; /* length in XML_Chars */
  274. int processed; /* # of processed bytes - when suspended */
  275. const XML_Char *systemId;
  276. const XML_Char *base;
  277. const XML_Char *publicId;
  278. const XML_Char *notation;
  279. XML_Bool open;
  280. XML_Bool is_param;
  281. XML_Bool is_internal; /* true if declared in internal subset outside PE */
  282. } ENTITY;
  283. typedef struct {
  284. enum XML_Content_Type type;
  285. enum XML_Content_Quant quant;
  286. const XML_Char *name;
  287. int firstchild;
  288. int lastchild;
  289. int childcnt;
  290. int nextsib;
  291. } CONTENT_SCAFFOLD;
  292. #define INIT_SCAFFOLD_ELEMENTS 32
  293. typedef struct block {
  294. struct block *next;
  295. int size;
  296. XML_Char s[1];
  297. } BLOCK;
  298. typedef struct {
  299. BLOCK *blocks;
  300. BLOCK *freeBlocks;
  301. const XML_Char *end;
  302. XML_Char *ptr;
  303. XML_Char *start;
  304. const XML_Memory_Handling_Suite *mem;
  305. } STRING_POOL;
  306. /* The XML_Char before the name is used to determine whether
  307. an attribute has been specified. */
  308. typedef struct attribute_id {
  309. XML_Char *name;
  310. PREFIX *prefix;
  311. XML_Bool maybeTokenized;
  312. XML_Bool xmlns;
  313. } ATTRIBUTE_ID;
  314. typedef struct {
  315. const ATTRIBUTE_ID *id;
  316. XML_Bool isCdata;
  317. const XML_Char *value;
  318. } DEFAULT_ATTRIBUTE;
  319. typedef struct {
  320. unsigned long version;
  321. unsigned long hash;
  322. const XML_Char *uriName;
  323. } NS_ATT;
  324. typedef struct {
  325. const XML_Char *name;
  326. PREFIX *prefix;
  327. const ATTRIBUTE_ID *idAtt;
  328. int nDefaultAtts;
  329. int allocDefaultAtts;
  330. DEFAULT_ATTRIBUTE *defaultAtts;
  331. } ELEMENT_TYPE;
  332. typedef struct {
  333. HASH_TABLE generalEntities;
  334. HASH_TABLE elementTypes;
  335. HASH_TABLE attributeIds;
  336. HASH_TABLE prefixes;
  337. STRING_POOL pool;
  338. STRING_POOL entityValuePool;
  339. /* false once a parameter entity reference has been skipped */
  340. XML_Bool keepProcessing;
  341. /* true once an internal or external PE reference has been encountered;
  342. this includes the reference to an external subset */
  343. XML_Bool hasParamEntityRefs;
  344. XML_Bool standalone;
  345. #ifdef XML_DTD
  346. /* indicates if external PE has been read */
  347. XML_Bool paramEntityRead;
  348. HASH_TABLE paramEntities;
  349. #endif /* XML_DTD */
  350. PREFIX defaultPrefix;
  351. /* === scaffolding for building content model === */
  352. XML_Bool in_eldecl;
  353. CONTENT_SCAFFOLD *scaffold;
  354. unsigned contentStringLen;
  355. unsigned scaffSize;
  356. unsigned scaffCount;
  357. int scaffLevel;
  358. int *scaffIndex;
  359. } DTD;
  360. typedef struct open_internal_entity {
  361. const char *internalEventPtr;
  362. const char *internalEventEndPtr;
  363. struct open_internal_entity *next;
  364. ENTITY *entity;
  365. int startTagLevel;
  366. XML_Bool betweenDecl; /* WFC: PE Between Declarations */
  367. } OPEN_INTERNAL_ENTITY;
  368. enum XML_Account {
  369. XML_ACCOUNT_DIRECT, /* bytes directly passed to the Expat parser */
  370. XML_ACCOUNT_ENTITY_EXPANSION, /* intermediate bytes produced during entity
  371. expansion */
  372. XML_ACCOUNT_NONE /* i.e. do not account, was accounted already */
  373. };
  374. #if XML_GE == 1
  375. typedef unsigned long long XmlBigCount;
  376. typedef struct accounting {
  377. XmlBigCount countBytesDirect;
  378. XmlBigCount countBytesIndirect;
  379. unsigned long debugLevel;
  380. float maximumAmplificationFactor; // >=1.0
  381. unsigned long long activationThresholdBytes;
  382. } ACCOUNTING;
  383. typedef struct entity_stats {
  384. unsigned int countEverOpened;
  385. unsigned int currentDepth;
  386. unsigned int maximumDepthSeen;
  387. unsigned long debugLevel;
  388. } ENTITY_STATS;
  389. #endif /* XML_GE == 1 */
  390. typedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,
  391. const char *end, const char **endPtr);
  392. static Processor prologProcessor;
  393. static Processor prologInitProcessor;
  394. static Processor contentProcessor;
  395. static Processor cdataSectionProcessor;
  396. #ifdef XML_DTD
  397. static Processor ignoreSectionProcessor;
  398. static Processor externalParEntProcessor;
  399. static Processor externalParEntInitProcessor;
  400. static Processor entityValueProcessor;
  401. static Processor entityValueInitProcessor;
  402. #endif /* XML_DTD */
  403. static Processor epilogProcessor;
  404. static Processor errorProcessor;
  405. static Processor externalEntityInitProcessor;
  406. static Processor externalEntityInitProcessor2;
  407. static Processor externalEntityInitProcessor3;
  408. static Processor externalEntityContentProcessor;
  409. static Processor internalEntityProcessor;
  410. static enum XML_Error handleUnknownEncoding(XML_Parser parser,
  411. const XML_Char *encodingName);
  412. static enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
  413. const char *s, const char *next);
  414. static enum XML_Error initializeEncoding(XML_Parser parser);
  415. static enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,
  416. const char *s, const char *end, int tok,
  417. const char *next, const char **nextPtr,
  418. XML_Bool haveMore, XML_Bool allowClosingDoctype,
  419. enum XML_Account account);
  420. static enum XML_Error processInternalEntity(XML_Parser parser, ENTITY *entity,
  421. XML_Bool betweenDecl);
  422. static enum XML_Error doContent(XML_Parser parser, int startTagLevel,
  423. const ENCODING *enc, const char *start,
  424. const char *end, const char **endPtr,
  425. XML_Bool haveMore, enum XML_Account account);
  426. static enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *enc,
  427. const char **startPtr, const char *end,
  428. const char **nextPtr, XML_Bool haveMore,
  429. enum XML_Account account);
  430. #ifdef XML_DTD
  431. static enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *enc,
  432. const char **startPtr, const char *end,
  433. const char **nextPtr, XML_Bool haveMore);
  434. #endif /* XML_DTD */
  435. static void freeBindings(XML_Parser parser, BINDING *bindings);
  436. static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *enc,
  437. const char *attStr, TAG_NAME *tagNamePtr,
  438. BINDING **bindingsPtr,
  439. enum XML_Account account);
  440. static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,
  441. const ATTRIBUTE_ID *attId, const XML_Char *uri,
  442. BINDING **bindingsPtr);
  443. static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId,
  444. XML_Bool isCdata, XML_Bool isId,
  445. const XML_Char *value, XML_Parser parser);
  446. static enum XML_Error storeAttributeValue(XML_Parser parser,
  447. const ENCODING *enc, XML_Bool isCdata,
  448. const char *ptr, const char *end,
  449. STRING_POOL *pool,
  450. enum XML_Account account);
  451. static enum XML_Error appendAttributeValue(XML_Parser parser,
  452. const ENCODING *enc,
  453. XML_Bool isCdata, const char *ptr,
  454. const char *end, STRING_POOL *pool,
  455. enum XML_Account account);
  456. static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,
  457. const char *start, const char *end);
  458. static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType);
  459. #if XML_GE == 1
  460. static enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,
  461. const char *start, const char *end,
  462. enum XML_Account account);
  463. #else
  464. static enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity);
  465. #endif
  466. static int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
  467. const char *start, const char *end);
  468. static int reportComment(XML_Parser parser, const ENCODING *enc,
  469. const char *start, const char *end);
  470. static void reportDefault(XML_Parser parser, const ENCODING *enc,
  471. const char *start, const char *end);
  472. static const XML_Char *getContext(XML_Parser parser);
  473. static XML_Bool setContext(XML_Parser parser, const XML_Char *context);
  474. static void FASTCALL normalizePublicId(XML_Char *s);
  475. static DTD *dtdCreate(const XML_Memory_Handling_Suite *ms);
  476. /* do not call if m_parentParser != NULL */
  477. static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
  478. static void dtdDestroy(DTD *p, XML_Bool isDocEntity,
  479. const XML_Memory_Handling_Suite *ms);
  480. static int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
  481. const XML_Memory_Handling_Suite *ms);
  482. static int copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
  483. STRING_POOL *newPool, const HASH_TABLE *oldTable);
  484. static NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,
  485. size_t createSize);
  486. static void FASTCALL hashTableInit(HASH_TABLE *table,
  487. const XML_Memory_Handling_Suite *ms);
  488. static void FASTCALL hashTableClear(HASH_TABLE *table);
  489. static void FASTCALL hashTableDestroy(HASH_TABLE *table);
  490. static void FASTCALL hashTableIterInit(HASH_TABLE_ITER *iter,
  491. const HASH_TABLE *table);
  492. static NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *iter);
  493. static void FASTCALL poolInit(STRING_POOL *pool,
  494. const XML_Memory_Handling_Suite *ms);
  495. static void FASTCALL poolClear(STRING_POOL *pool);
  496. static void FASTCALL poolDestroy(STRING_POOL *pool);
  497. static XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,
  498. const char *ptr, const char *end);
  499. static XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,
  500. const char *ptr, const char *end);
  501. static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
  502. static const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,
  503. const XML_Char *s);
  504. static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,
  505. int n);
  506. static const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,
  507. const XML_Char *s);
  508. static int FASTCALL nextScaffoldPart(XML_Parser parser);
  509. static XML_Content *build_model(XML_Parser parser);
  510. static ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,
  511. const char *ptr, const char *end);
  512. static XML_Char *copyString(const XML_Char *s,
  513. const XML_Memory_Handling_Suite *memsuite);
  514. static unsigned long generate_hash_secret_salt(XML_Parser parser);
  515. static XML_Bool startParsing(XML_Parser parser);
  516. static XML_Parser parserCreate(const XML_Char *encodingName,
  517. const XML_Memory_Handling_Suite *memsuite,
  518. const XML_Char *nameSep, DTD *dtd);
  519. static void parserInit(XML_Parser parser, const XML_Char *encodingName);
  520. #if XML_GE == 1
  521. static float accountingGetCurrentAmplification(XML_Parser rootParser);
  522. static void accountingReportStats(XML_Parser originParser, const char *epilog);
  523. static void accountingOnAbort(XML_Parser originParser);
  524. static void accountingReportDiff(XML_Parser rootParser,
  525. unsigned int levelsAwayFromRootParser,
  526. const char *before, const char *after,
  527. ptrdiff_t bytesMore, int source_line,
  528. enum XML_Account account);
  529. static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok,
  530. const char *before, const char *after,
  531. int source_line,
  532. enum XML_Account account);
  533. static void entityTrackingReportStats(XML_Parser parser, ENTITY *entity,
  534. const char *action, int sourceLine);
  535. static void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity,
  536. int sourceLine);
  537. static void entityTrackingOnClose(XML_Parser parser, ENTITY *entity,
  538. int sourceLine);
  539. static XML_Parser getRootParserOf(XML_Parser parser,
  540. unsigned int *outLevelDiff);
  541. #endif /* XML_GE == 1 */
  542. static unsigned long getDebugLevel(const char *variableName,
  543. unsigned long defaultDebugLevel);
  544. #define poolStart(pool) ((pool)->start)
  545. #define poolLength(pool) ((pool)->ptr - (pool)->start)
  546. #define poolChop(pool) ((void)--(pool->ptr))
  547. #define poolLastChar(pool) (((pool)->ptr)[-1])
  548. #define poolDiscard(pool) ((pool)->ptr = (pool)->start)
  549. #define poolFinish(pool) ((pool)->start = (pool)->ptr)
  550. #define poolAppendChar(pool, c) \
  551. (((pool)->ptr == (pool)->end && ! poolGrow(pool)) \
  552. ? 0 \
  553. : ((*((pool)->ptr)++ = c), 1))
  554. #if ! defined(XML_TESTING)
  555. const
  556. #endif
  557. XML_Bool g_reparseDeferralEnabledDefault
  558. = XML_TRUE; // write ONLY in runtests.c
  559. #if defined(XML_TESTING)
  560. unsigned int g_bytesScanned = 0; // used for testing only
  561. #endif
  562. struct XML_ParserStruct {
  563. /* The first member must be m_userData so that the XML_GetUserData
  564. macro works. */
  565. void *m_userData;
  566. void *m_handlerArg;
  567. // How the four parse buffer pointers below relate in time and space:
  568. //
  569. // m_buffer <= m_bufferPtr <= m_bufferEnd <= m_bufferLim
  570. // | | | |
  571. // <--parsed-->| | |
  572. // <---parsing--->| |
  573. // <--unoccupied-->|
  574. // <---------total-malloced/realloced-------->|
  575. char *m_buffer; // malloc/realloc base pointer of parse buffer
  576. const XML_Memory_Handling_Suite m_mem;
  577. const char *m_bufferPtr; // first character to be parsed
  578. char *m_bufferEnd; // past last character to be parsed
  579. const char *m_bufferLim; // allocated end of m_buffer
  580. XML_Index m_parseEndByteIndex;
  581. const char *m_parseEndPtr;
  582. size_t m_partialTokenBytesBefore; /* used in heuristic to avoid O(n^2) */
  583. XML_Bool m_reparseDeferralEnabled;
  584. int m_lastBufferRequestSize;
  585. XML_Char *m_dataBuf;
  586. XML_Char *m_dataBufEnd;
  587. XML_StartElementHandler m_startElementHandler;
  588. XML_EndElementHandler m_endElementHandler;
  589. XML_CharacterDataHandler m_characterDataHandler;
  590. XML_ProcessingInstructionHandler m_processingInstructionHandler;
  591. XML_CommentHandler m_commentHandler;
  592. XML_StartCdataSectionHandler m_startCdataSectionHandler;
  593. XML_EndCdataSectionHandler m_endCdataSectionHandler;
  594. XML_DefaultHandler m_defaultHandler;
  595. XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
  596. XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
  597. XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
  598. XML_NotationDeclHandler m_notationDeclHandler;
  599. XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
  600. XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
  601. XML_NotStandaloneHandler m_notStandaloneHandler;
  602. XML_ExternalEntityRefHandler m_externalEntityRefHandler;
  603. XML_Parser m_externalEntityRefHandlerArg;
  604. XML_SkippedEntityHandler m_skippedEntityHandler;
  605. XML_UnknownEncodingHandler m_unknownEncodingHandler;
  606. XML_ElementDeclHandler m_elementDeclHandler;
  607. XML_AttlistDeclHandler m_attlistDeclHandler;
  608. XML_EntityDeclHandler m_entityDeclHandler;
  609. XML_XmlDeclHandler m_xmlDeclHandler;
  610. const ENCODING *m_encoding;
  611. INIT_ENCODING m_initEncoding;
  612. const ENCODING *m_internalEncoding;
  613. const XML_Char *m_protocolEncodingName;
  614. XML_Bool m_ns;
  615. XML_Bool m_ns_triplets;
  616. void *m_unknownEncodingMem;
  617. void *m_unknownEncodingData;
  618. void *m_unknownEncodingHandlerData;
  619. void(XMLCALL *m_unknownEncodingRelease)(void *);
  620. PROLOG_STATE m_prologState;
  621. Processor *m_processor;
  622. enum XML_Error m_errorCode;
  623. const char *m_eventPtr;
  624. const char *m_eventEndPtr;
  625. const char *m_positionPtr;
  626. OPEN_INTERNAL_ENTITY *m_openInternalEntities;
  627. OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
  628. XML_Bool m_defaultExpandInternalEntities;
  629. int m_tagLevel;
  630. ENTITY *m_declEntity;
  631. const XML_Char *m_doctypeName;
  632. const XML_Char *m_doctypeSysid;
  633. const XML_Char *m_doctypePubid;
  634. const XML_Char *m_declAttributeType;
  635. const XML_Char *m_declNotationName;
  636. const XML_Char *m_declNotationPublicId;
  637. ELEMENT_TYPE *m_declElementType;
  638. ATTRIBUTE_ID *m_declAttributeId;
  639. XML_Bool m_declAttributeIsCdata;
  640. XML_Bool m_declAttributeIsId;
  641. DTD *m_dtd;
  642. const XML_Char *m_curBase;
  643. TAG *m_tagStack;
  644. TAG *m_freeTagList;
  645. BINDING *m_inheritedBindings;
  646. BINDING *m_freeBindingList;
  647. int m_attsSize;
  648. int m_nSpecifiedAtts;
  649. int m_idAttIndex;
  650. ATTRIBUTE *m_atts;
  651. NS_ATT *m_nsAtts;
  652. unsigned long m_nsAttsVersion;
  653. unsigned char m_nsAttsPower;
  654. #ifdef XML_ATTR_INFO
  655. XML_AttrInfo *m_attInfo;
  656. #endif
  657. POSITION m_position;
  658. STRING_POOL m_tempPool;
  659. STRING_POOL m_temp2Pool;
  660. char *m_groupConnector;
  661. unsigned int m_groupSize;
  662. XML_Char m_namespaceSeparator;
  663. XML_Parser m_parentParser;
  664. XML_ParsingStatus m_parsingStatus;
  665. #ifdef XML_DTD
  666. XML_Bool m_isParamEntity;
  667. XML_Bool m_useForeignDTD;
  668. enum XML_ParamEntityParsing m_paramEntityParsing;
  669. #endif
  670. unsigned long m_hash_secret_salt;
  671. #if XML_GE == 1
  672. ACCOUNTING m_accounting;
  673. ENTITY_STATS m_entity_stats;
  674. #endif
  675. };
  676. #define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
  677. #define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))
  678. #define FREE(parser, p) (parser->m_mem.free_fcn((p)))
  679. XML_Parser XMLCALL
  680. XML_ParserCreate(const XML_Char *encodingName) {
  681. return XML_ParserCreate_MM(encodingName, NULL, NULL);
  682. }
  683. XML_Parser XMLCALL
  684. XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {
  685. // WINSCP
  686. XML_Char tmp[2];
  687. tmp[0] = nsSep;
  688. tmp[1] = 0;
  689. return XML_ParserCreate_MM(encodingName, NULL, tmp);
  690. }
  691. // "xml=http://www.w3.org/XML/1998/namespace"
  692. static const XML_Char implicitContext[]
  693. = {ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h,
  694. ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
  695. ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD,
  696. ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r,
  697. ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,
  698. ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8,
  699. ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,
  700. ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e,
  701. '\0'};
  702. /* To avoid warnings about unused functions: */
  703. #if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
  704. # if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
  705. /* Obtain entropy on Linux 3.17+ */
  706. static int
  707. writeRandomBytes_getrandom_nonblock(void *target, size_t count) {
  708. int success = 0; /* full count bytes written? */
  709. size_t bytesWrittenTotal = 0;
  710. const unsigned int getrandomFlags = GRND_NONBLOCK;
  711. do {
  712. void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
  713. const size_t bytesToWrite = count - bytesWrittenTotal;
  714. const int bytesWrittenMore =
  715. # if defined(HAVE_GETRANDOM)
  716. getrandom(currentTarget, bytesToWrite, getrandomFlags);
  717. # else
  718. syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
  719. # endif
  720. if (bytesWrittenMore > 0) {
  721. bytesWrittenTotal += bytesWrittenMore;
  722. if (bytesWrittenTotal >= count)
  723. success = 1;
  724. }
  725. } while (! success && (errno == EINTR));
  726. return success;
  727. }
  728. # endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
  729. # if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
  730. /* Extract entropy from /dev/urandom */
  731. static int
  732. writeRandomBytes_dev_urandom(void *target, size_t count) {
  733. int success = 0; /* full count bytes written? */
  734. size_t bytesWrittenTotal = 0;
  735. const int fd = open("/dev/urandom", O_RDONLY);
  736. if (fd < 0) {
  737. return 0;
  738. }
  739. do {
  740. void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
  741. const size_t bytesToWrite = count - bytesWrittenTotal;
  742. const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
  743. if (bytesWrittenMore > 0) {
  744. bytesWrittenTotal += bytesWrittenMore;
  745. if (bytesWrittenTotal >= count)
  746. success = 1;
  747. }
  748. } while (! success && (errno == EINTR));
  749. close(fd);
  750. return success;
  751. }
  752. # endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
  753. #endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
  754. #if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
  755. static void
  756. writeRandomBytes_arc4random(void *target, size_t count) {
  757. size_t bytesWrittenTotal = 0;
  758. while (bytesWrittenTotal < count) {
  759. const uint32_t random32 = arc4random();
  760. size_t i = 0;
  761. for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
  762. i++, bytesWrittenTotal++) {
  763. const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
  764. ((uint8_t *)target)[bytesWrittenTotal] = random8;
  765. }
  766. }
  767. }
  768. #endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
  769. #ifdef _WIN32
  770. // WINSCP - See writeRandomBytes_rand_s
  771. typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG);
  772. HMODULE _Expat_LoadLibrary(LPCTSTR filename); /* see loadlibrary.c */
  773. /* Provide declaration of rand_s() for MinGW-32 (not 64, which has it),
  774. as it didn't declare it in its header prior to version 5.3.0 of its
  775. runtime package (mingwrt, containing stdlib.h). The upstream fix
  776. was introduced at https://osdn.net/projects/mingw/ticket/39658 . */
  777. # if defined(__MINGW32__) && defined(__MINGW32_VERSION) \
  778. && __MINGW32_VERSION < 5003000L && ! defined(__MINGW64_VERSION_MAJOR)
  779. __declspec(dllimport) int rand_s(unsigned int *);
  780. # endif
  781. /* Obtain entropy on Windows using the rand_s() function which
  782. * generates cryptographically secure random numbers. Internally it
  783. * uses RtlGenRandom API which is present in Windows XP and later.
  784. */
  785. static int
  786. writeRandomBytes_rand_s(void *target, size_t count) {
  787. // WINSCP, we do not have rand_s in C++Builder
  788. int success = 0; /* full count bytes written? */
  789. const HMODULE advapi32 = _Expat_LoadLibrary(TEXT("ADVAPI32.DLL"));
  790. if (advapi32) {
  791. const RTLGENRANDOM_FUNC RtlGenRandom
  792. = (RTLGENRANDOM_FUNC)GetProcAddress(advapi32, "SystemFunction036");
  793. if (RtlGenRandom) {
  794. if (RtlGenRandom((PVOID)target, (ULONG)count) == TRUE) {
  795. success = 1;
  796. }
  797. }
  798. FreeLibrary(advapi32);
  799. }
  800. return success;
  801. }
  802. #endif /* _WIN32 */
  803. #if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
  804. static unsigned long
  805. gather_time_entropy(void) {
  806. # ifdef _WIN32
  807. FILETIME ft;
  808. GetSystemTimeAsFileTime(&ft); /* never fails */
  809. return ft.dwHighDateTime ^ ft.dwLowDateTime;
  810. # else
  811. struct timeval tv;
  812. int gettimeofday_res;
  813. gettimeofday_res = gettimeofday(&tv, NULL);
  814. # if defined(NDEBUG)
  815. (void)gettimeofday_res;
  816. # else
  817. assert(gettimeofday_res == 0);
  818. # endif /* defined(NDEBUG) */
  819. /* Microseconds time is <20 bits entropy */
  820. return tv.tv_usec;
  821. # endif
  822. }
  823. #endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
  824. static unsigned long
  825. ENTROPY_DEBUG(const char *label, unsigned long entropy) {
  826. if (getDebugLevel("EXPAT_ENTROPY_DEBUG", 0) >= 1u) {
  827. fprintf(stderr, "expat: Entropy: %s --> 0x%0*lx (%lu bytes)\n", label,
  828. (int)sizeof(entropy) * 2, entropy, (unsigned long)sizeof(entropy));
  829. }
  830. return entropy;
  831. }
  832. static unsigned long
  833. generate_hash_secret_salt(XML_Parser parser) {
  834. unsigned long entropy;
  835. (void)parser;
  836. /* "Failproof" high quality providers: */
  837. #if defined(HAVE_ARC4RANDOM_BUF)
  838. arc4random_buf(&entropy, sizeof(entropy));
  839. return ENTROPY_DEBUG("arc4random_buf", entropy);
  840. #elif defined(HAVE_ARC4RANDOM)
  841. writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
  842. return ENTROPY_DEBUG("arc4random", entropy);
  843. #else
  844. /* Try high quality providers first .. */
  845. # ifdef _WIN32
  846. if (writeRandomBytes_rand_s((void *)&entropy, sizeof(entropy))) {
  847. return ENTROPY_DEBUG("rand_s", entropy);
  848. }
  849. # elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
  850. if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
  851. return ENTROPY_DEBUG("getrandom", entropy);
  852. }
  853. # endif
  854. # if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
  855. if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
  856. return ENTROPY_DEBUG("/dev/urandom", entropy);
  857. }
  858. # endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
  859. /* .. and self-made low quality for backup: */
  860. /* Process ID is 0 bits entropy if attacker has local access */
  861. entropy = gather_time_entropy() ^ getpid();
  862. /* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
  863. if (sizeof(unsigned long) == 4) {
  864. return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
  865. } else {
  866. return ENTROPY_DEBUG("fallback(8)",
  867. entropy * (unsigned long)2305843009213693951ULL);
  868. }
  869. #endif
  870. }
  871. static unsigned long
  872. get_hash_secret_salt(XML_Parser parser) {
  873. if (parser->m_parentParser != NULL)
  874. return get_hash_secret_salt(parser->m_parentParser);
  875. return parser->m_hash_secret_salt;
  876. }
  877. static enum XML_Error
  878. callProcessor(XML_Parser parser, const char *start, const char *end,
  879. const char **endPtr) {
  880. const size_t have_now = EXPAT_SAFE_PTR_DIFF(end, start);
  881. if (parser->m_reparseDeferralEnabled
  882. && ! parser->m_parsingStatus.finalBuffer) {
  883. // Heuristic: don't try to parse a partial token again until the amount of
  884. // available data has increased significantly.
  885. const size_t had_before = parser->m_partialTokenBytesBefore;
  886. // ...but *do* try anyway if we're close to causing a reallocation.
  887. size_t available_buffer
  888. = EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
  889. #if XML_CONTEXT_BYTES > 0
  890. available_buffer -= EXPAT_MIN(available_buffer, XML_CONTEXT_BYTES);
  891. #endif
  892. available_buffer
  893. += EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd);
  894. // m_lastBufferRequestSize is never assigned a value < 0, so the cast is ok
  895. { // WINSCP
  896. const bool enough
  897. = (have_now >= 2 * had_before)
  898. || ((size_t)parser->m_lastBufferRequestSize > available_buffer);
  899. if (! enough) {
  900. *endPtr = start; // callers may expect this to be set
  901. return XML_ERROR_NONE;
  902. }
  903. } // WINSCP
  904. }
  905. #if defined(XML_TESTING)
  906. g_bytesScanned += (unsigned)have_now;
  907. #endif
  908. { // WINSCP
  909. const enum XML_Error ret = parser->m_processor(parser, start, end, endPtr);
  910. if (ret == XML_ERROR_NONE) {
  911. // if we consumed nothing, remember what we had on this parse attempt.
  912. if (*endPtr == start) {
  913. parser->m_partialTokenBytesBefore = have_now;
  914. } else {
  915. parser->m_partialTokenBytesBefore = 0;
  916. }
  917. }
  918. return ret;
  919. } // WINSCP
  920. }
  921. static XML_Bool /* only valid for root parser */
  922. startParsing(XML_Parser parser) {
  923. /* hash functions must be initialized before setContext() is called */
  924. if (parser->m_hash_secret_salt == 0)
  925. parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
  926. if (parser->m_ns) {
  927. /* implicit context only set for root parser, since child
  928. parsers (i.e. external entity parsers) will inherit it
  929. */
  930. return setContext(parser, implicitContext);
  931. }
  932. return XML_TRUE;
  933. }
  934. XML_Parser XMLCALL
  935. XML_ParserCreate_MM(const XML_Char *encodingName,
  936. const XML_Memory_Handling_Suite *memsuite,
  937. const XML_Char *nameSep) {
  938. return parserCreate(encodingName, memsuite, nameSep, NULL);
  939. }
  940. static XML_Parser
  941. parserCreate(const XML_Char *encodingName,
  942. const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,
  943. DTD *dtd) {
  944. XML_Parser parser;
  945. if (memsuite) {
  946. XML_Memory_Handling_Suite *mtemp;
  947. parser = memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
  948. if (parser != NULL) {
  949. mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
  950. mtemp->malloc_fcn = memsuite->malloc_fcn;
  951. mtemp->realloc_fcn = memsuite->realloc_fcn;
  952. mtemp->free_fcn = memsuite->free_fcn;
  953. }
  954. } else {
  955. XML_Memory_Handling_Suite *mtemp;
  956. parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
  957. if (parser != NULL) {
  958. mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
  959. mtemp->malloc_fcn = malloc;
  960. mtemp->realloc_fcn = realloc;
  961. mtemp->free_fcn = free;
  962. }
  963. }
  964. if (! parser)
  965. return parser;
  966. parser->m_buffer = NULL;
  967. parser->m_bufferLim = NULL;
  968. parser->m_attsSize = INIT_ATTS_SIZE;
  969. parser->m_atts
  970. = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
  971. if (parser->m_atts == NULL) {
  972. FREE(parser, parser);
  973. return NULL;
  974. }
  975. #ifdef XML_ATTR_INFO
  976. parser->m_attInfo = (XML_AttrInfo *)MALLOC(
  977. parser, parser->m_attsSize * sizeof(XML_AttrInfo));
  978. if (parser->m_attInfo == NULL) {
  979. FREE(parser, parser->m_atts);
  980. FREE(parser, parser);
  981. return NULL;
  982. }
  983. #endif
  984. parser->m_dataBuf
  985. = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
  986. if (parser->m_dataBuf == NULL) {
  987. FREE(parser, parser->m_atts);
  988. #ifdef XML_ATTR_INFO
  989. FREE(parser, parser->m_attInfo);
  990. #endif
  991. FREE(parser, parser);
  992. return NULL;
  993. }
  994. parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
  995. if (dtd)
  996. parser->m_dtd = dtd;
  997. else {
  998. parser->m_dtd = dtdCreate(&parser->m_mem);
  999. if (parser->m_dtd == NULL) {
  1000. FREE(parser, parser->m_dataBuf);
  1001. FREE(parser, parser->m_atts);
  1002. #ifdef XML_ATTR_INFO
  1003. FREE(parser, parser->m_attInfo);
  1004. #endif
  1005. FREE(parser, parser);
  1006. return NULL;
  1007. }
  1008. }
  1009. parser->m_freeBindingList = NULL;
  1010. parser->m_freeTagList = NULL;
  1011. parser->m_freeInternalEntities = NULL;
  1012. parser->m_groupSize = 0;
  1013. parser->m_groupConnector = NULL;
  1014. parser->m_unknownEncodingHandler = NULL;
  1015. parser->m_unknownEncodingHandlerData = NULL;
  1016. parser->m_namespaceSeparator = ASCII_EXCL;
  1017. parser->m_ns = XML_FALSE;
  1018. parser->m_ns_triplets = XML_FALSE;
  1019. parser->m_nsAtts = NULL;
  1020. parser->m_nsAttsVersion = 0;
  1021. parser->m_nsAttsPower = 0;
  1022. parser->m_protocolEncodingName = NULL;
  1023. poolInit(&parser->m_tempPool, &(parser->m_mem));
  1024. poolInit(&parser->m_temp2Pool, &(parser->m_mem));
  1025. parserInit(parser, encodingName);
  1026. if (encodingName && ! parser->m_protocolEncodingName) {
  1027. if (dtd) {
  1028. // We need to stop the upcoming call to XML_ParserFree from happily
  1029. // destroying parser->m_dtd because the DTD is shared with the parent
  1030. // parser and the only guard that keeps XML_ParserFree from destroying
  1031. // parser->m_dtd is parser->m_isParamEntity but it will be set to
  1032. // XML_TRUE only later in XML_ExternalEntityParserCreate (or not at all).
  1033. parser->m_dtd = NULL;
  1034. }
  1035. XML_ParserFree(parser);
  1036. return NULL;
  1037. }
  1038. if (nameSep) {
  1039. parser->m_ns = XML_TRUE;
  1040. parser->m_internalEncoding = XmlGetInternalEncodingNS();
  1041. parser->m_namespaceSeparator = *nameSep;
  1042. } else {
  1043. parser->m_internalEncoding = XmlGetInternalEncoding();
  1044. }
  1045. return parser;
  1046. }
  1047. static void
  1048. parserInit(XML_Parser parser, const XML_Char *encodingName) {
  1049. parser->m_processor = prologInitProcessor;
  1050. XmlPrologStateInit(&parser->m_prologState);
  1051. if (encodingName != NULL) {
  1052. parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
  1053. }
  1054. parser->m_curBase = NULL;
  1055. XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
  1056. parser->m_userData = NULL;
  1057. parser->m_handlerArg = NULL;
  1058. parser->m_startElementHandler = NULL;
  1059. parser->m_endElementHandler = NULL;
  1060. parser->m_characterDataHandler = NULL;
  1061. parser->m_processingInstructionHandler = NULL;
  1062. parser->m_commentHandler = NULL;
  1063. parser->m_startCdataSectionHandler = NULL;
  1064. parser->m_endCdataSectionHandler = NULL;
  1065. parser->m_defaultHandler = NULL;
  1066. parser->m_startDoctypeDeclHandler = NULL;
  1067. parser->m_endDoctypeDeclHandler = NULL;
  1068. parser->m_unparsedEntityDeclHandler = NULL;
  1069. parser->m_notationDeclHandler = NULL;
  1070. parser->m_startNamespaceDeclHandler = NULL;
  1071. parser->m_endNamespaceDeclHandler = NULL;
  1072. parser->m_notStandaloneHandler = NULL;
  1073. parser->m_externalEntityRefHandler = NULL;
  1074. parser->m_externalEntityRefHandlerArg = parser;
  1075. parser->m_skippedEntityHandler = NULL;
  1076. parser->m_elementDeclHandler = NULL;
  1077. parser->m_attlistDeclHandler = NULL;
  1078. parser->m_entityDeclHandler = NULL;
  1079. parser->m_xmlDeclHandler = NULL;
  1080. parser->m_bufferPtr = parser->m_buffer;
  1081. parser->m_bufferEnd = parser->m_buffer;
  1082. parser->m_parseEndByteIndex = 0;
  1083. parser->m_parseEndPtr = NULL;
  1084. parser->m_partialTokenBytesBefore = 0;
  1085. parser->m_reparseDeferralEnabled = g_reparseDeferralEnabledDefault;
  1086. parser->m_lastBufferRequestSize = 0;
  1087. parser->m_declElementType = NULL;
  1088. parser->m_declAttributeId = NULL;
  1089. parser->m_declEntity = NULL;
  1090. parser->m_doctypeName = NULL;
  1091. parser->m_doctypeSysid = NULL;
  1092. parser->m_doctypePubid = NULL;
  1093. parser->m_declAttributeType = NULL;
  1094. parser->m_declNotationName = NULL;
  1095. parser->m_declNotationPublicId = NULL;
  1096. parser->m_declAttributeIsCdata = XML_FALSE;
  1097. parser->m_declAttributeIsId = XML_FALSE;
  1098. memset(&parser->m_position, 0, sizeof(POSITION));
  1099. parser->m_errorCode = XML_ERROR_NONE;
  1100. parser->m_eventPtr = NULL;
  1101. parser->m_eventEndPtr = NULL;
  1102. parser->m_positionPtr = NULL;
  1103. parser->m_openInternalEntities = NULL;
  1104. parser->m_defaultExpandInternalEntities = XML_TRUE;
  1105. parser->m_tagLevel = 0;
  1106. parser->m_tagStack = NULL;
  1107. parser->m_inheritedBindings = NULL;
  1108. parser->m_nSpecifiedAtts = 0;
  1109. parser->m_unknownEncodingMem = NULL;
  1110. parser->m_unknownEncodingRelease = NULL;
  1111. parser->m_unknownEncodingData = NULL;
  1112. parser->m_parentParser = NULL;
  1113. parser->m_parsingStatus.parsing = XML_INITIALIZED;
  1114. #ifdef XML_DTD
  1115. parser->m_isParamEntity = XML_FALSE;
  1116. parser->m_useForeignDTD = XML_FALSE;
  1117. parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
  1118. #endif
  1119. parser->m_hash_secret_salt = 0;
  1120. #if XML_GE == 1
  1121. memset(&parser->m_accounting, 0, sizeof(ACCOUNTING));
  1122. parser->m_accounting.debugLevel = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u);
  1123. parser->m_accounting.maximumAmplificationFactor
  1124. = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT;
  1125. parser->m_accounting.activationThresholdBytes
  1126. = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT;
  1127. memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS));
  1128. parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u);
  1129. #endif
  1130. }
  1131. /* moves list of bindings to m_freeBindingList */
  1132. static void FASTCALL
  1133. moveToFreeBindingList(XML_Parser parser, BINDING *bindings) {
  1134. while (bindings) {
  1135. BINDING *b = bindings;
  1136. bindings = bindings->nextTagBinding;
  1137. b->nextTagBinding = parser->m_freeBindingList;
  1138. parser->m_freeBindingList = b;
  1139. }
  1140. }
  1141. XML_Bool XMLCALL
  1142. XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
  1143. TAG *tStk;
  1144. OPEN_INTERNAL_ENTITY *openEntityList;
  1145. if (parser == NULL)
  1146. return XML_FALSE;
  1147. if (parser->m_parentParser)
  1148. return XML_FALSE;
  1149. /* move m_tagStack to m_freeTagList */
  1150. tStk = parser->m_tagStack;
  1151. while (tStk) {
  1152. TAG *tag = tStk;
  1153. tStk = tStk->parent;
  1154. tag->parent = parser->m_freeTagList;
  1155. moveToFreeBindingList(parser, tag->bindings);
  1156. tag->bindings = NULL;
  1157. parser->m_freeTagList = tag;
  1158. }
  1159. /* move m_openInternalEntities to m_freeInternalEntities */
  1160. openEntityList = parser->m_openInternalEntities;
  1161. while (openEntityList) {
  1162. OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
  1163. openEntityList = openEntity->next;
  1164. openEntity->next = parser->m_freeInternalEntities;
  1165. parser->m_freeInternalEntities = openEntity;
  1166. }
  1167. moveToFreeBindingList(parser, parser->m_inheritedBindings);
  1168. FREE(parser, parser->m_unknownEncodingMem);
  1169. if (parser->m_unknownEncodingRelease)
  1170. parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
  1171. poolClear(&parser->m_tempPool);
  1172. poolClear(&parser->m_temp2Pool);
  1173. FREE(parser, (void *)parser->m_protocolEncodingName);
  1174. parser->m_protocolEncodingName = NULL;
  1175. parserInit(parser, encodingName);
  1176. dtdReset(parser->m_dtd, &parser->m_mem);
  1177. return XML_TRUE;
  1178. }
  1179. enum XML_Status XMLCALL
  1180. XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {
  1181. if (parser == NULL)
  1182. return XML_STATUS_ERROR;
  1183. /* Block after XML_Parse()/XML_ParseBuffer() has been called.
  1184. XXX There's no way for the caller to determine which of the
  1185. XXX possible error cases caused the XML_STATUS_ERROR return.
  1186. */
  1187. if (parser->m_parsingStatus.parsing == XML_PARSING
  1188. || parser->m_parsingStatus.parsing == XML_SUSPENDED)
  1189. return XML_STATUS_ERROR;
  1190. /* Get rid of any previous encoding name */
  1191. FREE(parser, (void *)parser->m_protocolEncodingName);
  1192. if (encodingName == NULL)
  1193. /* No new encoding name */
  1194. parser->m_protocolEncodingName = NULL;
  1195. else {
  1196. /* Copy the new encoding name into allocated memory */
  1197. parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
  1198. if (! parser->m_protocolEncodingName)
  1199. return XML_STATUS_ERROR;
  1200. }
  1201. return XML_STATUS_OK;
  1202. }
  1203. XML_Parser XMLCALL
  1204. XML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,
  1205. const XML_Char *encodingName) {
  1206. XML_Parser parser = oldParser;
  1207. DTD *newDtd = NULL;
  1208. DTD *oldDtd;
  1209. XML_StartElementHandler oldStartElementHandler;
  1210. XML_EndElementHandler oldEndElementHandler;
  1211. XML_CharacterDataHandler oldCharacterDataHandler;
  1212. XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
  1213. XML_CommentHandler oldCommentHandler;
  1214. XML_StartCdataSectionHandler oldStartCdataSectionHandler;
  1215. XML_EndCdataSectionHandler oldEndCdataSectionHandler;
  1216. XML_DefaultHandler oldDefaultHandler;
  1217. XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
  1218. XML_NotationDeclHandler oldNotationDeclHandler;
  1219. XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
  1220. XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
  1221. XML_NotStandaloneHandler oldNotStandaloneHandler;
  1222. XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
  1223. XML_SkippedEntityHandler oldSkippedEntityHandler;
  1224. XML_UnknownEncodingHandler oldUnknownEncodingHandler;
  1225. XML_ElementDeclHandler oldElementDeclHandler;
  1226. XML_AttlistDeclHandler oldAttlistDeclHandler;
  1227. XML_EntityDeclHandler oldEntityDeclHandler;
  1228. XML_XmlDeclHandler oldXmlDeclHandler;
  1229. ELEMENT_TYPE *oldDeclElementType;
  1230. void *oldUserData;
  1231. void *oldHandlerArg;
  1232. XML_Bool oldDefaultExpandInternalEntities;
  1233. XML_Parser oldExternalEntityRefHandlerArg;
  1234. #ifdef XML_DTD
  1235. enum XML_ParamEntityParsing oldParamEntityParsing;
  1236. int oldInEntityValue;
  1237. #endif
  1238. XML_Bool oldns_triplets;
  1239. /* Note that the new parser shares the same hash secret as the old
  1240. parser, so that dtdCopy and copyEntityTable can lookup values
  1241. from hash tables associated with either parser without us having
  1242. to worry which hash secrets each table has.
  1243. */
  1244. unsigned long oldhash_secret_salt;
  1245. XML_Bool oldReparseDeferralEnabled;
  1246. /* Validate the oldParser parameter before we pull everything out of it */
  1247. if (oldParser == NULL)
  1248. return NULL;
  1249. /* Stash the original parser contents on the stack */
  1250. oldDtd = parser->m_dtd;
  1251. oldStartElementHandler = parser->m_startElementHandler;
  1252. oldEndElementHandler = parser->m_endElementHandler;
  1253. oldCharacterDataHandler = parser->m_characterDataHandler;
  1254. oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
  1255. oldCommentHandler = parser->m_commentHandler;
  1256. oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
  1257. oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
  1258. oldDefaultHandler = parser->m_defaultHandler;
  1259. oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
  1260. oldNotationDeclHandler = parser->m_notationDeclHandler;
  1261. oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
  1262. oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
  1263. oldNotStandaloneHandler = parser->m_notStandaloneHandler;
  1264. oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
  1265. oldSkippedEntityHandler = parser->m_skippedEntityHandler;
  1266. oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
  1267. oldElementDeclHandler = parser->m_elementDeclHandler;
  1268. oldAttlistDeclHandler = parser->m_attlistDeclHandler;
  1269. oldEntityDeclHandler = parser->m_entityDeclHandler;
  1270. oldXmlDeclHandler = parser->m_xmlDeclHandler;
  1271. oldDeclElementType = parser->m_declElementType;
  1272. oldUserData = parser->m_userData;
  1273. oldHandlerArg = parser->m_handlerArg;
  1274. oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
  1275. oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
  1276. #ifdef XML_DTD
  1277. oldParamEntityParsing = parser->m_paramEntityParsing;
  1278. oldInEntityValue = parser->m_prologState.inEntityValue;
  1279. #endif
  1280. oldns_triplets = parser->m_ns_triplets;
  1281. /* Note that the new parser shares the same hash secret as the old
  1282. parser, so that dtdCopy and copyEntityTable can lookup values
  1283. from hash tables associated with either parser without us having
  1284. to worry which hash secrets each table has.
  1285. */
  1286. oldhash_secret_salt = parser->m_hash_secret_salt;
  1287. oldReparseDeferralEnabled = parser->m_reparseDeferralEnabled;
  1288. #ifdef XML_DTD
  1289. if (! context)
  1290. newDtd = oldDtd;
  1291. #endif /* XML_DTD */
  1292. /* Note that the magical uses of the pre-processor to make field
  1293. access look more like C++ require that `parser' be overwritten
  1294. here. This makes this function more painful to follow than it
  1295. would be otherwise.
  1296. */
  1297. if (parser->m_ns) {
  1298. // WINSCP
  1299. XML_Char tmp[2];
  1300. tmp[0] = parser->m_namespaceSeparator;
  1301. tmp[1] = 0;
  1302. parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
  1303. } else {
  1304. parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
  1305. }
  1306. if (! parser)
  1307. return NULL;
  1308. parser->m_startElementHandler = oldStartElementHandler;
  1309. parser->m_endElementHandler = oldEndElementHandler;
  1310. parser->m_characterDataHandler = oldCharacterDataHandler;
  1311. parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
  1312. parser->m_commentHandler = oldCommentHandler;
  1313. parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
  1314. parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
  1315. parser->m_defaultHandler = oldDefaultHandler;
  1316. parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
  1317. parser->m_notationDeclHandler = oldNotationDeclHandler;
  1318. parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
  1319. parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
  1320. parser->m_notStandaloneHandler = oldNotStandaloneHandler;
  1321. parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
  1322. parser->m_skippedEntityHandler = oldSkippedEntityHandler;
  1323. parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
  1324. parser->m_elementDeclHandler = oldElementDeclHandler;
  1325. parser->m_attlistDeclHandler = oldAttlistDeclHandler;
  1326. parser->m_entityDeclHandler = oldEntityDeclHandler;
  1327. parser->m_xmlDeclHandler = oldXmlDeclHandler;
  1328. parser->m_declElementType = oldDeclElementType;
  1329. parser->m_userData = oldUserData;
  1330. if (oldUserData == oldHandlerArg)
  1331. parser->m_handlerArg = parser->m_userData;
  1332. else
  1333. parser->m_handlerArg = parser;
  1334. if (oldExternalEntityRefHandlerArg != oldParser)
  1335. parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
  1336. parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
  1337. parser->m_ns_triplets = oldns_triplets;
  1338. parser->m_hash_secret_salt = oldhash_secret_salt;
  1339. parser->m_reparseDeferralEnabled = oldReparseDeferralEnabled;
  1340. parser->m_parentParser = oldParser;
  1341. #ifdef XML_DTD
  1342. parser->m_paramEntityParsing = oldParamEntityParsing;
  1343. parser->m_prologState.inEntityValue = oldInEntityValue;
  1344. if (context) {
  1345. #endif /* XML_DTD */
  1346. if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
  1347. || ! setContext(parser, context)) {
  1348. XML_ParserFree(parser);
  1349. return NULL;
  1350. }
  1351. parser->m_processor = externalEntityInitProcessor;
  1352. #ifdef XML_DTD
  1353. } else {
  1354. /* The DTD instance referenced by parser->m_dtd is shared between the
  1355. document's root parser and external PE parsers, therefore one does not
  1356. need to call setContext. In addition, one also *must* not call
  1357. setContext, because this would overwrite existing prefix->binding
  1358. pointers in parser->m_dtd with ones that get destroyed with the external
  1359. PE parser. This would leave those prefixes with dangling pointers.
  1360. */
  1361. parser->m_isParamEntity = XML_TRUE;
  1362. XmlPrologStateInitExternalEntity(&parser->m_prologState);
  1363. parser->m_processor = externalParEntInitProcessor;
  1364. }
  1365. #endif /* XML_DTD */
  1366. return parser;
  1367. }
  1368. static void FASTCALL
  1369. destroyBindings(BINDING *bindings, XML_Parser parser) {
  1370. for (;;) {
  1371. BINDING *b = bindings;
  1372. if (! b)
  1373. break;
  1374. bindings = b->nextTagBinding;
  1375. FREE(parser, b->uri);
  1376. FREE(parser, b);
  1377. }
  1378. }
  1379. void XMLCALL
  1380. XML_ParserFree(XML_Parser parser) {
  1381. TAG *tagList;
  1382. OPEN_INTERNAL_ENTITY *entityList;
  1383. if (parser == NULL)
  1384. return;
  1385. /* free m_tagStack and m_freeTagList */
  1386. tagList = parser->m_tagStack;
  1387. for (;;) {
  1388. TAG *p;
  1389. if (tagList == NULL) {
  1390. if (parser->m_freeTagList == NULL)
  1391. break;
  1392. tagList = parser->m_freeTagList;
  1393. parser->m_freeTagList = NULL;
  1394. }
  1395. p = tagList;
  1396. tagList = tagList->parent;
  1397. FREE(parser, p->buf);
  1398. destroyBindings(p->bindings, parser);
  1399. FREE(parser, p);
  1400. }
  1401. /* free m_openInternalEntities and m_freeInternalEntities */
  1402. entityList = parser->m_openInternalEntities;
  1403. for (;;) {
  1404. OPEN_INTERNAL_ENTITY *openEntity;
  1405. if (entityList == NULL) {
  1406. if (parser->m_freeInternalEntities == NULL)
  1407. break;
  1408. entityList = parser->m_freeInternalEntities;
  1409. parser->m_freeInternalEntities = NULL;
  1410. }
  1411. openEntity = entityList;
  1412. entityList = entityList->next;
  1413. FREE(parser, openEntity);
  1414. }
  1415. destroyBindings(parser->m_freeBindingList, parser);
  1416. destroyBindings(parser->m_inheritedBindings, parser);
  1417. poolDestroy(&parser->m_tempPool);
  1418. poolDestroy(&parser->m_temp2Pool);
  1419. FREE(parser, (void *)parser->m_protocolEncodingName);
  1420. #ifdef XML_DTD
  1421. /* external parameter entity parsers share the DTD structure
  1422. parser->m_dtd with the root parser, so we must not destroy it
  1423. */
  1424. if (! parser->m_isParamEntity && parser->m_dtd)
  1425. #else
  1426. if (parser->m_dtd)
  1427. #endif /* XML_DTD */
  1428. dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser,
  1429. &parser->m_mem);
  1430. FREE(parser, (void *)parser->m_atts);
  1431. #ifdef XML_ATTR_INFO
  1432. FREE(parser, (void *)parser->m_attInfo);
  1433. #endif
  1434. FREE(parser, parser->m_groupConnector);
  1435. FREE(parser, parser->m_buffer);
  1436. FREE(parser, parser->m_dataBuf);
  1437. FREE(parser, parser->m_nsAtts);
  1438. FREE(parser, parser->m_unknownEncodingMem);
  1439. if (parser->m_unknownEncodingRelease)
  1440. parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
  1441. FREE(parser, parser);
  1442. }
  1443. void XMLCALL
  1444. XML_UseParserAsHandlerArg(XML_Parser parser) {
  1445. if (parser != NULL)
  1446. parser->m_handlerArg = parser;
  1447. }
  1448. enum XML_Error XMLCALL
  1449. XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {
  1450. if (parser == NULL)
  1451. return XML_ERROR_INVALID_ARGUMENT;
  1452. #ifdef XML_DTD
  1453. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  1454. if (parser->m_parsingStatus.parsing == XML_PARSING
  1455. || parser->m_parsingStatus.parsing == XML_SUSPENDED)
  1456. return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
  1457. parser->m_useForeignDTD = useDTD;
  1458. return XML_ERROR_NONE;
  1459. #else
  1460. UNUSED_P(useDTD);
  1461. return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
  1462. #endif
  1463. }
  1464. void XMLCALL
  1465. XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {
  1466. if (parser == NULL)
  1467. return;
  1468. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  1469. if (parser->m_parsingStatus.parsing == XML_PARSING
  1470. || parser->m_parsingStatus.parsing == XML_SUSPENDED)
  1471. return;
  1472. parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
  1473. }
  1474. void XMLCALL
  1475. XML_SetUserData(XML_Parser parser, void *p) {
  1476. if (parser == NULL)
  1477. return;
  1478. if (parser->m_handlerArg == parser->m_userData)
  1479. parser->m_handlerArg = parser->m_userData = p;
  1480. else
  1481. parser->m_userData = p;
  1482. }
  1483. enum XML_Status XMLCALL
  1484. XML_SetBase(XML_Parser parser, const XML_Char *p) {
  1485. if (parser == NULL)
  1486. return XML_STATUS_ERROR;
  1487. if (p) {
  1488. p = poolCopyString(&parser->m_dtd->pool, p);
  1489. if (! p)
  1490. return XML_STATUS_ERROR;
  1491. parser->m_curBase = p;
  1492. } else
  1493. parser->m_curBase = NULL;
  1494. return XML_STATUS_OK;
  1495. }
  1496. const XML_Char *XMLCALL
  1497. XML_GetBase(XML_Parser parser) {
  1498. if (parser == NULL)
  1499. return NULL;
  1500. return parser->m_curBase;
  1501. }
  1502. int XMLCALL
  1503. XML_GetSpecifiedAttributeCount(XML_Parser parser) {
  1504. if (parser == NULL)
  1505. return -1;
  1506. return parser->m_nSpecifiedAtts;
  1507. }
  1508. int XMLCALL
  1509. XML_GetIdAttributeIndex(XML_Parser parser) {
  1510. if (parser == NULL)
  1511. return -1;
  1512. return parser->m_idAttIndex;
  1513. }
  1514. #ifdef XML_ATTR_INFO
  1515. const XML_AttrInfo *XMLCALL
  1516. XML_GetAttributeInfo(XML_Parser parser) {
  1517. if (parser == NULL)
  1518. return NULL;
  1519. return parser->m_attInfo;
  1520. }
  1521. #endif
  1522. void XMLCALL
  1523. XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
  1524. XML_EndElementHandler end) {
  1525. if (parser == NULL)
  1526. return;
  1527. parser->m_startElementHandler = start;
  1528. parser->m_endElementHandler = end;
  1529. }
  1530. void XMLCALL
  1531. XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {
  1532. if (parser != NULL)
  1533. parser->m_startElementHandler = start;
  1534. }
  1535. void XMLCALL
  1536. XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {
  1537. if (parser != NULL)
  1538. parser->m_endElementHandler = end;
  1539. }
  1540. void XMLCALL
  1541. XML_SetCharacterDataHandler(XML_Parser parser,
  1542. XML_CharacterDataHandler handler) {
  1543. if (parser != NULL)
  1544. parser->m_characterDataHandler = handler;
  1545. }
  1546. void XMLCALL
  1547. XML_SetProcessingInstructionHandler(XML_Parser parser,
  1548. XML_ProcessingInstructionHandler handler) {
  1549. if (parser != NULL)
  1550. parser->m_processingInstructionHandler = handler;
  1551. }
  1552. void XMLCALL
  1553. XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {
  1554. if (parser != NULL)
  1555. parser->m_commentHandler = handler;
  1556. }
  1557. void XMLCALL
  1558. XML_SetCdataSectionHandler(XML_Parser parser,
  1559. XML_StartCdataSectionHandler start,
  1560. XML_EndCdataSectionHandler end) {
  1561. if (parser == NULL)
  1562. return;
  1563. parser->m_startCdataSectionHandler = start;
  1564. parser->m_endCdataSectionHandler = end;
  1565. }
  1566. void XMLCALL
  1567. XML_SetStartCdataSectionHandler(XML_Parser parser,
  1568. XML_StartCdataSectionHandler start) {
  1569. if (parser != NULL)
  1570. parser->m_startCdataSectionHandler = start;
  1571. }
  1572. void XMLCALL
  1573. XML_SetEndCdataSectionHandler(XML_Parser parser,
  1574. XML_EndCdataSectionHandler end) {
  1575. if (parser != NULL)
  1576. parser->m_endCdataSectionHandler = end;
  1577. }
  1578. void XMLCALL
  1579. XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {
  1580. if (parser == NULL)
  1581. return;
  1582. parser->m_defaultHandler = handler;
  1583. parser->m_defaultExpandInternalEntities = XML_FALSE;
  1584. }
  1585. void XMLCALL
  1586. XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {
  1587. if (parser == NULL)
  1588. return;
  1589. parser->m_defaultHandler = handler;
  1590. parser->m_defaultExpandInternalEntities = XML_TRUE;
  1591. }
  1592. void XMLCALL
  1593. XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
  1594. XML_EndDoctypeDeclHandler end) {
  1595. if (parser == NULL)
  1596. return;
  1597. parser->m_startDoctypeDeclHandler = start;
  1598. parser->m_endDoctypeDeclHandler = end;
  1599. }
  1600. void XMLCALL
  1601. XML_SetStartDoctypeDeclHandler(XML_Parser parser,
  1602. XML_StartDoctypeDeclHandler start) {
  1603. if (parser != NULL)
  1604. parser->m_startDoctypeDeclHandler = start;
  1605. }
  1606. void XMLCALL
  1607. XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {
  1608. if (parser != NULL)
  1609. parser->m_endDoctypeDeclHandler = end;
  1610. }
  1611. void XMLCALL
  1612. XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
  1613. XML_UnparsedEntityDeclHandler handler) {
  1614. if (parser != NULL)
  1615. parser->m_unparsedEntityDeclHandler = handler;
  1616. }
  1617. void XMLCALL
  1618. XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {
  1619. if (parser != NULL)
  1620. parser->m_notationDeclHandler = handler;
  1621. }
  1622. void XMLCALL
  1623. XML_SetNamespaceDeclHandler(XML_Parser parser,
  1624. XML_StartNamespaceDeclHandler start,
  1625. XML_EndNamespaceDeclHandler end) {
  1626. if (parser == NULL)
  1627. return;
  1628. parser->m_startNamespaceDeclHandler = start;
  1629. parser->m_endNamespaceDeclHandler = end;
  1630. }
  1631. void XMLCALL
  1632. XML_SetStartNamespaceDeclHandler(XML_Parser parser,
  1633. XML_StartNamespaceDeclHandler start) {
  1634. if (parser != NULL)
  1635. parser->m_startNamespaceDeclHandler = start;
  1636. }
  1637. void XMLCALL
  1638. XML_SetEndNamespaceDeclHandler(XML_Parser parser,
  1639. XML_EndNamespaceDeclHandler end) {
  1640. if (parser != NULL)
  1641. parser->m_endNamespaceDeclHandler = end;
  1642. }
  1643. void XMLCALL
  1644. XML_SetNotStandaloneHandler(XML_Parser parser,
  1645. XML_NotStandaloneHandler handler) {
  1646. if (parser != NULL)
  1647. parser->m_notStandaloneHandler = handler;
  1648. }
  1649. void XMLCALL
  1650. XML_SetExternalEntityRefHandler(XML_Parser parser,
  1651. XML_ExternalEntityRefHandler handler) {
  1652. if (parser != NULL)
  1653. parser->m_externalEntityRefHandler = handler;
  1654. }
  1655. void XMLCALL
  1656. XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {
  1657. if (parser == NULL)
  1658. return;
  1659. if (arg)
  1660. parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
  1661. else
  1662. parser->m_externalEntityRefHandlerArg = parser;
  1663. }
  1664. void XMLCALL
  1665. XML_SetSkippedEntityHandler(XML_Parser parser,
  1666. XML_SkippedEntityHandler handler) {
  1667. if (parser != NULL)
  1668. parser->m_skippedEntityHandler = handler;
  1669. }
  1670. void XMLCALL
  1671. XML_SetUnknownEncodingHandler(XML_Parser parser,
  1672. XML_UnknownEncodingHandler handler, void *data) {
  1673. if (parser == NULL)
  1674. return;
  1675. parser->m_unknownEncodingHandler = handler;
  1676. parser->m_unknownEncodingHandlerData = data;
  1677. }
  1678. void XMLCALL
  1679. XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {
  1680. if (parser != NULL)
  1681. parser->m_elementDeclHandler = eldecl;
  1682. }
  1683. void XMLCALL
  1684. XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {
  1685. if (parser != NULL)
  1686. parser->m_attlistDeclHandler = attdecl;
  1687. }
  1688. void XMLCALL
  1689. XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {
  1690. if (parser != NULL)
  1691. parser->m_entityDeclHandler = handler;
  1692. }
  1693. void XMLCALL
  1694. XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {
  1695. if (parser != NULL)
  1696. parser->m_xmlDeclHandler = handler;
  1697. }
  1698. int XMLCALL
  1699. XML_SetParamEntityParsing(XML_Parser parser,
  1700. enum XML_ParamEntityParsing peParsing) {
  1701. if (parser == NULL)
  1702. return 0;
  1703. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  1704. if (parser->m_parsingStatus.parsing == XML_PARSING
  1705. || parser->m_parsingStatus.parsing == XML_SUSPENDED)
  1706. return 0;
  1707. #ifdef XML_DTD
  1708. parser->m_paramEntityParsing = peParsing;
  1709. return 1;
  1710. #else
  1711. return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
  1712. #endif
  1713. }
  1714. int XMLCALL
  1715. XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {
  1716. if (parser == NULL)
  1717. return 0;
  1718. if (parser->m_parentParser)
  1719. return XML_SetHashSalt(parser->m_parentParser, hash_salt);
  1720. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  1721. if (parser->m_parsingStatus.parsing == XML_PARSING
  1722. || parser->m_parsingStatus.parsing == XML_SUSPENDED)
  1723. return 0;
  1724. parser->m_hash_secret_salt = hash_salt;
  1725. return 1;
  1726. }
  1727. enum XML_Status XMLCALL
  1728. XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {
  1729. if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
  1730. if (parser != NULL)
  1731. parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
  1732. return XML_STATUS_ERROR;
  1733. }
  1734. switch (parser->m_parsingStatus.parsing) {
  1735. case XML_SUSPENDED:
  1736. parser->m_errorCode = XML_ERROR_SUSPENDED;
  1737. return XML_STATUS_ERROR;
  1738. case XML_FINISHED:
  1739. parser->m_errorCode = XML_ERROR_FINISHED;
  1740. return XML_STATUS_ERROR;
  1741. case XML_INITIALIZED:
  1742. if (parser->m_parentParser == NULL && ! startParsing(parser)) {
  1743. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1744. return XML_STATUS_ERROR;
  1745. }
  1746. /* fall through */
  1747. default:
  1748. parser->m_parsingStatus.parsing = XML_PARSING;
  1749. }
  1750. #if XML_CONTEXT_BYTES == 0
  1751. if (parser->m_bufferPtr == parser->m_bufferEnd) {
  1752. const char *end;
  1753. int nLeftOver;
  1754. enum XML_Status result;
  1755. /* Detect overflow (a+b > MAX <==> b > MAX-a) */
  1756. if ((XML_Size)len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
  1757. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1758. parser->m_eventPtr = parser->m_eventEndPtr = NULL;
  1759. parser->m_processor = errorProcessor;
  1760. return XML_STATUS_ERROR;
  1761. }
  1762. // though this isn't a buffer request, we assume that `len` is the app's
  1763. // preferred buffer fill size, and therefore save it here.
  1764. parser->m_lastBufferRequestSize = len;
  1765. parser->m_parseEndByteIndex += len;
  1766. parser->m_positionPtr = s;
  1767. parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
  1768. parser->m_errorCode
  1769. = callProcessor(parser, s, parser->m_parseEndPtr = s + len, &end);
  1770. if (parser->m_errorCode != XML_ERROR_NONE) {
  1771. parser->m_eventEndPtr = parser->m_eventPtr;
  1772. parser->m_processor = errorProcessor;
  1773. return XML_STATUS_ERROR;
  1774. } else {
  1775. switch (parser->m_parsingStatus.parsing) {
  1776. case XML_SUSPENDED:
  1777. result = XML_STATUS_SUSPENDED;
  1778. break;
  1779. case XML_INITIALIZED:
  1780. case XML_PARSING:
  1781. if (isFinal) {
  1782. parser->m_parsingStatus.parsing = XML_FINISHED;
  1783. return XML_STATUS_OK;
  1784. }
  1785. /* fall through */
  1786. default:
  1787. result = XML_STATUS_OK;
  1788. }
  1789. }
  1790. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,
  1791. &parser->m_position);
  1792. nLeftOver = s + len - end;
  1793. if (nLeftOver) {
  1794. // Back up and restore the parsing status to avoid XML_ERROR_SUSPENDED
  1795. // (and XML_ERROR_FINISHED) from XML_GetBuffer.
  1796. const enum XML_Parsing originalStatus = parser->m_parsingStatus.parsing;
  1797. parser->m_parsingStatus.parsing = XML_PARSING;
  1798. void *const temp = XML_GetBuffer(parser, nLeftOver);
  1799. parser->m_parsingStatus.parsing = originalStatus;
  1800. // GetBuffer may have overwritten this, but we want to remember what the
  1801. // app requested, not how many bytes were left over after parsing.
  1802. parser->m_lastBufferRequestSize = len;
  1803. if (temp == NULL) {
  1804. // NOTE: parser->m_errorCode has already been set by XML_GetBuffer().
  1805. parser->m_eventPtr = parser->m_eventEndPtr = NULL;
  1806. parser->m_processor = errorProcessor;
  1807. return XML_STATUS_ERROR;
  1808. }
  1809. // Since we know that the buffer was empty and XML_CONTEXT_BYTES is 0, we
  1810. // don't have any data to preserve, and can copy straight into the start
  1811. // of the buffer rather than the GetBuffer return pointer (which may be
  1812. // pointing further into the allocated buffer).
  1813. memcpy(parser->m_buffer, end, nLeftOver);
  1814. }
  1815. parser->m_bufferPtr = parser->m_buffer;
  1816. parser->m_bufferEnd = parser->m_buffer + nLeftOver;
  1817. parser->m_positionPtr = parser->m_bufferPtr;
  1818. parser->m_parseEndPtr = parser->m_bufferEnd;
  1819. parser->m_eventPtr = parser->m_bufferPtr;
  1820. parser->m_eventEndPtr = parser->m_bufferPtr;
  1821. return result;
  1822. }
  1823. #endif /* XML_CONTEXT_BYTES == 0 */
  1824. { // WINSCP
  1825. void *buff = XML_GetBuffer(parser, len);
  1826. if (buff == NULL)
  1827. return XML_STATUS_ERROR;
  1828. if (len > 0) {
  1829. assert(s != NULL); // make sure s==NULL && len!=0 was rejected above
  1830. memcpy(buff, s, len);
  1831. }
  1832. return XML_ParseBuffer(parser, len, isFinal);
  1833. } // WINSCP
  1834. }
  1835. enum XML_Status XMLCALL
  1836. XML_ParseBuffer(XML_Parser parser, int len, int isFinal) {
  1837. const char *start;
  1838. enum XML_Status result = XML_STATUS_OK;
  1839. if (parser == NULL)
  1840. return XML_STATUS_ERROR;
  1841. if (len < 0) {
  1842. parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
  1843. return XML_STATUS_ERROR;
  1844. }
  1845. switch (parser->m_parsingStatus.parsing) {
  1846. case XML_SUSPENDED:
  1847. parser->m_errorCode = XML_ERROR_SUSPENDED;
  1848. return XML_STATUS_ERROR;
  1849. case XML_FINISHED:
  1850. parser->m_errorCode = XML_ERROR_FINISHED;
  1851. return XML_STATUS_ERROR;
  1852. case XML_INITIALIZED:
  1853. /* Has someone called XML_GetBuffer successfully before? */
  1854. if (! parser->m_bufferPtr) {
  1855. parser->m_errorCode = XML_ERROR_NO_BUFFER;
  1856. return XML_STATUS_ERROR;
  1857. }
  1858. if (parser->m_parentParser == NULL && ! startParsing(parser)) {
  1859. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1860. return XML_STATUS_ERROR;
  1861. }
  1862. /* fall through */
  1863. default:
  1864. parser->m_parsingStatus.parsing = XML_PARSING;
  1865. }
  1866. start = parser->m_bufferPtr;
  1867. parser->m_positionPtr = start;
  1868. parser->m_bufferEnd += len;
  1869. parser->m_parseEndPtr = parser->m_bufferEnd;
  1870. parser->m_parseEndByteIndex += len;
  1871. parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
  1872. parser->m_errorCode = callProcessor(parser, start, parser->m_parseEndPtr,
  1873. &parser->m_bufferPtr);
  1874. if (parser->m_errorCode != XML_ERROR_NONE) {
  1875. parser->m_eventEndPtr = parser->m_eventPtr;
  1876. parser->m_processor = errorProcessor;
  1877. return XML_STATUS_ERROR;
  1878. } else {
  1879. switch (parser->m_parsingStatus.parsing) {
  1880. case XML_SUSPENDED:
  1881. result = XML_STATUS_SUSPENDED;
  1882. break;
  1883. case XML_INITIALIZED:
  1884. case XML_PARSING:
  1885. if (isFinal) {
  1886. parser->m_parsingStatus.parsing = XML_FINISHED;
  1887. return result;
  1888. }
  1889. default:; /* should not happen */
  1890. }
  1891. }
  1892. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  1893. parser->m_bufferPtr, &parser->m_position);
  1894. parser->m_positionPtr = parser->m_bufferPtr;
  1895. return result;
  1896. }
  1897. void *XMLCALL
  1898. XML_GetBuffer(XML_Parser parser, int len) {
  1899. if (parser == NULL)
  1900. return NULL;
  1901. if (len < 0) {
  1902. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1903. return NULL;
  1904. }
  1905. switch (parser->m_parsingStatus.parsing) {
  1906. case XML_SUSPENDED:
  1907. parser->m_errorCode = XML_ERROR_SUSPENDED;
  1908. return NULL;
  1909. case XML_FINISHED:
  1910. parser->m_errorCode = XML_ERROR_FINISHED;
  1911. return NULL;
  1912. default:;
  1913. }
  1914. // whether or not the request succeeds, `len` seems to be the app's preferred
  1915. // buffer fill size; remember it.
  1916. parser->m_lastBufferRequestSize = len;
  1917. if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)
  1918. || parser->m_buffer == NULL) {
  1919. #if XML_CONTEXT_BYTES > 0
  1920. int keep;
  1921. #endif /* XML_CONTEXT_BYTES > 0 */
  1922. /* Do not invoke signed arithmetic overflow: */
  1923. int neededSize = (int)((unsigned)len
  1924. + (unsigned)EXPAT_SAFE_PTR_DIFF(
  1925. parser->m_bufferEnd, parser->m_bufferPtr));
  1926. if (neededSize < 0) {
  1927. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1928. return NULL;
  1929. }
  1930. #if XML_CONTEXT_BYTES > 0
  1931. keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
  1932. if (keep > XML_CONTEXT_BYTES)
  1933. keep = XML_CONTEXT_BYTES;
  1934. /* Detect and prevent integer overflow */
  1935. if (keep > INT_MAX - neededSize) {
  1936. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1937. return NULL;
  1938. }
  1939. neededSize += keep;
  1940. #endif /* XML_CONTEXT_BYTES > 0 */
  1941. if (parser->m_buffer && parser->m_bufferPtr
  1942. && neededSize
  1943. <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
  1944. #if XML_CONTEXT_BYTES > 0
  1945. if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
  1946. int offset
  1947. = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)
  1948. - keep;
  1949. /* The buffer pointers cannot be NULL here; we have at least some bytes
  1950. * in the buffer */
  1951. memmove(parser->m_buffer, &parser->m_buffer[offset],
  1952. parser->m_bufferEnd - parser->m_bufferPtr + keep);
  1953. parser->m_bufferEnd -= offset;
  1954. parser->m_bufferPtr -= offset;
  1955. }
  1956. #else
  1957. memmove(parser->m_buffer, parser->m_bufferPtr,
  1958. EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
  1959. parser->m_bufferEnd
  1960. = parser->m_buffer
  1961. + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
  1962. parser->m_bufferPtr = parser->m_buffer;
  1963. #endif /* XML_CONTEXT_BYTES > 0 */
  1964. } else {
  1965. char *newBuf;
  1966. int bufferSize
  1967. = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer);
  1968. if (bufferSize == 0)
  1969. bufferSize = INIT_BUFFER_SIZE;
  1970. do {
  1971. /* Do not invoke signed arithmetic overflow: */
  1972. bufferSize = (int)(2U * (unsigned)bufferSize);
  1973. } while (bufferSize < neededSize && bufferSize > 0);
  1974. if (bufferSize <= 0) {
  1975. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1976. return NULL;
  1977. }
  1978. newBuf = (char *)MALLOC(parser, bufferSize);
  1979. if (newBuf == 0) {
  1980. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  1981. return NULL;
  1982. }
  1983. parser->m_bufferLim = newBuf + bufferSize;
  1984. #if XML_CONTEXT_BYTES > 0
  1985. if (parser->m_bufferPtr) {
  1986. memcpy(newBuf, &parser->m_bufferPtr[-keep],
  1987. EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
  1988. + keep);
  1989. FREE(parser, parser->m_buffer);
  1990. parser->m_buffer = newBuf;
  1991. parser->m_bufferEnd
  1992. = parser->m_buffer
  1993. + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
  1994. + keep;
  1995. parser->m_bufferPtr = parser->m_buffer + keep;
  1996. } else {
  1997. /* This must be a brand new buffer with no data in it yet */
  1998. parser->m_bufferEnd = newBuf;
  1999. parser->m_bufferPtr = parser->m_buffer = newBuf;
  2000. }
  2001. #else
  2002. if (parser->m_bufferPtr) {
  2003. memcpy(newBuf, parser->m_bufferPtr,
  2004. EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
  2005. FREE(parser, parser->m_buffer);
  2006. parser->m_bufferEnd
  2007. = newBuf
  2008. + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
  2009. } else {
  2010. /* This must be a brand new buffer with no data in it yet */
  2011. parser->m_bufferEnd = newBuf;
  2012. }
  2013. parser->m_bufferPtr = parser->m_buffer = newBuf;
  2014. #endif /* XML_CONTEXT_BYTES > 0 */
  2015. }
  2016. parser->m_eventPtr = parser->m_eventEndPtr = NULL;
  2017. parser->m_positionPtr = NULL;
  2018. }
  2019. return parser->m_bufferEnd;
  2020. }
  2021. enum XML_Status XMLCALL
  2022. XML_StopParser(XML_Parser parser, XML_Bool resumable) {
  2023. if (parser == NULL)
  2024. return XML_STATUS_ERROR;
  2025. switch (parser->m_parsingStatus.parsing) {
  2026. case XML_SUSPENDED:
  2027. if (resumable) {
  2028. parser->m_errorCode = XML_ERROR_SUSPENDED;
  2029. return XML_STATUS_ERROR;
  2030. }
  2031. parser->m_parsingStatus.parsing = XML_FINISHED;
  2032. break;
  2033. case XML_FINISHED:
  2034. parser->m_errorCode = XML_ERROR_FINISHED;
  2035. return XML_STATUS_ERROR;
  2036. default:
  2037. if (resumable) {
  2038. #ifdef XML_DTD
  2039. if (parser->m_isParamEntity) {
  2040. parser->m_errorCode = XML_ERROR_SUSPEND_PE;
  2041. return XML_STATUS_ERROR;
  2042. }
  2043. #endif
  2044. parser->m_parsingStatus.parsing = XML_SUSPENDED;
  2045. } else
  2046. parser->m_parsingStatus.parsing = XML_FINISHED;
  2047. }
  2048. return XML_STATUS_OK;
  2049. }
  2050. enum XML_Status XMLCALL
  2051. XML_ResumeParser(XML_Parser parser) {
  2052. enum XML_Status result = XML_STATUS_OK;
  2053. if (parser == NULL)
  2054. return XML_STATUS_ERROR;
  2055. if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
  2056. parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
  2057. return XML_STATUS_ERROR;
  2058. }
  2059. parser->m_parsingStatus.parsing = XML_PARSING;
  2060. parser->m_errorCode = callProcessor(
  2061. parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
  2062. if (parser->m_errorCode != XML_ERROR_NONE) {
  2063. parser->m_eventEndPtr = parser->m_eventPtr;
  2064. parser->m_processor = errorProcessor;
  2065. return XML_STATUS_ERROR;
  2066. } else {
  2067. switch (parser->m_parsingStatus.parsing) {
  2068. case XML_SUSPENDED:
  2069. result = XML_STATUS_SUSPENDED;
  2070. break;
  2071. case XML_INITIALIZED:
  2072. case XML_PARSING:
  2073. if (parser->m_parsingStatus.finalBuffer) {
  2074. parser->m_parsingStatus.parsing = XML_FINISHED;
  2075. return result;
  2076. }
  2077. default:;
  2078. }
  2079. }
  2080. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  2081. parser->m_bufferPtr, &parser->m_position);
  2082. parser->m_positionPtr = parser->m_bufferPtr;
  2083. return result;
  2084. }
  2085. void XMLCALL
  2086. XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {
  2087. if (parser == NULL)
  2088. return;
  2089. assert(status != NULL);
  2090. *status = parser->m_parsingStatus;
  2091. }
  2092. enum XML_Error XMLCALL
  2093. XML_GetErrorCode(XML_Parser parser) {
  2094. if (parser == NULL)
  2095. return XML_ERROR_INVALID_ARGUMENT;
  2096. return parser->m_errorCode;
  2097. }
  2098. XML_Index XMLCALL
  2099. XML_GetCurrentByteIndex(XML_Parser parser) {
  2100. if (parser == NULL)
  2101. return -1;
  2102. if (parser->m_eventPtr)
  2103. return (XML_Index)(parser->m_parseEndByteIndex
  2104. - (parser->m_parseEndPtr - parser->m_eventPtr));
  2105. return -1;
  2106. }
  2107. int XMLCALL
  2108. XML_GetCurrentByteCount(XML_Parser parser) {
  2109. if (parser == NULL)
  2110. return 0;
  2111. if (parser->m_eventEndPtr && parser->m_eventPtr)
  2112. return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
  2113. return 0;
  2114. }
  2115. const char *XMLCALL
  2116. XML_GetInputContext(XML_Parser parser, int *offset, int *size) {
  2117. #if XML_CONTEXT_BYTES > 0
  2118. if (parser == NULL)
  2119. return NULL;
  2120. if (parser->m_eventPtr && parser->m_buffer) {
  2121. if (offset != NULL)
  2122. *offset = (int)(parser->m_eventPtr - parser->m_buffer);
  2123. if (size != NULL)
  2124. *size = (int)(parser->m_bufferEnd - parser->m_buffer);
  2125. return parser->m_buffer;
  2126. }
  2127. #else
  2128. (void)parser;
  2129. (void)offset;
  2130. (void)size;
  2131. #endif /* XML_CONTEXT_BYTES > 0 */
  2132. return (const char *)0;
  2133. }
  2134. XML_Size XMLCALL
  2135. XML_GetCurrentLineNumber(XML_Parser parser) {
  2136. if (parser == NULL)
  2137. return 0;
  2138. if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
  2139. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  2140. parser->m_eventPtr, &parser->m_position);
  2141. parser->m_positionPtr = parser->m_eventPtr;
  2142. }
  2143. return parser->m_position.lineNumber + 1;
  2144. }
  2145. XML_Size XMLCALL
  2146. XML_GetCurrentColumnNumber(XML_Parser parser) {
  2147. if (parser == NULL)
  2148. return 0;
  2149. if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
  2150. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  2151. parser->m_eventPtr, &parser->m_position);
  2152. parser->m_positionPtr = parser->m_eventPtr;
  2153. }
  2154. return parser->m_position.columnNumber;
  2155. }
  2156. void XMLCALL
  2157. XML_FreeContentModel(XML_Parser parser, XML_Content *model) {
  2158. if (parser != NULL)
  2159. FREE(parser, model);
  2160. }
  2161. void *XMLCALL
  2162. XML_MemMalloc(XML_Parser parser, size_t size) {
  2163. if (parser == NULL)
  2164. return NULL;
  2165. return MALLOC(parser, size);
  2166. }
  2167. void *XMLCALL
  2168. XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {
  2169. if (parser == NULL)
  2170. return NULL;
  2171. return REALLOC(parser, ptr, size);
  2172. }
  2173. void XMLCALL
  2174. XML_MemFree(XML_Parser parser, void *ptr) {
  2175. if (parser != NULL)
  2176. FREE(parser, ptr);
  2177. }
  2178. void XMLCALL
  2179. XML_DefaultCurrent(XML_Parser parser) {
  2180. if (parser == NULL)
  2181. return;
  2182. if (parser->m_defaultHandler) {
  2183. if (parser->m_openInternalEntities)
  2184. reportDefault(parser, parser->m_internalEncoding,
  2185. parser->m_openInternalEntities->internalEventPtr,
  2186. parser->m_openInternalEntities->internalEventEndPtr);
  2187. else
  2188. reportDefault(parser, parser->m_encoding, parser->m_eventPtr,
  2189. parser->m_eventEndPtr);
  2190. }
  2191. }
  2192. const XML_LChar *XMLCALL
  2193. XML_ErrorString(enum XML_Error code) {
  2194. switch (code) {
  2195. case XML_ERROR_NONE:
  2196. return NULL;
  2197. case XML_ERROR_NO_MEMORY:
  2198. return XML_L("out of memory");
  2199. case XML_ERROR_SYNTAX:
  2200. return XML_L("syntax error");
  2201. case XML_ERROR_NO_ELEMENTS:
  2202. return XML_L("no element found");
  2203. case XML_ERROR_INVALID_TOKEN:
  2204. return XML_L("not well-formed (invalid token)");
  2205. case XML_ERROR_UNCLOSED_TOKEN:
  2206. return XML_L("unclosed token");
  2207. case XML_ERROR_PARTIAL_CHAR:
  2208. return XML_L("partial character");
  2209. case XML_ERROR_TAG_MISMATCH:
  2210. return XML_L("mismatched tag");
  2211. case XML_ERROR_DUPLICATE_ATTRIBUTE:
  2212. return XML_L("duplicate attribute");
  2213. case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
  2214. return XML_L("junk after document element");
  2215. case XML_ERROR_PARAM_ENTITY_REF:
  2216. return XML_L("illegal parameter entity reference");
  2217. case XML_ERROR_UNDEFINED_ENTITY:
  2218. return XML_L("undefined entity");
  2219. case XML_ERROR_RECURSIVE_ENTITY_REF:
  2220. return XML_L("recursive entity reference");
  2221. case XML_ERROR_ASYNC_ENTITY:
  2222. return XML_L("asynchronous entity");
  2223. case XML_ERROR_BAD_CHAR_REF:
  2224. return XML_L("reference to invalid character number");
  2225. case XML_ERROR_BINARY_ENTITY_REF:
  2226. return XML_L("reference to binary entity");
  2227. case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
  2228. return XML_L("reference to external entity in attribute");
  2229. case XML_ERROR_MISPLACED_XML_PI:
  2230. return XML_L("XML or text declaration not at start of entity");
  2231. case XML_ERROR_UNKNOWN_ENCODING:
  2232. return XML_L("unknown encoding");
  2233. case XML_ERROR_INCORRECT_ENCODING:
  2234. return XML_L("encoding specified in XML declaration is incorrect");
  2235. case XML_ERROR_UNCLOSED_CDATA_SECTION:
  2236. return XML_L("unclosed CDATA section");
  2237. case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
  2238. return XML_L("error in processing external entity reference");
  2239. case XML_ERROR_NOT_STANDALONE:
  2240. return XML_L("document is not standalone");
  2241. case XML_ERROR_UNEXPECTED_STATE:
  2242. return XML_L("unexpected parser state - please send a bug report");
  2243. case XML_ERROR_ENTITY_DECLARED_IN_PE:
  2244. return XML_L("entity declared in parameter entity");
  2245. case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
  2246. return XML_L("requested feature requires XML_DTD support in Expat");
  2247. case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
  2248. return XML_L("cannot change setting once parsing has begun");
  2249. /* Added in 1.95.7. */
  2250. case XML_ERROR_UNBOUND_PREFIX:
  2251. return XML_L("unbound prefix");
  2252. /* Added in 1.95.8. */
  2253. case XML_ERROR_UNDECLARING_PREFIX:
  2254. return XML_L("must not undeclare prefix");
  2255. case XML_ERROR_INCOMPLETE_PE:
  2256. return XML_L("incomplete markup in parameter entity");
  2257. case XML_ERROR_XML_DECL:
  2258. return XML_L("XML declaration not well-formed");
  2259. case XML_ERROR_TEXT_DECL:
  2260. return XML_L("text declaration not well-formed");
  2261. case XML_ERROR_PUBLICID:
  2262. return XML_L("illegal character(s) in public id");
  2263. case XML_ERROR_SUSPENDED:
  2264. return XML_L("parser suspended");
  2265. case XML_ERROR_NOT_SUSPENDED:
  2266. return XML_L("parser not suspended");
  2267. case XML_ERROR_ABORTED:
  2268. return XML_L("parsing aborted");
  2269. case XML_ERROR_FINISHED:
  2270. return XML_L("parsing finished");
  2271. case XML_ERROR_SUSPEND_PE:
  2272. return XML_L("cannot suspend in external parameter entity");
  2273. /* Added in 2.0.0. */
  2274. case XML_ERROR_RESERVED_PREFIX_XML:
  2275. return XML_L(
  2276. "reserved prefix (xml) must not be undeclared or bound to another namespace name");
  2277. case XML_ERROR_RESERVED_PREFIX_XMLNS:
  2278. return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
  2279. case XML_ERROR_RESERVED_NAMESPACE_URI:
  2280. return XML_L(
  2281. "prefix must not be bound to one of the reserved namespace names");
  2282. /* Added in 2.2.5. */
  2283. case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
  2284. return XML_L("invalid argument");
  2285. /* Added in 2.3.0. */
  2286. case XML_ERROR_NO_BUFFER:
  2287. return XML_L(
  2288. "a successful prior call to function XML_GetBuffer is required");
  2289. /* Added in 2.4.0. */
  2290. case XML_ERROR_AMPLIFICATION_LIMIT_BREACH:
  2291. return XML_L(
  2292. "limit on input amplification factor (from DTD and entities) breached");
  2293. }
  2294. return NULL;
  2295. }
  2296. const XML_LChar *XMLCALL
  2297. XML_ExpatVersion(void) {
  2298. /* V1 is used to string-ize the version number. However, it would
  2299. string-ize the actual version macro *names* unless we get them
  2300. substituted before being passed to V1. CPP is defined to expand
  2301. a macro, then rescan for more expansions. Thus, we use V2 to expand
  2302. the version macros, then CPP will expand the resulting V1() macro
  2303. with the correct numerals. */
  2304. /* ### I'm assuming cpp is portable in this respect... */
  2305. #define V1(a, b, c) XML_L(#a) XML_L(".") XML_L(#b) XML_L(".") XML_L(#c)
  2306. #define V2(a, b, c) XML_L("expat_") V1(a, b, c)
  2307. return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
  2308. #undef V1
  2309. #undef V2
  2310. }
  2311. XML_Expat_Version XMLCALL
  2312. XML_ExpatVersionInfo(void) {
  2313. XML_Expat_Version version;
  2314. version.major = XML_MAJOR_VERSION;
  2315. version.minor = XML_MINOR_VERSION;
  2316. version.micro = XML_MICRO_VERSION;
  2317. return version;
  2318. }
  2319. const XML_Feature *XMLCALL
  2320. XML_GetFeatureList(void) {
  2321. static const XML_Feature features[] = {
  2322. {XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
  2323. sizeof(XML_Char)},
  2324. {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
  2325. sizeof(XML_LChar)},
  2326. #ifdef XML_UNICODE
  2327. {XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
  2328. #endif
  2329. #ifdef XML_UNICODE_WCHAR_T
  2330. {XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
  2331. #endif
  2332. #ifdef XML_DTD
  2333. {XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
  2334. #endif
  2335. #if XML_CONTEXT_BYTES > 0
  2336. {XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
  2337. XML_CONTEXT_BYTES},
  2338. #endif
  2339. #ifdef XML_MIN_SIZE
  2340. {XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
  2341. #endif
  2342. #ifdef XML_NS
  2343. {XML_FEATURE_NS, XML_L("XML_NS"), 0},
  2344. #endif
  2345. #ifdef XML_LARGE_SIZE
  2346. {XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
  2347. #endif
  2348. #ifdef XML_ATTR_INFO
  2349. {XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
  2350. #endif
  2351. #if XML_GE == 1
  2352. /* Added in Expat 2.4.0 for XML_DTD defined and
  2353. * added in Expat 2.6.0 for XML_GE == 1. */
  2354. {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT,
  2355. XML_L("XML_BLAP_MAX_AMP"),
  2356. (long int)
  2357. EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT},
  2358. {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT,
  2359. XML_L("XML_BLAP_ACT_THRES"),
  2360. EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT},
  2361. /* Added in Expat 2.6.0. */
  2362. {XML_FEATURE_GE, XML_L("XML_GE"), 0},
  2363. #endif
  2364. {XML_FEATURE_END, NULL, 0}};
  2365. return features;
  2366. }
  2367. #if XML_GE == 1
  2368. XML_Bool XMLCALL
  2369. XML_SetBillionLaughsAttackProtectionMaximumAmplification(
  2370. XML_Parser parser, float maximumAmplificationFactor) {
  2371. if ((parser == NULL) || (parser->m_parentParser != NULL)
  2372. || isnan(maximumAmplificationFactor)
  2373. || (maximumAmplificationFactor < 1.0f)) {
  2374. return XML_FALSE;
  2375. }
  2376. parser->m_accounting.maximumAmplificationFactor = maximumAmplificationFactor;
  2377. return XML_TRUE;
  2378. }
  2379. XML_Bool XMLCALL
  2380. XML_SetBillionLaughsAttackProtectionActivationThreshold(
  2381. XML_Parser parser, unsigned long long activationThresholdBytes) {
  2382. if ((parser == NULL) || (parser->m_parentParser != NULL)) {
  2383. return XML_FALSE;
  2384. }
  2385. parser->m_accounting.activationThresholdBytes = activationThresholdBytes;
  2386. return XML_TRUE;
  2387. }
  2388. #endif /* XML_GE == 1 */
  2389. XML_Bool XMLCALL
  2390. XML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled) {
  2391. if (parser != NULL && (enabled == XML_TRUE || enabled == XML_FALSE)) {
  2392. parser->m_reparseDeferralEnabled = enabled;
  2393. return XML_TRUE;
  2394. }
  2395. return XML_FALSE;
  2396. }
  2397. /* Initially tag->rawName always points into the parse buffer;
  2398. for those TAG instances opened while the current parse buffer was
  2399. processed, and not yet closed, we need to store tag->rawName in a more
  2400. permanent location, since the parse buffer is about to be discarded.
  2401. */
  2402. static XML_Bool
  2403. storeRawNames(XML_Parser parser) {
  2404. TAG *tag = parser->m_tagStack;
  2405. while (tag) {
  2406. int bufSize;
  2407. int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
  2408. size_t rawNameLen;
  2409. char *rawNameBuf = tag->buf + nameLen;
  2410. /* Stop if already stored. Since m_tagStack is a stack, we can stop
  2411. at the first entry that has already been copied; everything
  2412. below it in the stack is already been accounted for in a
  2413. previous call to this function.
  2414. */
  2415. if (tag->rawName == rawNameBuf)
  2416. break;
  2417. /* For reuse purposes we need to ensure that the
  2418. size of tag->buf is a multiple of sizeof(XML_Char).
  2419. */
  2420. rawNameLen = ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
  2421. /* Detect and prevent integer overflow. */
  2422. if (rawNameLen > (size_t)INT_MAX - nameLen)
  2423. return XML_FALSE;
  2424. bufSize = nameLen + (int)rawNameLen;
  2425. if (bufSize > tag->bufEnd - tag->buf) {
  2426. char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
  2427. if (temp == NULL)
  2428. return XML_FALSE;
  2429. /* if tag->name.str points to tag->buf (only when namespace
  2430. processing is off) then we have to update it
  2431. */
  2432. if (tag->name.str == (XML_Char *)tag->buf)
  2433. tag->name.str = (XML_Char *)temp;
  2434. /* if tag->name.localPart is set (when namespace processing is on)
  2435. then update it as well, since it will always point into tag->buf
  2436. */
  2437. if (tag->name.localPart)
  2438. tag->name.localPart
  2439. = (XML_Char *)temp + (tag->name.localPart - (XML_Char *)tag->buf);
  2440. tag->buf = temp;
  2441. tag->bufEnd = temp + bufSize;
  2442. rawNameBuf = temp + nameLen;
  2443. }
  2444. memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
  2445. tag->rawName = rawNameBuf;
  2446. tag = tag->parent;
  2447. }
  2448. return XML_TRUE;
  2449. }
  2450. static enum XML_Error PTRCALL
  2451. contentProcessor(XML_Parser parser, const char *start, const char *end,
  2452. const char **endPtr) {
  2453. enum XML_Error result = doContent(
  2454. parser, 0, parser->m_encoding, start, end, endPtr,
  2455. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);
  2456. if (result == XML_ERROR_NONE) {
  2457. if (! storeRawNames(parser))
  2458. return XML_ERROR_NO_MEMORY;
  2459. }
  2460. return result;
  2461. }
  2462. static enum XML_Error PTRCALL
  2463. externalEntityInitProcessor(XML_Parser parser, const char *start,
  2464. const char *end, const char **endPtr) {
  2465. enum XML_Error result = initializeEncoding(parser);
  2466. if (result != XML_ERROR_NONE)
  2467. return result;
  2468. parser->m_processor = externalEntityInitProcessor2;
  2469. return externalEntityInitProcessor2(parser, start, end, endPtr);
  2470. }
  2471. static enum XML_Error PTRCALL
  2472. externalEntityInitProcessor2(XML_Parser parser, const char *start,
  2473. const char *end, const char **endPtr) {
  2474. const char *next = start; /* XmlContentTok doesn't always set the last arg */
  2475. int tok = XmlContentTok(parser->m_encoding, start, end, &next);
  2476. switch (tok) {
  2477. case XML_TOK_BOM:
  2478. #if XML_GE == 1
  2479. if (! accountingDiffTolerated(parser, tok, start, next, __LINE__,
  2480. XML_ACCOUNT_DIRECT)) {
  2481. accountingOnAbort(parser);
  2482. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  2483. }
  2484. #endif /* XML_GE == 1 */
  2485. /* If we are at the end of the buffer, this would cause the next stage,
  2486. i.e. externalEntityInitProcessor3, to pass control directly to
  2487. doContent (by detecting XML_TOK_NONE) without processing any xml text
  2488. declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
  2489. */
  2490. if (next == end && ! parser->m_parsingStatus.finalBuffer) {
  2491. *endPtr = next;
  2492. return XML_ERROR_NONE;
  2493. }
  2494. start = next;
  2495. break;
  2496. case XML_TOK_PARTIAL:
  2497. if (! parser->m_parsingStatus.finalBuffer) {
  2498. *endPtr = start;
  2499. return XML_ERROR_NONE;
  2500. }
  2501. parser->m_eventPtr = start;
  2502. return XML_ERROR_UNCLOSED_TOKEN;
  2503. case XML_TOK_PARTIAL_CHAR:
  2504. if (! parser->m_parsingStatus.finalBuffer) {
  2505. *endPtr = start;
  2506. return XML_ERROR_NONE;
  2507. }
  2508. parser->m_eventPtr = start;
  2509. return XML_ERROR_PARTIAL_CHAR;
  2510. }
  2511. parser->m_processor = externalEntityInitProcessor3;
  2512. return externalEntityInitProcessor3(parser, start, end, endPtr);
  2513. }
  2514. static enum XML_Error PTRCALL
  2515. externalEntityInitProcessor3(XML_Parser parser, const char *start,
  2516. const char *end, const char **endPtr) {
  2517. int tok;
  2518. const char *next = start; /* XmlContentTok doesn't always set the last arg */
  2519. parser->m_eventPtr = start;
  2520. tok = XmlContentTok(parser->m_encoding, start, end, &next);
  2521. /* Note: These bytes are accounted later in:
  2522. - processXmlDecl
  2523. - externalEntityContentProcessor
  2524. */
  2525. parser->m_eventEndPtr = next;
  2526. switch (tok) {
  2527. case XML_TOK_XML_DECL: {
  2528. enum XML_Error result;
  2529. result = processXmlDecl(parser, 1, start, next);
  2530. if (result != XML_ERROR_NONE)
  2531. return result;
  2532. switch (parser->m_parsingStatus.parsing) {
  2533. case XML_SUSPENDED:
  2534. *endPtr = next;
  2535. return XML_ERROR_NONE;
  2536. case XML_FINISHED:
  2537. return XML_ERROR_ABORTED;
  2538. default:
  2539. start = next;
  2540. }
  2541. } break;
  2542. case XML_TOK_PARTIAL:
  2543. if (! parser->m_parsingStatus.finalBuffer) {
  2544. *endPtr = start;
  2545. return XML_ERROR_NONE;
  2546. }
  2547. return XML_ERROR_UNCLOSED_TOKEN;
  2548. case XML_TOK_PARTIAL_CHAR:
  2549. if (! parser->m_parsingStatus.finalBuffer) {
  2550. *endPtr = start;
  2551. return XML_ERROR_NONE;
  2552. }
  2553. return XML_ERROR_PARTIAL_CHAR;
  2554. }
  2555. parser->m_processor = externalEntityContentProcessor;
  2556. parser->m_tagLevel = 1;
  2557. return externalEntityContentProcessor(parser, start, end, endPtr);
  2558. }
  2559. static enum XML_Error PTRCALL
  2560. externalEntityContentProcessor(XML_Parser parser, const char *start,
  2561. const char *end, const char **endPtr) {
  2562. enum XML_Error result
  2563. = doContent(parser, 1, parser->m_encoding, start, end, endPtr,
  2564. (XML_Bool)! parser->m_parsingStatus.finalBuffer,
  2565. XML_ACCOUNT_ENTITY_EXPANSION);
  2566. if (result == XML_ERROR_NONE) {
  2567. if (! storeRawNames(parser))
  2568. return XML_ERROR_NO_MEMORY;
  2569. }
  2570. return result;
  2571. }
  2572. static enum XML_Error
  2573. doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
  2574. const char *s, const char *end, const char **nextPtr,
  2575. XML_Bool haveMore, enum XML_Account account) {
  2576. /* save one level of indirection */
  2577. DTD *const dtd = parser->m_dtd;
  2578. const char **eventPP;
  2579. const char **eventEndPP;
  2580. if (enc == parser->m_encoding) {
  2581. eventPP = &parser->m_eventPtr;
  2582. eventEndPP = &parser->m_eventEndPtr;
  2583. } else {
  2584. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  2585. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  2586. }
  2587. *eventPP = s;
  2588. for (;;) {
  2589. const char *next = s; /* XmlContentTok doesn't always set the last arg */
  2590. int tok = XmlContentTok(enc, s, end, &next);
  2591. #if XML_GE == 1
  2592. const char *accountAfter
  2593. = ((tok == XML_TOK_TRAILING_RSQB) || (tok == XML_TOK_TRAILING_CR))
  2594. ? (haveMore ? s /* i.e. 0 bytes */ : end)
  2595. : next;
  2596. if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__,
  2597. account)) {
  2598. accountingOnAbort(parser);
  2599. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  2600. }
  2601. #endif
  2602. *eventEndPP = next;
  2603. switch (tok) {
  2604. case XML_TOK_TRAILING_CR:
  2605. if (haveMore) {
  2606. *nextPtr = s;
  2607. return XML_ERROR_NONE;
  2608. }
  2609. *eventEndPP = end;
  2610. if (parser->m_characterDataHandler) {
  2611. XML_Char c = 0xA;
  2612. parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
  2613. } else if (parser->m_defaultHandler)
  2614. reportDefault(parser, enc, s, end);
  2615. /* We are at the end of the final buffer, should we check for
  2616. XML_SUSPENDED, XML_FINISHED?
  2617. */
  2618. if (startTagLevel == 0)
  2619. return XML_ERROR_NO_ELEMENTS;
  2620. if (parser->m_tagLevel != startTagLevel)
  2621. return XML_ERROR_ASYNC_ENTITY;
  2622. *nextPtr = end;
  2623. return XML_ERROR_NONE;
  2624. case XML_TOK_NONE:
  2625. if (haveMore) {
  2626. *nextPtr = s;
  2627. return XML_ERROR_NONE;
  2628. }
  2629. if (startTagLevel > 0) {
  2630. if (parser->m_tagLevel != startTagLevel)
  2631. return XML_ERROR_ASYNC_ENTITY;
  2632. *nextPtr = s;
  2633. return XML_ERROR_NONE;
  2634. }
  2635. return XML_ERROR_NO_ELEMENTS;
  2636. case XML_TOK_INVALID:
  2637. *eventPP = next;
  2638. return XML_ERROR_INVALID_TOKEN;
  2639. case XML_TOK_PARTIAL:
  2640. if (haveMore) {
  2641. *nextPtr = s;
  2642. return XML_ERROR_NONE;
  2643. }
  2644. return XML_ERROR_UNCLOSED_TOKEN;
  2645. case XML_TOK_PARTIAL_CHAR:
  2646. if (haveMore) {
  2647. *nextPtr = s;
  2648. return XML_ERROR_NONE;
  2649. }
  2650. return XML_ERROR_PARTIAL_CHAR;
  2651. case XML_TOK_ENTITY_REF: {
  2652. const XML_Char *name;
  2653. ENTITY *entity;
  2654. XML_Char ch = (XML_Char)XmlPredefinedEntityName(
  2655. enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
  2656. if (ch) {
  2657. #if XML_GE == 1
  2658. /* NOTE: We are replacing 4-6 characters original input for 1 character
  2659. * so there is no amplification and hence recording without
  2660. * protection. */
  2661. accountingDiffTolerated(parser, tok, (char *)&ch,
  2662. ((char *)&ch) + sizeof(XML_Char), __LINE__,
  2663. XML_ACCOUNT_ENTITY_EXPANSION);
  2664. #endif /* XML_GE == 1 */
  2665. if (parser->m_characterDataHandler)
  2666. parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
  2667. else if (parser->m_defaultHandler)
  2668. reportDefault(parser, enc, s, next);
  2669. break;
  2670. }
  2671. name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  2672. next - enc->minBytesPerChar);
  2673. if (! name)
  2674. return XML_ERROR_NO_MEMORY;
  2675. entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
  2676. poolDiscard(&dtd->pool);
  2677. /* First, determine if a check for an existing declaration is needed;
  2678. if yes, check that the entity exists, and that it is internal,
  2679. otherwise call the skipped entity or default handler.
  2680. */
  2681. if (! dtd->hasParamEntityRefs || dtd->standalone) {
  2682. if (! entity)
  2683. return XML_ERROR_UNDEFINED_ENTITY;
  2684. else if (! entity->is_internal)
  2685. return XML_ERROR_ENTITY_DECLARED_IN_PE;
  2686. } else if (! entity) {
  2687. if (parser->m_skippedEntityHandler)
  2688. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  2689. else if (parser->m_defaultHandler)
  2690. reportDefault(parser, enc, s, next);
  2691. break;
  2692. }
  2693. if (entity->open)
  2694. return XML_ERROR_RECURSIVE_ENTITY_REF;
  2695. if (entity->notation)
  2696. return XML_ERROR_BINARY_ENTITY_REF;
  2697. if (entity->textPtr) {
  2698. enum XML_Error result;
  2699. if (! parser->m_defaultExpandInternalEntities) {
  2700. if (parser->m_skippedEntityHandler)
  2701. parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,
  2702. 0);
  2703. else if (parser->m_defaultHandler)
  2704. reportDefault(parser, enc, s, next);
  2705. break;
  2706. }
  2707. result = processInternalEntity(parser, entity, XML_FALSE);
  2708. if (result != XML_ERROR_NONE)
  2709. return result;
  2710. } else if (parser->m_externalEntityRefHandler) {
  2711. const XML_Char *context;
  2712. entity->open = XML_TRUE;
  2713. context = getContext(parser);
  2714. entity->open = XML_FALSE;
  2715. if (! context)
  2716. return XML_ERROR_NO_MEMORY;
  2717. if (! parser->m_externalEntityRefHandler(
  2718. parser->m_externalEntityRefHandlerArg, context, entity->base,
  2719. entity->systemId, entity->publicId))
  2720. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  2721. poolDiscard(&parser->m_tempPool);
  2722. } else if (parser->m_defaultHandler)
  2723. reportDefault(parser, enc, s, next);
  2724. break;
  2725. }
  2726. case XML_TOK_START_TAG_NO_ATTS:
  2727. /* fall through */
  2728. case XML_TOK_START_TAG_WITH_ATTS: {
  2729. TAG *tag;
  2730. enum XML_Error result;
  2731. XML_Char *toPtr;
  2732. if (parser->m_freeTagList) {
  2733. tag = parser->m_freeTagList;
  2734. parser->m_freeTagList = parser->m_freeTagList->parent;
  2735. } else {
  2736. tag = (TAG *)MALLOC(parser, sizeof(TAG));
  2737. if (! tag)
  2738. return XML_ERROR_NO_MEMORY;
  2739. tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
  2740. if (! tag->buf) {
  2741. FREE(parser, tag);
  2742. return XML_ERROR_NO_MEMORY;
  2743. }
  2744. tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
  2745. }
  2746. tag->bindings = NULL;
  2747. tag->parent = parser->m_tagStack;
  2748. parser->m_tagStack = tag;
  2749. tag->name.localPart = NULL;
  2750. tag->name.prefix = NULL;
  2751. tag->rawName = s + enc->minBytesPerChar;
  2752. tag->rawNameLength = XmlNameLength(enc, tag->rawName);
  2753. ++parser->m_tagLevel;
  2754. {
  2755. const char *rawNameEnd = tag->rawName + tag->rawNameLength;
  2756. const char *fromPtr = tag->rawName;
  2757. toPtr = (XML_Char *)tag->buf;
  2758. for (;;) {
  2759. int bufSize;
  2760. int convLen;
  2761. const enum XML_Convert_Result convert_res
  2762. = XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,
  2763. (ICHAR *)tag->bufEnd - 1);
  2764. convLen = (int)(toPtr - (XML_Char *)tag->buf);
  2765. if ((fromPtr >= rawNameEnd)
  2766. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
  2767. tag->name.strLen = convLen;
  2768. break;
  2769. }
  2770. bufSize = (int)(tag->bufEnd - tag->buf) << 1;
  2771. {
  2772. char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
  2773. if (temp == NULL)
  2774. return XML_ERROR_NO_MEMORY;
  2775. tag->buf = temp;
  2776. tag->bufEnd = temp + bufSize;
  2777. toPtr = (XML_Char *)temp + convLen;
  2778. }
  2779. }
  2780. }
  2781. tag->name.str = (XML_Char *)tag->buf;
  2782. *toPtr = XML_T('\0');
  2783. result
  2784. = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings), account);
  2785. if (result)
  2786. return result;
  2787. if (parser->m_startElementHandler)
  2788. parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
  2789. (const XML_Char **)parser->m_atts);
  2790. else if (parser->m_defaultHandler)
  2791. reportDefault(parser, enc, s, next);
  2792. poolClear(&parser->m_tempPool);
  2793. break;
  2794. }
  2795. case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
  2796. /* fall through */
  2797. case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {
  2798. const char *rawName = s + enc->minBytesPerChar;
  2799. enum XML_Error result;
  2800. BINDING *bindings = NULL;
  2801. XML_Bool noElmHandlers = XML_TRUE;
  2802. TAG_NAME name;
  2803. name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
  2804. rawName + XmlNameLength(enc, rawName));
  2805. if (! name.str)
  2806. return XML_ERROR_NO_MEMORY;
  2807. poolFinish(&parser->m_tempPool);
  2808. result = storeAtts(parser, enc, s, &name, &bindings,
  2809. XML_ACCOUNT_NONE /* token spans whole start tag */);
  2810. if (result != XML_ERROR_NONE) {
  2811. freeBindings(parser, bindings);
  2812. return result;
  2813. }
  2814. poolFinish(&parser->m_tempPool);
  2815. if (parser->m_startElementHandler) {
  2816. parser->m_startElementHandler(parser->m_handlerArg, name.str,
  2817. (const XML_Char **)parser->m_atts);
  2818. noElmHandlers = XML_FALSE;
  2819. }
  2820. if (parser->m_endElementHandler) {
  2821. if (parser->m_startElementHandler)
  2822. *eventPP = *eventEndPP;
  2823. parser->m_endElementHandler(parser->m_handlerArg, name.str);
  2824. noElmHandlers = XML_FALSE;
  2825. }
  2826. if (noElmHandlers && parser->m_defaultHandler)
  2827. reportDefault(parser, enc, s, next);
  2828. poolClear(&parser->m_tempPool);
  2829. freeBindings(parser, bindings);
  2830. }
  2831. if ((parser->m_tagLevel == 0)
  2832. && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
  2833. if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
  2834. parser->m_processor = epilogProcessor;
  2835. else
  2836. return epilogProcessor(parser, next, end, nextPtr);
  2837. }
  2838. break;
  2839. case XML_TOK_END_TAG:
  2840. if (parser->m_tagLevel == startTagLevel)
  2841. return XML_ERROR_ASYNC_ENTITY;
  2842. else {
  2843. int len;
  2844. const char *rawName;
  2845. TAG *tag = parser->m_tagStack;
  2846. rawName = s + enc->minBytesPerChar * 2;
  2847. len = XmlNameLength(enc, rawName);
  2848. if (len != tag->rawNameLength
  2849. || memcmp(tag->rawName, rawName, len) != 0) {
  2850. *eventPP = rawName;
  2851. return XML_ERROR_TAG_MISMATCH;
  2852. }
  2853. parser->m_tagStack = tag->parent;
  2854. tag->parent = parser->m_freeTagList;
  2855. parser->m_freeTagList = tag;
  2856. --parser->m_tagLevel;
  2857. if (parser->m_endElementHandler) {
  2858. const XML_Char *localPart;
  2859. const XML_Char *prefix;
  2860. XML_Char *uri;
  2861. localPart = tag->name.localPart;
  2862. if (parser->m_ns && localPart) {
  2863. /* localPart and prefix may have been overwritten in
  2864. tag->name.str, since this points to the binding->uri
  2865. buffer which gets reused; so we have to add them again
  2866. */
  2867. uri = (XML_Char *)tag->name.str + tag->name.uriLen;
  2868. /* don't need to check for space - already done in storeAtts() */
  2869. while (*localPart)
  2870. *uri++ = *localPart++;
  2871. prefix = tag->name.prefix;
  2872. if (parser->m_ns_triplets && prefix) {
  2873. *uri++ = parser->m_namespaceSeparator;
  2874. while (*prefix)
  2875. *uri++ = *prefix++;
  2876. }
  2877. *uri = XML_T('\0');
  2878. }
  2879. parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
  2880. } else if (parser->m_defaultHandler)
  2881. reportDefault(parser, enc, s, next);
  2882. while (tag->bindings) {
  2883. BINDING *b = tag->bindings;
  2884. if (parser->m_endNamespaceDeclHandler)
  2885. parser->m_endNamespaceDeclHandler(parser->m_handlerArg,
  2886. b->prefix->name);
  2887. tag->bindings = tag->bindings->nextTagBinding;
  2888. b->nextTagBinding = parser->m_freeBindingList;
  2889. parser->m_freeBindingList = b;
  2890. b->prefix->binding = b->prevPrefixBinding;
  2891. }
  2892. if ((parser->m_tagLevel == 0)
  2893. && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
  2894. if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
  2895. parser->m_processor = epilogProcessor;
  2896. else
  2897. return epilogProcessor(parser, next, end, nextPtr);
  2898. }
  2899. }
  2900. break;
  2901. case XML_TOK_CHAR_REF: {
  2902. int n = XmlCharRefNumber(enc, s);
  2903. if (n < 0)
  2904. return XML_ERROR_BAD_CHAR_REF;
  2905. if (parser->m_characterDataHandler) {
  2906. XML_Char buf[XML_ENCODE_MAX];
  2907. parser->m_characterDataHandler(parser->m_handlerArg, buf,
  2908. XmlEncode(n, (ICHAR *)buf));
  2909. } else if (parser->m_defaultHandler)
  2910. reportDefault(parser, enc, s, next);
  2911. } break;
  2912. case XML_TOK_XML_DECL:
  2913. return XML_ERROR_MISPLACED_XML_PI;
  2914. case XML_TOK_DATA_NEWLINE:
  2915. if (parser->m_characterDataHandler) {
  2916. XML_Char c = 0xA;
  2917. parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
  2918. } else if (parser->m_defaultHandler)
  2919. reportDefault(parser, enc, s, next);
  2920. break;
  2921. case XML_TOK_CDATA_SECT_OPEN: {
  2922. enum XML_Error result;
  2923. if (parser->m_startCdataSectionHandler)
  2924. parser->m_startCdataSectionHandler(parser->m_handlerArg);
  2925. /* BEGIN disabled code */
  2926. /* Suppose you doing a transformation on a document that involves
  2927. changing only the character data. You set up a defaultHandler
  2928. and a characterDataHandler. The defaultHandler simply copies
  2929. characters through. The characterDataHandler does the
  2930. transformation and writes the characters out escaping them as
  2931. necessary. This case will fail to work if we leave out the
  2932. following two lines (because & and < inside CDATA sections will
  2933. be incorrectly escaped).
  2934. However, now we have a start/endCdataSectionHandler, so it seems
  2935. easier to let the user deal with this.
  2936. */
  2937. else if ((0) && parser->m_characterDataHandler)
  2938. parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  2939. 0);
  2940. /* END disabled code */
  2941. else if (parser->m_defaultHandler)
  2942. reportDefault(parser, enc, s, next);
  2943. result
  2944. = doCdataSection(parser, enc, &next, end, nextPtr, haveMore, account);
  2945. if (result != XML_ERROR_NONE)
  2946. return result;
  2947. else if (! next) {
  2948. parser->m_processor = cdataSectionProcessor;
  2949. return result;
  2950. }
  2951. } break;
  2952. case XML_TOK_TRAILING_RSQB:
  2953. if (haveMore) {
  2954. *nextPtr = s;
  2955. return XML_ERROR_NONE;
  2956. }
  2957. if (parser->m_characterDataHandler) {
  2958. if (MUST_CONVERT(enc, s)) {
  2959. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  2960. XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  2961. parser->m_characterDataHandler(
  2962. parser->m_handlerArg, parser->m_dataBuf,
  2963. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  2964. } else
  2965. parser->m_characterDataHandler(
  2966. parser->m_handlerArg, (const XML_Char *)s,
  2967. (int)((const XML_Char *)end - (const XML_Char *)s));
  2968. } else if (parser->m_defaultHandler)
  2969. reportDefault(parser, enc, s, end);
  2970. /* We are at the end of the final buffer, should we check for
  2971. XML_SUSPENDED, XML_FINISHED?
  2972. */
  2973. if (startTagLevel == 0) {
  2974. *eventPP = end;
  2975. return XML_ERROR_NO_ELEMENTS;
  2976. }
  2977. if (parser->m_tagLevel != startTagLevel) {
  2978. *eventPP = end;
  2979. return XML_ERROR_ASYNC_ENTITY;
  2980. }
  2981. *nextPtr = end;
  2982. return XML_ERROR_NONE;
  2983. case XML_TOK_DATA_CHARS: {
  2984. XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
  2985. if (charDataHandler) {
  2986. if (MUST_CONVERT(enc, s)) {
  2987. for (;;) {
  2988. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  2989. const enum XML_Convert_Result convert_res = XmlConvert(
  2990. enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  2991. *eventEndPP = s;
  2992. charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  2993. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  2994. if ((convert_res == XML_CONVERT_COMPLETED)
  2995. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  2996. break;
  2997. *eventPP = s;
  2998. }
  2999. } else
  3000. charDataHandler(parser->m_handlerArg, (const XML_Char *)s,
  3001. (int)((const XML_Char *)next - (const XML_Char *)s));
  3002. } else if (parser->m_defaultHandler)
  3003. reportDefault(parser, enc, s, next);
  3004. } break;
  3005. case XML_TOK_PI:
  3006. if (! reportProcessingInstruction(parser, enc, s, next))
  3007. return XML_ERROR_NO_MEMORY;
  3008. break;
  3009. case XML_TOK_COMMENT:
  3010. if (! reportComment(parser, enc, s, next))
  3011. return XML_ERROR_NO_MEMORY;
  3012. break;
  3013. default:
  3014. /* All of the tokens produced by XmlContentTok() have their own
  3015. * explicit cases, so this default is not strictly necessary.
  3016. * However it is a useful safety net, so we retain the code and
  3017. * simply exclude it from the coverage tests.
  3018. *
  3019. * LCOV_EXCL_START
  3020. */
  3021. if (parser->m_defaultHandler)
  3022. reportDefault(parser, enc, s, next);
  3023. break;
  3024. /* LCOV_EXCL_STOP */
  3025. }
  3026. *eventPP = s = next;
  3027. switch (parser->m_parsingStatus.parsing) {
  3028. case XML_SUSPENDED:
  3029. *nextPtr = next;
  3030. return XML_ERROR_NONE;
  3031. case XML_FINISHED:
  3032. return XML_ERROR_ABORTED;
  3033. default:;
  3034. }
  3035. }
  3036. /* not reached */
  3037. }
  3038. /* This function does not call free() on the allocated memory, merely
  3039. * moving it to the parser's m_freeBindingList where it can be freed or
  3040. * reused as appropriate.
  3041. */
  3042. static void
  3043. freeBindings(XML_Parser parser, BINDING *bindings) {
  3044. while (bindings) {
  3045. BINDING *b = bindings;
  3046. /* m_startNamespaceDeclHandler will have been called for this
  3047. * binding in addBindings(), so call the end handler now.
  3048. */
  3049. if (parser->m_endNamespaceDeclHandler)
  3050. parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
  3051. bindings = bindings->nextTagBinding;
  3052. b->nextTagBinding = parser->m_freeBindingList;
  3053. parser->m_freeBindingList = b;
  3054. b->prefix->binding = b->prevPrefixBinding;
  3055. }
  3056. }
  3057. /* Precondition: all arguments must be non-NULL;
  3058. Purpose:
  3059. - normalize attributes
  3060. - check attributes for well-formedness
  3061. - generate namespace aware attribute names (URI, prefix)
  3062. - build list of attributes for startElementHandler
  3063. - default attributes
  3064. - process namespace declarations (check and report them)
  3065. - generate namespace aware element name (URI, prefix)
  3066. */
  3067. static enum XML_Error
  3068. storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
  3069. TAG_NAME *tagNamePtr, BINDING **bindingsPtr,
  3070. enum XML_Account account) {
  3071. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  3072. ELEMENT_TYPE *elementType;
  3073. int nDefaultAtts;
  3074. const XML_Char **appAtts; /* the attribute list for the application */
  3075. int attIndex = 0;
  3076. int prefixLen;
  3077. int i;
  3078. int n;
  3079. XML_Char *uri;
  3080. int nPrefixes = 0;
  3081. BINDING *binding;
  3082. const XML_Char *localPart;
  3083. /* lookup the element type name */
  3084. elementType
  3085. = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);
  3086. if (! elementType) {
  3087. const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
  3088. if (! name)
  3089. return XML_ERROR_NO_MEMORY;
  3090. elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
  3091. sizeof(ELEMENT_TYPE));
  3092. if (! elementType)
  3093. return XML_ERROR_NO_MEMORY;
  3094. if (parser->m_ns && ! setElementTypePrefix(parser, elementType))
  3095. return XML_ERROR_NO_MEMORY;
  3096. }
  3097. nDefaultAtts = elementType->nDefaultAtts;
  3098. /* get the attributes from the tokenizer */
  3099. n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
  3100. /* Detect and prevent integer overflow */
  3101. if (n > INT_MAX - nDefaultAtts) {
  3102. return XML_ERROR_NO_MEMORY;
  3103. }
  3104. if (n + nDefaultAtts > parser->m_attsSize) {
  3105. int oldAttsSize = parser->m_attsSize;
  3106. ATTRIBUTE *temp;
  3107. #ifdef XML_ATTR_INFO
  3108. XML_AttrInfo *temp2;
  3109. #endif
  3110. /* Detect and prevent integer overflow */
  3111. if ((nDefaultAtts > INT_MAX - INIT_ATTS_SIZE)
  3112. || (n > INT_MAX - (nDefaultAtts + INIT_ATTS_SIZE))) {
  3113. return XML_ERROR_NO_MEMORY;
  3114. }
  3115. parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
  3116. /* Detect and prevent integer overflow.
  3117. * The preprocessor guard addresses the "always false" warning
  3118. * from -Wtype-limits on platforms where
  3119. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3120. #if UINT_MAX >= SIZE_MAX
  3121. if ((unsigned)parser->m_attsSize > (size_t)(-1) / sizeof(ATTRIBUTE)) {
  3122. parser->m_attsSize = oldAttsSize;
  3123. return XML_ERROR_NO_MEMORY;
  3124. }
  3125. #endif
  3126. temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts,
  3127. parser->m_attsSize * sizeof(ATTRIBUTE));
  3128. if (temp == NULL) {
  3129. parser->m_attsSize = oldAttsSize;
  3130. return XML_ERROR_NO_MEMORY;
  3131. }
  3132. parser->m_atts = temp;
  3133. #ifdef XML_ATTR_INFO
  3134. /* Detect and prevent integer overflow.
  3135. * The preprocessor guard addresses the "always false" warning
  3136. * from -Wtype-limits on platforms where
  3137. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3138. # if UINT_MAX >= SIZE_MAX
  3139. if ((unsigned)parser->m_attsSize > (size_t)(-1) / sizeof(XML_AttrInfo)) {
  3140. parser->m_attsSize = oldAttsSize;
  3141. return XML_ERROR_NO_MEMORY;
  3142. }
  3143. # endif
  3144. temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo,
  3145. parser->m_attsSize * sizeof(XML_AttrInfo));
  3146. if (temp2 == NULL) {
  3147. parser->m_attsSize = oldAttsSize;
  3148. return XML_ERROR_NO_MEMORY;
  3149. }
  3150. parser->m_attInfo = temp2;
  3151. #endif
  3152. if (n > oldAttsSize)
  3153. XmlGetAttributes(enc, attStr, n, parser->m_atts);
  3154. }
  3155. appAtts = (const XML_Char **)parser->m_atts;
  3156. for (i = 0; i < n; i++) {
  3157. ATTRIBUTE *currAtt = &parser->m_atts[i];
  3158. #ifdef XML_ATTR_INFO
  3159. XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
  3160. #endif
  3161. /* add the name and value to the attribute list */
  3162. ATTRIBUTE_ID *attId
  3163. = getAttributeId(parser, enc, currAtt->name,
  3164. currAtt->name + XmlNameLength(enc, currAtt->name));
  3165. if (! attId)
  3166. return XML_ERROR_NO_MEMORY;
  3167. #ifdef XML_ATTR_INFO
  3168. currAttInfo->nameStart
  3169. = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
  3170. currAttInfo->nameEnd
  3171. = currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);
  3172. currAttInfo->valueStart = parser->m_parseEndByteIndex
  3173. - (parser->m_parseEndPtr - currAtt->valuePtr);
  3174. currAttInfo->valueEnd = parser->m_parseEndByteIndex
  3175. - (parser->m_parseEndPtr - currAtt->valueEnd);
  3176. #endif
  3177. /* Detect duplicate attributes by their QNames. This does not work when
  3178. namespace processing is turned on and different prefixes for the same
  3179. namespace are used. For this case we have a check further down.
  3180. */
  3181. if ((attId->name)[-1]) {
  3182. if (enc == parser->m_encoding)
  3183. parser->m_eventPtr = parser->m_atts[i].name;
  3184. return XML_ERROR_DUPLICATE_ATTRIBUTE;
  3185. }
  3186. (attId->name)[-1] = 1;
  3187. appAtts[attIndex++] = attId->name;
  3188. if (! parser->m_atts[i].normalized) {
  3189. enum XML_Error result;
  3190. XML_Bool isCdata = XML_TRUE;
  3191. /* figure out whether declared as other than CDATA */
  3192. if (attId->maybeTokenized) {
  3193. int j;
  3194. for (j = 0; j < nDefaultAtts; j++) {
  3195. if (attId == elementType->defaultAtts[j].id) {
  3196. isCdata = elementType->defaultAtts[j].isCdata;
  3197. break;
  3198. }
  3199. }
  3200. }
  3201. /* normalize the attribute value */
  3202. result = storeAttributeValue(
  3203. parser, enc, isCdata, parser->m_atts[i].valuePtr,
  3204. parser->m_atts[i].valueEnd, &parser->m_tempPool, account);
  3205. if (result)
  3206. return result;
  3207. appAtts[attIndex] = poolStart(&parser->m_tempPool);
  3208. poolFinish(&parser->m_tempPool);
  3209. } else {
  3210. /* the value did not need normalizing */
  3211. appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,
  3212. parser->m_atts[i].valuePtr,
  3213. parser->m_atts[i].valueEnd);
  3214. if (appAtts[attIndex] == 0)
  3215. return XML_ERROR_NO_MEMORY;
  3216. poolFinish(&parser->m_tempPool);
  3217. }
  3218. /* handle prefixed attribute names */
  3219. if (attId->prefix) {
  3220. if (attId->xmlns) {
  3221. /* deal with namespace declarations here */
  3222. enum XML_Error result = addBinding(parser, attId->prefix, attId,
  3223. appAtts[attIndex], bindingsPtr);
  3224. if (result)
  3225. return result;
  3226. --attIndex;
  3227. } else {
  3228. /* deal with other prefixed names later */
  3229. attIndex++;
  3230. nPrefixes++;
  3231. (attId->name)[-1] = 2;
  3232. }
  3233. } else
  3234. attIndex++;
  3235. }
  3236. /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
  3237. parser->m_nSpecifiedAtts = attIndex;
  3238. if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
  3239. for (i = 0; i < attIndex; i += 2)
  3240. if (appAtts[i] == elementType->idAtt->name) {
  3241. parser->m_idAttIndex = i;
  3242. break;
  3243. }
  3244. } else
  3245. parser->m_idAttIndex = -1;
  3246. /* do attribute defaulting */
  3247. for (i = 0; i < nDefaultAtts; i++) {
  3248. const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
  3249. if (! (da->id->name)[-1] && da->value) {
  3250. if (da->id->prefix) {
  3251. if (da->id->xmlns) {
  3252. enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
  3253. da->value, bindingsPtr);
  3254. if (result)
  3255. return result;
  3256. } else {
  3257. (da->id->name)[-1] = 2;
  3258. nPrefixes++;
  3259. appAtts[attIndex++] = da->id->name;
  3260. appAtts[attIndex++] = da->value;
  3261. }
  3262. } else {
  3263. (da->id->name)[-1] = 1;
  3264. appAtts[attIndex++] = da->id->name;
  3265. appAtts[attIndex++] = da->value;
  3266. }
  3267. }
  3268. }
  3269. appAtts[attIndex] = 0;
  3270. /* expand prefixed attribute names, check for duplicates,
  3271. and clear flags that say whether attributes were specified */
  3272. i = 0;
  3273. if (nPrefixes) {
  3274. int j; /* hash table index */
  3275. unsigned long version = parser->m_nsAttsVersion;
  3276. /* Detect and prevent invalid shift */
  3277. if (parser->m_nsAttsPower >= sizeof(unsigned int) * 8 /* bits per byte */) {
  3278. return XML_ERROR_NO_MEMORY;
  3279. }
  3280. { // WINSCP
  3281. unsigned int nsAttsSize = 1u << parser->m_nsAttsPower;
  3282. unsigned char oldNsAttsPower = parser->m_nsAttsPower;
  3283. /* size of hash table must be at least 2 * (# of prefixed attributes) */
  3284. if ((nPrefixes << 1)
  3285. >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
  3286. NS_ATT *temp;
  3287. /* hash table size must also be a power of 2 and >= 8 */
  3288. while (nPrefixes >> parser->m_nsAttsPower++)
  3289. ;
  3290. if (parser->m_nsAttsPower < 3)
  3291. parser->m_nsAttsPower = 3;
  3292. /* Detect and prevent invalid shift */
  3293. if (parser->m_nsAttsPower >= sizeof(nsAttsSize) * 8 /* bits per byte */) {
  3294. /* Restore actual size of memory in m_nsAtts */
  3295. parser->m_nsAttsPower = oldNsAttsPower;
  3296. return XML_ERROR_NO_MEMORY;
  3297. }
  3298. nsAttsSize = 1u << parser->m_nsAttsPower;
  3299. /* Detect and prevent integer overflow.
  3300. * The preprocessor guard addresses the "always false" warning
  3301. * from -Wtype-limits on platforms where
  3302. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3303. #if UINT_MAX >= SIZE_MAX
  3304. if (nsAttsSize > (size_t)(-1) / sizeof(NS_ATT)) {
  3305. /* Restore actual size of memory in m_nsAtts */
  3306. parser->m_nsAttsPower = oldNsAttsPower;
  3307. return XML_ERROR_NO_MEMORY;
  3308. }
  3309. #endif
  3310. temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts,
  3311. nsAttsSize * sizeof(NS_ATT));
  3312. if (! temp) {
  3313. /* Restore actual size of memory in m_nsAtts */
  3314. parser->m_nsAttsPower = oldNsAttsPower;
  3315. return XML_ERROR_NO_MEMORY;
  3316. }
  3317. parser->m_nsAtts = temp;
  3318. version = 0; /* force re-initialization of m_nsAtts hash table */
  3319. }
  3320. /* using a version flag saves us from initializing m_nsAtts every time */
  3321. if (! version) { /* initialize version flags when version wraps around */
  3322. version = INIT_ATTS_VERSION;
  3323. for (j = nsAttsSize; j != 0;)
  3324. parser->m_nsAtts[--j].version = version;
  3325. }
  3326. parser->m_nsAttsVersion = --version;
  3327. /* expand prefixed names and check for duplicates */
  3328. for (; i < attIndex; i += 2) {
  3329. const XML_Char *s = appAtts[i];
  3330. if (s[-1] == 2) { /* prefixed */
  3331. ATTRIBUTE_ID *id;
  3332. const BINDING *b;
  3333. unsigned long uriHash;
  3334. struct siphash sip_state;
  3335. struct sipkey sip_key;
  3336. copy_salt_to_sipkey(parser, &sip_key);
  3337. sip24_init(&sip_state, &sip_key);
  3338. ((XML_Char *)s)[-1] = 0; /* clear flag */
  3339. id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
  3340. if (! id || ! id->prefix) {
  3341. /* This code is walking through the appAtts array, dealing
  3342. * with (in this case) a prefixed attribute name. To be in
  3343. * the array, the attribute must have already been bound, so
  3344. * has to have passed through the hash table lookup once
  3345. * already. That implies that an entry for it already
  3346. * exists, so the lookup above will return a pointer to
  3347. * already allocated memory. There is no opportunaity for
  3348. * the allocator to fail, so the condition above cannot be
  3349. * fulfilled.
  3350. *
  3351. * Since it is difficult to be certain that the above
  3352. * analysis is complete, we retain the test and merely
  3353. * remove the code from coverage tests.
  3354. */
  3355. return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
  3356. }
  3357. b = id->prefix->binding;
  3358. if (! b)
  3359. return XML_ERROR_UNBOUND_PREFIX;
  3360. for (j = 0; j < b->uriLen; j++) {
  3361. const XML_Char c = b->uri[j];
  3362. if (! poolAppendChar(&parser->m_tempPool, c))
  3363. return XML_ERROR_NO_MEMORY;
  3364. }
  3365. sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
  3366. while (*s++ != XML_T(ASCII_COLON))
  3367. ;
  3368. sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
  3369. do { /* copies null terminator */
  3370. if (! poolAppendChar(&parser->m_tempPool, *s))
  3371. return XML_ERROR_NO_MEMORY;
  3372. } while (*s++);
  3373. uriHash = (unsigned long)sip24_final(&sip_state);
  3374. { /* Check hash table for duplicate of expanded name (uriName).
  3375. Derived from code in lookup(parser, HASH_TABLE *table, ...).
  3376. */
  3377. unsigned char step = 0;
  3378. unsigned long mask = nsAttsSize - 1;
  3379. j = uriHash & mask; /* index into hash table */
  3380. while (parser->m_nsAtts[j].version == version) {
  3381. /* for speed we compare stored hash values first */
  3382. if (uriHash == parser->m_nsAtts[j].hash) {
  3383. const XML_Char *s1 = poolStart(&parser->m_tempPool);
  3384. const XML_Char *s2 = parser->m_nsAtts[j].uriName;
  3385. /* s1 is null terminated, but not s2 */
  3386. for (; *s1 == *s2 && *s1 != 0; s1++, s2++)
  3387. ;
  3388. if (*s1 == 0)
  3389. return XML_ERROR_DUPLICATE_ATTRIBUTE;
  3390. }
  3391. if (! step)
  3392. step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
  3393. j < step ? (j += nsAttsSize - step) : (j -= step);
  3394. }
  3395. }
  3396. if (parser->m_ns_triplets) { /* append namespace separator and prefix */
  3397. parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
  3398. s = b->prefix->name;
  3399. do {
  3400. if (! poolAppendChar(&parser->m_tempPool, *s))
  3401. return XML_ERROR_NO_MEMORY;
  3402. } while (*s++);
  3403. }
  3404. /* store expanded name in attribute list */
  3405. s = poolStart(&parser->m_tempPool);
  3406. poolFinish(&parser->m_tempPool);
  3407. appAtts[i] = s;
  3408. /* fill empty slot with new version, uriName and hash value */
  3409. parser->m_nsAtts[j].version = version;
  3410. parser->m_nsAtts[j].hash = uriHash;
  3411. parser->m_nsAtts[j].uriName = s;
  3412. if (! --nPrefixes) {
  3413. i += 2;
  3414. break;
  3415. }
  3416. } else /* not prefixed */
  3417. ((XML_Char *)s)[-1] = 0; /* clear flag */
  3418. }
  3419. } // WINSCP
  3420. }
  3421. /* clear flags for the remaining attributes */
  3422. for (; i < attIndex; i += 2)
  3423. ((XML_Char *)(appAtts[i]))[-1] = 0;
  3424. for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
  3425. binding->attId->name[-1] = 0;
  3426. if (! parser->m_ns)
  3427. return XML_ERROR_NONE;
  3428. /* expand the element type name */
  3429. if (elementType->prefix) {
  3430. binding = elementType->prefix->binding;
  3431. if (! binding)
  3432. return XML_ERROR_UNBOUND_PREFIX;
  3433. localPart = tagNamePtr->str;
  3434. while (*localPart++ != XML_T(ASCII_COLON))
  3435. ;
  3436. } else if (dtd->defaultPrefix.binding) {
  3437. binding = dtd->defaultPrefix.binding;
  3438. localPart = tagNamePtr->str;
  3439. } else
  3440. return XML_ERROR_NONE;
  3441. prefixLen = 0;
  3442. if (parser->m_ns_triplets && binding->prefix->name) {
  3443. for (; binding->prefix->name[prefixLen++];)
  3444. ; /* prefixLen includes null terminator */
  3445. }
  3446. tagNamePtr->localPart = localPart;
  3447. tagNamePtr->uriLen = binding->uriLen;
  3448. tagNamePtr->prefix = binding->prefix->name;
  3449. tagNamePtr->prefixLen = prefixLen;
  3450. for (i = 0; localPart[i++];)
  3451. ; /* i includes null terminator */
  3452. /* Detect and prevent integer overflow */
  3453. if (binding->uriLen > INT_MAX - prefixLen
  3454. || i > INT_MAX - (binding->uriLen + prefixLen)) {
  3455. return XML_ERROR_NO_MEMORY;
  3456. }
  3457. n = i + binding->uriLen + prefixLen;
  3458. if (n > binding->uriAlloc) {
  3459. TAG *p;
  3460. /* Detect and prevent integer overflow */
  3461. if (n > INT_MAX - EXPAND_SPARE) {
  3462. return XML_ERROR_NO_MEMORY;
  3463. }
  3464. /* Detect and prevent integer overflow.
  3465. * The preprocessor guard addresses the "always false" warning
  3466. * from -Wtype-limits on platforms where
  3467. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3468. #if UINT_MAX >= SIZE_MAX
  3469. if ((unsigned)(n + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
  3470. return XML_ERROR_NO_MEMORY;
  3471. }
  3472. #endif
  3473. uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
  3474. if (! uri)
  3475. return XML_ERROR_NO_MEMORY;
  3476. binding->uriAlloc = n + EXPAND_SPARE;
  3477. memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
  3478. for (p = parser->m_tagStack; p; p = p->parent)
  3479. if (p->name.str == binding->uri)
  3480. p->name.str = uri;
  3481. FREE(parser, binding->uri);
  3482. binding->uri = uri;
  3483. }
  3484. /* if m_namespaceSeparator != '\0' then uri includes it already */
  3485. uri = binding->uri + binding->uriLen;
  3486. memcpy(uri, localPart, i * sizeof(XML_Char));
  3487. /* we always have a namespace separator between localPart and prefix */
  3488. if (prefixLen) {
  3489. uri += i - 1;
  3490. *uri = parser->m_namespaceSeparator; /* replace null terminator */
  3491. memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
  3492. }
  3493. tagNamePtr->str = binding->uri;
  3494. return XML_ERROR_NONE;
  3495. }
  3496. static XML_Bool
  3497. is_rfc3986_uri_char(XML_Char candidate) {
  3498. // For the RFC 3986 ANBF grammar see
  3499. // https://datatracker.ietf.org/doc/html/rfc3986#appendix-A
  3500. switch (candidate) {
  3501. // From rule "ALPHA" (uppercase half)
  3502. case 'A':
  3503. case 'B':
  3504. case 'C':
  3505. case 'D':
  3506. case 'E':
  3507. case 'F':
  3508. case 'G':
  3509. case 'H':
  3510. case 'I':
  3511. case 'J':
  3512. case 'K':
  3513. case 'L':
  3514. case 'M':
  3515. case 'N':
  3516. case 'O':
  3517. case 'P':
  3518. case 'Q':
  3519. case 'R':
  3520. case 'S':
  3521. case 'T':
  3522. case 'U':
  3523. case 'V':
  3524. case 'W':
  3525. case 'X':
  3526. case 'Y':
  3527. case 'Z':
  3528. // From rule "ALPHA" (lowercase half)
  3529. case 'a':
  3530. case 'b':
  3531. case 'c':
  3532. case 'd':
  3533. case 'e':
  3534. case 'f':
  3535. case 'g':
  3536. case 'h':
  3537. case 'i':
  3538. case 'j':
  3539. case 'k':
  3540. case 'l':
  3541. case 'm':
  3542. case 'n':
  3543. case 'o':
  3544. case 'p':
  3545. case 'q':
  3546. case 'r':
  3547. case 's':
  3548. case 't':
  3549. case 'u':
  3550. case 'v':
  3551. case 'w':
  3552. case 'x':
  3553. case 'y':
  3554. case 'z':
  3555. // From rule "DIGIT"
  3556. case '0':
  3557. case '1':
  3558. case '2':
  3559. case '3':
  3560. case '4':
  3561. case '5':
  3562. case '6':
  3563. case '7':
  3564. case '8':
  3565. case '9':
  3566. // From rule "pct-encoded"
  3567. case '%':
  3568. // From rule "unreserved"
  3569. case '-':
  3570. case '.':
  3571. case '_':
  3572. case '~':
  3573. // From rule "gen-delims"
  3574. case ':':
  3575. case '/':
  3576. case '?':
  3577. case '#':
  3578. case '[':
  3579. case ']':
  3580. case '@':
  3581. // From rule "sub-delims"
  3582. case '!':
  3583. case '$':
  3584. case '&':
  3585. case '\'':
  3586. case '(':
  3587. case ')':
  3588. case '*':
  3589. case '+':
  3590. case ',':
  3591. case ';':
  3592. case '=':
  3593. return XML_TRUE;
  3594. default:
  3595. return XML_FALSE;
  3596. }
  3597. }
  3598. /* addBinding() overwrites the value of prefix->binding without checking.
  3599. Therefore one must keep track of the old value outside of addBinding().
  3600. */
  3601. static enum XML_Error
  3602. addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
  3603. const XML_Char *uri, BINDING **bindingsPtr) {
  3604. // "http://www.w3.org/XML/1998/namespace"
  3605. static const XML_Char xmlNamespace[]
  3606. = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON,
  3607. ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
  3608. ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o,
  3609. ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M,
  3610. ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9,
  3611. ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m,
  3612. ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
  3613. ASCII_e, '\0'};
  3614. static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;
  3615. // "http://www.w3.org/2000/xmlns/"
  3616. static const XML_Char xmlnsNamespace[]
  3617. = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
  3618. ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,
  3619. ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH,
  3620. ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x,
  3621. ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'};
  3622. static const int xmlnsLen
  3623. = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;
  3624. XML_Bool mustBeXML = XML_FALSE;
  3625. XML_Bool isXML = XML_TRUE;
  3626. XML_Bool isXMLNS = XML_TRUE;
  3627. BINDING *b;
  3628. int len;
  3629. /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
  3630. if (*uri == XML_T('\0') && prefix->name)
  3631. return XML_ERROR_UNDECLARING_PREFIX;
  3632. if (prefix->name && prefix->name[0] == XML_T(ASCII_x)
  3633. && prefix->name[1] == XML_T(ASCII_m)
  3634. && prefix->name[2] == XML_T(ASCII_l)) {
  3635. /* Not allowed to bind xmlns */
  3636. if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)
  3637. && prefix->name[5] == XML_T('\0'))
  3638. return XML_ERROR_RESERVED_PREFIX_XMLNS;
  3639. if (prefix->name[3] == XML_T('\0'))
  3640. mustBeXML = XML_TRUE;
  3641. }
  3642. for (len = 0; uri[len]; len++) {
  3643. if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
  3644. isXML = XML_FALSE;
  3645. if (! mustBeXML && isXMLNS
  3646. && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
  3647. isXMLNS = XML_FALSE;
  3648. // NOTE: While Expat does not validate namespace URIs against RFC 3986
  3649. // today (and is not REQUIRED to do so with regard to the XML 1.0
  3650. // namespaces specification) we have to at least make sure, that
  3651. // the application on top of Expat (that is likely splitting expanded
  3652. // element names ("qualified names") of form
  3653. // "[uri sep] local [sep prefix] '\0'" back into 1, 2 or 3 pieces
  3654. // in its element handler code) cannot be confused by an attacker
  3655. // putting additional namespace separator characters into namespace
  3656. // declarations. That would be ambiguous and not to be expected.
  3657. //
  3658. // While the HTML API docs of function XML_ParserCreateNS have been
  3659. // advising against use of a namespace separator character that can
  3660. // appear in a URI for >20 years now, some widespread applications
  3661. // are using URI characters (':' (colon) in particular) for a
  3662. // namespace separator, in practice. To keep these applications
  3663. // functional, we only reject namespaces URIs containing the
  3664. // application-chosen namespace separator if the chosen separator
  3665. // is a non-URI character with regard to RFC 3986.
  3666. if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)
  3667. && ! is_rfc3986_uri_char(uri[len])) {
  3668. return XML_ERROR_SYNTAX;
  3669. }
  3670. }
  3671. isXML = isXML && len == xmlLen;
  3672. isXMLNS = isXMLNS && len == xmlnsLen;
  3673. if (mustBeXML != isXML)
  3674. return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
  3675. : XML_ERROR_RESERVED_NAMESPACE_URI;
  3676. if (isXMLNS)
  3677. return XML_ERROR_RESERVED_NAMESPACE_URI;
  3678. if (parser->m_namespaceSeparator)
  3679. len++;
  3680. if (parser->m_freeBindingList) {
  3681. b = parser->m_freeBindingList;
  3682. if (len > b->uriAlloc) {
  3683. /* Detect and prevent integer overflow */
  3684. if (len > INT_MAX - EXPAND_SPARE) {
  3685. return XML_ERROR_NO_MEMORY;
  3686. }
  3687. /* Detect and prevent integer overflow.
  3688. * The preprocessor guard addresses the "always false" warning
  3689. * from -Wtype-limits on platforms where
  3690. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3691. #if UINT_MAX >= SIZE_MAX
  3692. if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
  3693. return XML_ERROR_NO_MEMORY;
  3694. }
  3695. #endif
  3696. { // WINSCP
  3697. XML_Char *temp = (XML_Char *)REALLOC(
  3698. parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));
  3699. if (temp == NULL)
  3700. return XML_ERROR_NO_MEMORY;
  3701. b->uri = temp;
  3702. b->uriAlloc = len + EXPAND_SPARE;
  3703. } // WINSCP
  3704. }
  3705. parser->m_freeBindingList = b->nextTagBinding;
  3706. } else {
  3707. b = (BINDING *)MALLOC(parser, sizeof(BINDING));
  3708. if (! b)
  3709. return XML_ERROR_NO_MEMORY;
  3710. /* Detect and prevent integer overflow */
  3711. if (len > INT_MAX - EXPAND_SPARE) {
  3712. return XML_ERROR_NO_MEMORY;
  3713. }
  3714. /* Detect and prevent integer overflow.
  3715. * The preprocessor guard addresses the "always false" warning
  3716. * from -Wtype-limits on platforms where
  3717. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3718. #if UINT_MAX >= SIZE_MAX
  3719. if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
  3720. return XML_ERROR_NO_MEMORY;
  3721. }
  3722. #endif
  3723. b->uri
  3724. = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
  3725. if (! b->uri) {
  3726. FREE(parser, b);
  3727. return XML_ERROR_NO_MEMORY;
  3728. }
  3729. b->uriAlloc = len + EXPAND_SPARE;
  3730. }
  3731. b->uriLen = len;
  3732. memcpy(b->uri, uri, len * sizeof(XML_Char));
  3733. if (parser->m_namespaceSeparator)
  3734. b->uri[len - 1] = parser->m_namespaceSeparator;
  3735. b->prefix = prefix;
  3736. b->attId = attId;
  3737. b->prevPrefixBinding = prefix->binding;
  3738. /* NULL binding when default namespace undeclared */
  3739. if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
  3740. prefix->binding = NULL;
  3741. else
  3742. prefix->binding = b;
  3743. b->nextTagBinding = *bindingsPtr;
  3744. *bindingsPtr = b;
  3745. /* if attId == NULL then we are not starting a namespace scope */
  3746. if (attId && parser->m_startNamespaceDeclHandler)
  3747. parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
  3748. prefix->binding ? uri : 0);
  3749. return XML_ERROR_NONE;
  3750. }
  3751. /* The idea here is to avoid using stack for each CDATA section when
  3752. the whole file is parsed with one call.
  3753. */
  3754. static enum XML_Error PTRCALL
  3755. cdataSectionProcessor(XML_Parser parser, const char *start, const char *end,
  3756. const char **endPtr) {
  3757. enum XML_Error result = doCdataSection(
  3758. parser, parser->m_encoding, &start, end, endPtr,
  3759. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);
  3760. if (result != XML_ERROR_NONE)
  3761. return result;
  3762. if (start) {
  3763. if (parser->m_parentParser) { /* we are parsing an external entity */
  3764. parser->m_processor = externalEntityContentProcessor;
  3765. return externalEntityContentProcessor(parser, start, end, endPtr);
  3766. } else {
  3767. parser->m_processor = contentProcessor;
  3768. return contentProcessor(parser, start, end, endPtr);
  3769. }
  3770. }
  3771. return result;
  3772. }
  3773. /* startPtr gets set to non-null if the section is closed, and to null if
  3774. the section is not yet closed.
  3775. */
  3776. static enum XML_Error
  3777. doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
  3778. const char *end, const char **nextPtr, XML_Bool haveMore,
  3779. enum XML_Account account) {
  3780. const char *s = *startPtr;
  3781. const char **eventPP;
  3782. const char **eventEndPP;
  3783. if (enc == parser->m_encoding) {
  3784. eventPP = &parser->m_eventPtr;
  3785. *eventPP = s;
  3786. eventEndPP = &parser->m_eventEndPtr;
  3787. } else {
  3788. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  3789. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  3790. }
  3791. *eventPP = s;
  3792. *startPtr = NULL;
  3793. for (;;) {
  3794. const char *next = s; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
  3795. int tok = XmlCdataSectionTok(enc, s, end, &next);
  3796. #if XML_GE == 1
  3797. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
  3798. accountingOnAbort(parser);
  3799. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  3800. }
  3801. #else
  3802. UNUSED_P(account);
  3803. #endif
  3804. *eventEndPP = next;
  3805. switch (tok) {
  3806. case XML_TOK_CDATA_SECT_CLOSE:
  3807. if (parser->m_endCdataSectionHandler)
  3808. parser->m_endCdataSectionHandler(parser->m_handlerArg);
  3809. /* BEGIN disabled code */
  3810. /* see comment under XML_TOK_CDATA_SECT_OPEN */
  3811. else if ((0) && parser->m_characterDataHandler)
  3812. parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  3813. 0);
  3814. /* END disabled code */
  3815. else if (parser->m_defaultHandler)
  3816. reportDefault(parser, enc, s, next);
  3817. *startPtr = next;
  3818. *nextPtr = next;
  3819. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  3820. return XML_ERROR_ABORTED;
  3821. else
  3822. return XML_ERROR_NONE;
  3823. case XML_TOK_DATA_NEWLINE:
  3824. if (parser->m_characterDataHandler) {
  3825. XML_Char c = 0xA;
  3826. parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
  3827. } else if (parser->m_defaultHandler)
  3828. reportDefault(parser, enc, s, next);
  3829. break;
  3830. case XML_TOK_DATA_CHARS: {
  3831. XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
  3832. if (charDataHandler) {
  3833. if (MUST_CONVERT(enc, s)) {
  3834. for (;;) {
  3835. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  3836. const enum XML_Convert_Result convert_res = XmlConvert(
  3837. enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  3838. *eventEndPP = next;
  3839. charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  3840. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  3841. if ((convert_res == XML_CONVERT_COMPLETED)
  3842. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  3843. break;
  3844. *eventPP = s;
  3845. }
  3846. } else
  3847. charDataHandler(parser->m_handlerArg, (const XML_Char *)s,
  3848. (int)((const XML_Char *)next - (const XML_Char *)s));
  3849. } else if (parser->m_defaultHandler)
  3850. reportDefault(parser, enc, s, next);
  3851. } break;
  3852. case XML_TOK_INVALID:
  3853. *eventPP = next;
  3854. return XML_ERROR_INVALID_TOKEN;
  3855. case XML_TOK_PARTIAL_CHAR:
  3856. if (haveMore) {
  3857. *nextPtr = s;
  3858. return XML_ERROR_NONE;
  3859. }
  3860. return XML_ERROR_PARTIAL_CHAR;
  3861. case XML_TOK_PARTIAL:
  3862. case XML_TOK_NONE:
  3863. if (haveMore) {
  3864. *nextPtr = s;
  3865. return XML_ERROR_NONE;
  3866. }
  3867. return XML_ERROR_UNCLOSED_CDATA_SECTION;
  3868. default:
  3869. /* Every token returned by XmlCdataSectionTok() has its own
  3870. * explicit case, so this default case will never be executed.
  3871. * We retain it as a safety net and exclude it from the coverage
  3872. * statistics.
  3873. *
  3874. * LCOV_EXCL_START
  3875. */
  3876. *eventPP = next;
  3877. return XML_ERROR_UNEXPECTED_STATE;
  3878. /* LCOV_EXCL_STOP */
  3879. }
  3880. *eventPP = s = next;
  3881. switch (parser->m_parsingStatus.parsing) {
  3882. case XML_SUSPENDED:
  3883. *nextPtr = next;
  3884. return XML_ERROR_NONE;
  3885. case XML_FINISHED:
  3886. return XML_ERROR_ABORTED;
  3887. default:;
  3888. }
  3889. }
  3890. /* not reached */
  3891. }
  3892. #ifdef XML_DTD
  3893. /* The idea here is to avoid using stack for each IGNORE section when
  3894. the whole file is parsed with one call.
  3895. */
  3896. static enum XML_Error PTRCALL
  3897. ignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,
  3898. const char **endPtr) {
  3899. enum XML_Error result
  3900. = doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,
  3901. (XML_Bool)! parser->m_parsingStatus.finalBuffer);
  3902. if (result != XML_ERROR_NONE)
  3903. return result;
  3904. if (start) {
  3905. parser->m_processor = prologProcessor;
  3906. return prologProcessor(parser, start, end, endPtr);
  3907. }
  3908. return result;
  3909. }
  3910. /* startPtr gets set to non-null is the section is closed, and to null
  3911. if the section is not yet closed.
  3912. */
  3913. static enum XML_Error
  3914. doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
  3915. const char *end, const char **nextPtr, XML_Bool haveMore) {
  3916. const char *next = *startPtr; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
  3917. int tok;
  3918. const char *s = *startPtr;
  3919. const char **eventPP;
  3920. const char **eventEndPP;
  3921. if (enc == parser->m_encoding) {
  3922. eventPP = &parser->m_eventPtr;
  3923. *eventPP = s;
  3924. eventEndPP = &parser->m_eventEndPtr;
  3925. } else {
  3926. /* It's not entirely clear, but it seems the following two lines
  3927. * of code cannot be executed. The only occasions on which 'enc'
  3928. * is not 'encoding' are when this function is called
  3929. * from the internal entity processing, and IGNORE sections are an
  3930. * error in internal entities.
  3931. *
  3932. * Since it really isn't clear that this is true, we keep the code
  3933. * and just remove it from our coverage tests.
  3934. *
  3935. * LCOV_EXCL_START
  3936. */
  3937. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  3938. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  3939. /* LCOV_EXCL_STOP */
  3940. }
  3941. *eventPP = s;
  3942. *startPtr = NULL;
  3943. tok = XmlIgnoreSectionTok(enc, s, end, &next);
  3944. # if XML_GE == 1
  3945. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  3946. XML_ACCOUNT_DIRECT)) {
  3947. accountingOnAbort(parser);
  3948. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  3949. }
  3950. # endif
  3951. *eventEndPP = next;
  3952. switch (tok) {
  3953. case XML_TOK_IGNORE_SECT:
  3954. if (parser->m_defaultHandler)
  3955. reportDefault(parser, enc, s, next);
  3956. *startPtr = next;
  3957. *nextPtr = next;
  3958. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  3959. return XML_ERROR_ABORTED;
  3960. else
  3961. return XML_ERROR_NONE;
  3962. case XML_TOK_INVALID:
  3963. *eventPP = next;
  3964. return XML_ERROR_INVALID_TOKEN;
  3965. case XML_TOK_PARTIAL_CHAR:
  3966. if (haveMore) {
  3967. *nextPtr = s;
  3968. return XML_ERROR_NONE;
  3969. }
  3970. return XML_ERROR_PARTIAL_CHAR;
  3971. case XML_TOK_PARTIAL:
  3972. case XML_TOK_NONE:
  3973. if (haveMore) {
  3974. *nextPtr = s;
  3975. return XML_ERROR_NONE;
  3976. }
  3977. return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
  3978. default:
  3979. /* All of the tokens that XmlIgnoreSectionTok() returns have
  3980. * explicit cases to handle them, so this default case is never
  3981. * executed. We keep it as a safety net anyway, and remove it
  3982. * from our test coverage statistics.
  3983. *
  3984. * LCOV_EXCL_START
  3985. */
  3986. *eventPP = next;
  3987. return XML_ERROR_UNEXPECTED_STATE;
  3988. /* LCOV_EXCL_STOP */
  3989. }
  3990. /* not reached */
  3991. }
  3992. #endif /* XML_DTD */
  3993. static enum XML_Error
  3994. initializeEncoding(XML_Parser parser) {
  3995. const char *s;
  3996. #ifdef XML_UNICODE
  3997. char encodingBuf[128];
  3998. /* See comments about `protocolEncodingName` in parserInit() */
  3999. if (! parser->m_protocolEncodingName)
  4000. s = NULL;
  4001. else {
  4002. int i;
  4003. for (i = 0; parser->m_protocolEncodingName[i]; i++) {
  4004. if (i == sizeof(encodingBuf) - 1
  4005. || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
  4006. encodingBuf[0] = '\0';
  4007. break;
  4008. }
  4009. encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
  4010. }
  4011. encodingBuf[i] = '\0';
  4012. s = encodingBuf;
  4013. }
  4014. #else
  4015. s = parser->m_protocolEncodingName;
  4016. #endif
  4017. if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(
  4018. &parser->m_initEncoding, &parser->m_encoding, s))
  4019. return XML_ERROR_NONE;
  4020. return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
  4021. }
  4022. static enum XML_Error
  4023. processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
  4024. const char *next) {
  4025. const char *encodingName = NULL;
  4026. const XML_Char *storedEncName = NULL;
  4027. const ENCODING *newEncoding = NULL;
  4028. const char *version = NULL;
  4029. const char *versionend = NULL;
  4030. const XML_Char *storedversion = NULL;
  4031. int standalone = -1;
  4032. #if XML_GE == 1
  4033. if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__,
  4034. XML_ACCOUNT_DIRECT)) {
  4035. accountingOnAbort(parser);
  4036. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4037. }
  4038. #endif
  4039. if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(
  4040. isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,
  4041. &version, &versionend, &encodingName, &newEncoding, &standalone)) {
  4042. if (isGeneralTextEntity)
  4043. return XML_ERROR_TEXT_DECL;
  4044. else
  4045. return XML_ERROR_XML_DECL;
  4046. }
  4047. if (! isGeneralTextEntity && standalone == 1) {
  4048. parser->m_dtd->standalone = XML_TRUE;
  4049. #ifdef XML_DTD
  4050. if (parser->m_paramEntityParsing
  4051. == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
  4052. parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
  4053. #endif /* XML_DTD */
  4054. }
  4055. if (parser->m_xmlDeclHandler) {
  4056. if (encodingName != NULL) {
  4057. storedEncName = poolStoreString(
  4058. &parser->m_temp2Pool, parser->m_encoding, encodingName,
  4059. encodingName + XmlNameLength(parser->m_encoding, encodingName));
  4060. if (! storedEncName)
  4061. return XML_ERROR_NO_MEMORY;
  4062. poolFinish(&parser->m_temp2Pool);
  4063. }
  4064. if (version) {
  4065. storedversion
  4066. = poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,
  4067. versionend - parser->m_encoding->minBytesPerChar);
  4068. if (! storedversion)
  4069. return XML_ERROR_NO_MEMORY;
  4070. }
  4071. parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,
  4072. standalone);
  4073. } else if (parser->m_defaultHandler)
  4074. reportDefault(parser, parser->m_encoding, s, next);
  4075. if (parser->m_protocolEncodingName == NULL) {
  4076. if (newEncoding) {
  4077. /* Check that the specified encoding does not conflict with what
  4078. * the parser has already deduced. Do we have the same number
  4079. * of bytes in the smallest representation of a character? If
  4080. * this is UTF-16, is it the same endianness?
  4081. */
  4082. if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
  4083. || (newEncoding->minBytesPerChar == 2
  4084. && newEncoding != parser->m_encoding)) {
  4085. parser->m_eventPtr = encodingName;
  4086. return XML_ERROR_INCORRECT_ENCODING;
  4087. }
  4088. parser->m_encoding = newEncoding;
  4089. } else if (encodingName) {
  4090. enum XML_Error result;
  4091. if (! storedEncName) {
  4092. storedEncName = poolStoreString(
  4093. &parser->m_temp2Pool, parser->m_encoding, encodingName,
  4094. encodingName + XmlNameLength(parser->m_encoding, encodingName));
  4095. if (! storedEncName)
  4096. return XML_ERROR_NO_MEMORY;
  4097. }
  4098. result = handleUnknownEncoding(parser, storedEncName);
  4099. poolClear(&parser->m_temp2Pool);
  4100. if (result == XML_ERROR_UNKNOWN_ENCODING)
  4101. parser->m_eventPtr = encodingName;
  4102. return result;
  4103. }
  4104. }
  4105. if (storedEncName || storedversion)
  4106. poolClear(&parser->m_temp2Pool);
  4107. return XML_ERROR_NONE;
  4108. }
  4109. static enum XML_Error
  4110. handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {
  4111. if (parser->m_unknownEncodingHandler) {
  4112. XML_Encoding info;
  4113. int i;
  4114. for (i = 0; i < 256; i++)
  4115. info.map[i] = -1;
  4116. info.convert = NULL;
  4117. info.data = NULL;
  4118. info.release = NULL;
  4119. if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,
  4120. encodingName, &info)) {
  4121. ENCODING *enc;
  4122. parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
  4123. if (! parser->m_unknownEncodingMem) {
  4124. if (info.release)
  4125. info.release(info.data);
  4126. return XML_ERROR_NO_MEMORY;
  4127. }
  4128. enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(
  4129. parser->m_unknownEncodingMem, info.map, info.convert, info.data);
  4130. if (enc) {
  4131. parser->m_unknownEncodingData = info.data;
  4132. parser->m_unknownEncodingRelease = info.release;
  4133. parser->m_encoding = enc;
  4134. return XML_ERROR_NONE;
  4135. }
  4136. }
  4137. if (info.release != NULL)
  4138. info.release(info.data);
  4139. }
  4140. return XML_ERROR_UNKNOWN_ENCODING;
  4141. }
  4142. static enum XML_Error PTRCALL
  4143. prologInitProcessor(XML_Parser parser, const char *s, const char *end,
  4144. const char **nextPtr) {
  4145. enum XML_Error result = initializeEncoding(parser);
  4146. if (result != XML_ERROR_NONE)
  4147. return result;
  4148. parser->m_processor = prologProcessor;
  4149. return prologProcessor(parser, s, end, nextPtr);
  4150. }
  4151. #ifdef XML_DTD
  4152. static enum XML_Error PTRCALL
  4153. externalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,
  4154. const char **nextPtr) {
  4155. enum XML_Error result = initializeEncoding(parser);
  4156. if (result != XML_ERROR_NONE)
  4157. return result;
  4158. /* we know now that XML_Parse(Buffer) has been called,
  4159. so we consider the external parameter entity read */
  4160. parser->m_dtd->paramEntityRead = XML_TRUE;
  4161. if (parser->m_prologState.inEntityValue) {
  4162. parser->m_processor = entityValueInitProcessor;
  4163. return entityValueInitProcessor(parser, s, end, nextPtr);
  4164. } else {
  4165. parser->m_processor = externalParEntProcessor;
  4166. return externalParEntProcessor(parser, s, end, nextPtr);
  4167. }
  4168. }
  4169. static enum XML_Error PTRCALL
  4170. entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
  4171. const char **nextPtr) {
  4172. int tok;
  4173. const char *start = s;
  4174. const char *next = start;
  4175. parser->m_eventPtr = start;
  4176. for (;;) {
  4177. tok = XmlPrologTok(parser->m_encoding, start, end, &next);
  4178. /* Note: Except for XML_TOK_BOM below, these bytes are accounted later in:
  4179. - storeEntityValue
  4180. - processXmlDecl
  4181. */
  4182. parser->m_eventEndPtr = next;
  4183. if (tok <= 0) {
  4184. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4185. *nextPtr = s;
  4186. return XML_ERROR_NONE;
  4187. }
  4188. switch (tok) {
  4189. case XML_TOK_INVALID:
  4190. return XML_ERROR_INVALID_TOKEN;
  4191. case XML_TOK_PARTIAL:
  4192. return XML_ERROR_UNCLOSED_TOKEN;
  4193. case XML_TOK_PARTIAL_CHAR:
  4194. return XML_ERROR_PARTIAL_CHAR;
  4195. case XML_TOK_NONE: /* start == end */
  4196. default:
  4197. break;
  4198. }
  4199. /* found end of entity value - can store it now */
  4200. return storeEntityValue(parser, parser->m_encoding, s, end,
  4201. XML_ACCOUNT_DIRECT);
  4202. } else if (tok == XML_TOK_XML_DECL) {
  4203. enum XML_Error result;
  4204. result = processXmlDecl(parser, 0, start, next);
  4205. if (result != XML_ERROR_NONE)
  4206. return result;
  4207. /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For
  4208. * that to happen, a parameter entity parsing handler must have attempted
  4209. * to suspend the parser, which fails and raises an error. The parser can
  4210. * be aborted, but can't be suspended.
  4211. */
  4212. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  4213. return XML_ERROR_ABORTED;
  4214. *nextPtr = next;
  4215. /* stop scanning for text declaration - we found one */
  4216. parser->m_processor = entityValueProcessor;
  4217. return entityValueProcessor(parser, next, end, nextPtr);
  4218. }
  4219. /* XmlPrologTok has now set the encoding based on the BOM it found, and we
  4220. must move s and nextPtr forward to consume the BOM.
  4221. If we didn't, and got XML_TOK_NONE from the next XmlPrologTok call, we
  4222. would leave the BOM in the buffer and return. On the next call to this
  4223. function, our XmlPrologTok call would return XML_TOK_INVALID, since it
  4224. is not valid to have multiple BOMs.
  4225. */
  4226. else if (tok == XML_TOK_BOM) {
  4227. # if XML_GE == 1
  4228. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4229. XML_ACCOUNT_DIRECT)) {
  4230. accountingOnAbort(parser);
  4231. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4232. }
  4233. # endif
  4234. *nextPtr = next;
  4235. s = next;
  4236. }
  4237. /* If we get this token, we have the start of what might be a
  4238. normal tag, but not a declaration (i.e. it doesn't begin with
  4239. "<!"). In a DTD context, that isn't legal.
  4240. */
  4241. else if (tok == XML_TOK_INSTANCE_START) {
  4242. *nextPtr = next;
  4243. return XML_ERROR_SYNTAX;
  4244. }
  4245. start = next;
  4246. parser->m_eventPtr = start;
  4247. }
  4248. }
  4249. static enum XML_Error PTRCALL
  4250. externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
  4251. const char **nextPtr) {
  4252. const char *next = s;
  4253. int tok;
  4254. tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4255. if (tok <= 0) {
  4256. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4257. *nextPtr = s;
  4258. return XML_ERROR_NONE;
  4259. }
  4260. switch (tok) {
  4261. case XML_TOK_INVALID:
  4262. return XML_ERROR_INVALID_TOKEN;
  4263. case XML_TOK_PARTIAL:
  4264. return XML_ERROR_UNCLOSED_TOKEN;
  4265. case XML_TOK_PARTIAL_CHAR:
  4266. return XML_ERROR_PARTIAL_CHAR;
  4267. case XML_TOK_NONE: /* start == end */
  4268. default:
  4269. break;
  4270. }
  4271. }
  4272. /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
  4273. However, when parsing an external subset, doProlog will not accept a BOM
  4274. as valid, and report a syntax error, so we have to skip the BOM, and
  4275. account for the BOM bytes.
  4276. */
  4277. else if (tok == XML_TOK_BOM) {
  4278. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4279. XML_ACCOUNT_DIRECT)) {
  4280. accountingOnAbort(parser);
  4281. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4282. }
  4283. s = next;
  4284. tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4285. }
  4286. parser->m_processor = prologProcessor;
  4287. return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
  4288. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
  4289. XML_ACCOUNT_DIRECT);
  4290. }
  4291. static enum XML_Error PTRCALL
  4292. entityValueProcessor(XML_Parser parser, const char *s, const char *end,
  4293. const char **nextPtr) {
  4294. const char *start = s;
  4295. const char *next = s;
  4296. const ENCODING *enc = parser->m_encoding;
  4297. int tok;
  4298. for (;;) {
  4299. tok = XmlPrologTok(enc, start, end, &next);
  4300. /* Note: These bytes are accounted later in:
  4301. - storeEntityValue
  4302. */
  4303. if (tok <= 0) {
  4304. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4305. *nextPtr = s;
  4306. return XML_ERROR_NONE;
  4307. }
  4308. switch (tok) {
  4309. case XML_TOK_INVALID:
  4310. return XML_ERROR_INVALID_TOKEN;
  4311. case XML_TOK_PARTIAL:
  4312. return XML_ERROR_UNCLOSED_TOKEN;
  4313. case XML_TOK_PARTIAL_CHAR:
  4314. return XML_ERROR_PARTIAL_CHAR;
  4315. case XML_TOK_NONE: /* start == end */
  4316. default:
  4317. break;
  4318. }
  4319. /* found end of entity value - can store it now */
  4320. return storeEntityValue(parser, enc, s, end, XML_ACCOUNT_DIRECT);
  4321. }
  4322. start = next;
  4323. }
  4324. }
  4325. #endif /* XML_DTD */
  4326. static enum XML_Error PTRCALL
  4327. prologProcessor(XML_Parser parser, const char *s, const char *end,
  4328. const char **nextPtr) {
  4329. const char *next = s;
  4330. int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4331. return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
  4332. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
  4333. XML_ACCOUNT_DIRECT);
  4334. }
  4335. static enum XML_Error
  4336. doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
  4337. int tok, const char *next, const char **nextPtr, XML_Bool haveMore,
  4338. XML_Bool allowClosingDoctype, enum XML_Account account) {
  4339. #ifdef XML_DTD
  4340. static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
  4341. #endif /* XML_DTD */
  4342. static const XML_Char atypeCDATA[]
  4343. = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
  4344. static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
  4345. static const XML_Char atypeIDREF[]
  4346. = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
  4347. static const XML_Char atypeIDREFS[]
  4348. = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
  4349. static const XML_Char atypeENTITY[]
  4350. = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
  4351. static const XML_Char atypeENTITIES[]
  4352. = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
  4353. ASCII_I, ASCII_E, ASCII_S, '\0'};
  4354. static const XML_Char atypeNMTOKEN[]
  4355. = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
  4356. static const XML_Char atypeNMTOKENS[]
  4357. = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
  4358. ASCII_E, ASCII_N, ASCII_S, '\0'};
  4359. static const XML_Char notationPrefix[]
  4360. = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,
  4361. ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
  4362. static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
  4363. static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
  4364. #ifndef XML_DTD
  4365. UNUSED_P(account);
  4366. #endif
  4367. { // WINSCP
  4368. /* save one level of indirection */
  4369. DTD *const dtd = parser->m_dtd;
  4370. const char **eventPP;
  4371. const char **eventEndPP;
  4372. enum XML_Content_Quant quant;
  4373. if (enc == parser->m_encoding) {
  4374. eventPP = &parser->m_eventPtr;
  4375. eventEndPP = &parser->m_eventEndPtr;
  4376. } else {
  4377. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  4378. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  4379. }
  4380. for (;;) {
  4381. int role;
  4382. XML_Bool handleDefault = XML_TRUE;
  4383. *eventPP = s;
  4384. *eventEndPP = next;
  4385. if (tok <= 0) {
  4386. if (haveMore && tok != XML_TOK_INVALID) {
  4387. *nextPtr = s;
  4388. return XML_ERROR_NONE;
  4389. }
  4390. switch (tok) {
  4391. case XML_TOK_INVALID:
  4392. *eventPP = next;
  4393. return XML_ERROR_INVALID_TOKEN;
  4394. case XML_TOK_PARTIAL:
  4395. return XML_ERROR_UNCLOSED_TOKEN;
  4396. case XML_TOK_PARTIAL_CHAR:
  4397. return XML_ERROR_PARTIAL_CHAR;
  4398. case -XML_TOK_PROLOG_S:
  4399. tok = -tok;
  4400. break;
  4401. case XML_TOK_NONE:
  4402. #ifdef XML_DTD
  4403. /* for internal PE NOT referenced between declarations */
  4404. if (enc != parser->m_encoding
  4405. && ! parser->m_openInternalEntities->betweenDecl) {
  4406. *nextPtr = s;
  4407. return XML_ERROR_NONE;
  4408. }
  4409. /* WFC: PE Between Declarations - must check that PE contains
  4410. complete markup, not only for external PEs, but also for
  4411. internal PEs if the reference occurs between declarations.
  4412. */
  4413. if (parser->m_isParamEntity || enc != parser->m_encoding) {
  4414. if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
  4415. == XML_ROLE_ERROR)
  4416. return XML_ERROR_INCOMPLETE_PE;
  4417. *nextPtr = s;
  4418. return XML_ERROR_NONE;
  4419. }
  4420. #endif /* XML_DTD */
  4421. return XML_ERROR_NO_ELEMENTS;
  4422. default:
  4423. tok = -tok;
  4424. next = end;
  4425. break;
  4426. }
  4427. }
  4428. role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
  4429. #if XML_GE == 1
  4430. switch (role) {
  4431. case XML_ROLE_INSTANCE_START: // bytes accounted in contentProcessor
  4432. case XML_ROLE_XML_DECL: // bytes accounted in processXmlDecl
  4433. # ifdef XML_DTD
  4434. case XML_ROLE_TEXT_DECL: // bytes accounted in processXmlDecl
  4435. # endif
  4436. break;
  4437. default:
  4438. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
  4439. accountingOnAbort(parser);
  4440. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4441. }
  4442. }
  4443. #endif
  4444. switch (role) {
  4445. case XML_ROLE_XML_DECL: {
  4446. enum XML_Error result = processXmlDecl(parser, 0, s, next);
  4447. if (result != XML_ERROR_NONE)
  4448. return result;
  4449. enc = parser->m_encoding;
  4450. handleDefault = XML_FALSE;
  4451. } break;
  4452. case XML_ROLE_DOCTYPE_NAME:
  4453. if (parser->m_startDoctypeDeclHandler) {
  4454. parser->m_doctypeName
  4455. = poolStoreString(&parser->m_tempPool, enc, s, next);
  4456. if (! parser->m_doctypeName)
  4457. return XML_ERROR_NO_MEMORY;
  4458. poolFinish(&parser->m_tempPool);
  4459. parser->m_doctypePubid = NULL;
  4460. handleDefault = XML_FALSE;
  4461. }
  4462. parser->m_doctypeSysid = NULL; /* always initialize to NULL */
  4463. break;
  4464. case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
  4465. if (parser->m_startDoctypeDeclHandler) {
  4466. parser->m_startDoctypeDeclHandler(
  4467. parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
  4468. parser->m_doctypePubid, 1);
  4469. parser->m_doctypeName = NULL;
  4470. poolClear(&parser->m_tempPool);
  4471. handleDefault = XML_FALSE;
  4472. }
  4473. break;
  4474. #ifdef XML_DTD
  4475. case XML_ROLE_TEXT_DECL: {
  4476. enum XML_Error result = processXmlDecl(parser, 1, s, next);
  4477. if (result != XML_ERROR_NONE)
  4478. return result;
  4479. enc = parser->m_encoding;
  4480. handleDefault = XML_FALSE;
  4481. } break;
  4482. #endif /* XML_DTD */
  4483. case XML_ROLE_DOCTYPE_PUBLIC_ID:
  4484. #ifdef XML_DTD
  4485. parser->m_useForeignDTD = XML_FALSE;
  4486. parser->m_declEntity = (ENTITY *)lookup(
  4487. parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
  4488. if (! parser->m_declEntity)
  4489. return XML_ERROR_NO_MEMORY;
  4490. #endif /* XML_DTD */
  4491. dtd->hasParamEntityRefs = XML_TRUE;
  4492. if (parser->m_startDoctypeDeclHandler) {
  4493. XML_Char *pubId;
  4494. if (! XmlIsPublicId(enc, s, next, eventPP))
  4495. return XML_ERROR_PUBLICID;
  4496. pubId = poolStoreString(&parser->m_tempPool, enc,
  4497. s + enc->minBytesPerChar,
  4498. next - enc->minBytesPerChar);
  4499. if (! pubId)
  4500. return XML_ERROR_NO_MEMORY;
  4501. normalizePublicId(pubId);
  4502. poolFinish(&parser->m_tempPool);
  4503. parser->m_doctypePubid = pubId;
  4504. handleDefault = XML_FALSE;
  4505. goto alreadyChecked;
  4506. }
  4507. /* fall through */
  4508. case XML_ROLE_ENTITY_PUBLIC_ID:
  4509. if (! XmlIsPublicId(enc, s, next, eventPP))
  4510. return XML_ERROR_PUBLICID;
  4511. alreadyChecked:
  4512. if (dtd->keepProcessing && parser->m_declEntity) {
  4513. XML_Char *tem
  4514. = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  4515. next - enc->minBytesPerChar);
  4516. if (! tem)
  4517. return XML_ERROR_NO_MEMORY;
  4518. normalizePublicId(tem);
  4519. parser->m_declEntity->publicId = tem;
  4520. poolFinish(&dtd->pool);
  4521. /* Don't suppress the default handler if we fell through from
  4522. * the XML_ROLE_DOCTYPE_PUBLIC_ID case.
  4523. */
  4524. if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
  4525. handleDefault = XML_FALSE;
  4526. }
  4527. break;
  4528. case XML_ROLE_DOCTYPE_CLOSE:
  4529. if (allowClosingDoctype != XML_TRUE) {
  4530. /* Must not close doctype from within expanded parameter entities */
  4531. return XML_ERROR_INVALID_TOKEN;
  4532. }
  4533. if (parser->m_doctypeName) {
  4534. parser->m_startDoctypeDeclHandler(
  4535. parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
  4536. parser->m_doctypePubid, 0);
  4537. poolClear(&parser->m_tempPool);
  4538. handleDefault = XML_FALSE;
  4539. }
  4540. /* parser->m_doctypeSysid will be non-NULL in the case of a previous
  4541. XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
  4542. was not set, indicating an external subset
  4543. */
  4544. #ifdef XML_DTD
  4545. if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
  4546. XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
  4547. dtd->hasParamEntityRefs = XML_TRUE;
  4548. if (parser->m_paramEntityParsing
  4549. && parser->m_externalEntityRefHandler) {
  4550. ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  4551. externalSubsetName, sizeof(ENTITY));
  4552. if (! entity) {
  4553. /* The external subset name "#" will have already been
  4554. * inserted into the hash table at the start of the
  4555. * external entity parsing, so no allocation will happen
  4556. * and lookup() cannot fail.
  4557. */
  4558. return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
  4559. }
  4560. if (parser->m_useForeignDTD)
  4561. entity->base = parser->m_curBase;
  4562. dtd->paramEntityRead = XML_FALSE;
  4563. if (! parser->m_externalEntityRefHandler(
  4564. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  4565. entity->systemId, entity->publicId))
  4566. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  4567. if (dtd->paramEntityRead) {
  4568. if (! dtd->standalone && parser->m_notStandaloneHandler
  4569. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  4570. return XML_ERROR_NOT_STANDALONE;
  4571. }
  4572. /* if we didn't read the foreign DTD then this means that there
  4573. is no external subset and we must reset dtd->hasParamEntityRefs
  4574. */
  4575. else if (! parser->m_doctypeSysid)
  4576. dtd->hasParamEntityRefs = hadParamEntityRefs;
  4577. /* end of DTD - no need to update dtd->keepProcessing */
  4578. }
  4579. parser->m_useForeignDTD = XML_FALSE;
  4580. }
  4581. #endif /* XML_DTD */
  4582. if (parser->m_endDoctypeDeclHandler) {
  4583. parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
  4584. handleDefault = XML_FALSE;
  4585. }
  4586. break;
  4587. case XML_ROLE_INSTANCE_START:
  4588. #ifdef XML_DTD
  4589. /* if there is no DOCTYPE declaration then now is the
  4590. last chance to read the foreign DTD
  4591. */
  4592. if (parser->m_useForeignDTD) {
  4593. XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
  4594. dtd->hasParamEntityRefs = XML_TRUE;
  4595. if (parser->m_paramEntityParsing
  4596. && parser->m_externalEntityRefHandler) {
  4597. ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  4598. externalSubsetName, sizeof(ENTITY));
  4599. if (! entity)
  4600. return XML_ERROR_NO_MEMORY;
  4601. entity->base = parser->m_curBase;
  4602. dtd->paramEntityRead = XML_FALSE;
  4603. if (! parser->m_externalEntityRefHandler(
  4604. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  4605. entity->systemId, entity->publicId))
  4606. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  4607. if (dtd->paramEntityRead) {
  4608. if (! dtd->standalone && parser->m_notStandaloneHandler
  4609. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  4610. return XML_ERROR_NOT_STANDALONE;
  4611. }
  4612. /* if we didn't read the foreign DTD then this means that there
  4613. is no external subset and we must reset dtd->hasParamEntityRefs
  4614. */
  4615. else
  4616. dtd->hasParamEntityRefs = hadParamEntityRefs;
  4617. /* end of DTD - no need to update dtd->keepProcessing */
  4618. }
  4619. }
  4620. #endif /* XML_DTD */
  4621. parser->m_processor = contentProcessor;
  4622. return contentProcessor(parser, s, end, nextPtr);
  4623. case XML_ROLE_ATTLIST_ELEMENT_NAME:
  4624. parser->m_declElementType = getElementType(parser, enc, s, next);
  4625. if (! parser->m_declElementType)
  4626. return XML_ERROR_NO_MEMORY;
  4627. goto checkAttListDeclHandler;
  4628. case XML_ROLE_ATTRIBUTE_NAME:
  4629. parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
  4630. if (! parser->m_declAttributeId)
  4631. return XML_ERROR_NO_MEMORY;
  4632. parser->m_declAttributeIsCdata = XML_FALSE;
  4633. parser->m_declAttributeType = NULL;
  4634. parser->m_declAttributeIsId = XML_FALSE;
  4635. goto checkAttListDeclHandler;
  4636. case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
  4637. parser->m_declAttributeIsCdata = XML_TRUE;
  4638. parser->m_declAttributeType = atypeCDATA;
  4639. goto checkAttListDeclHandler;
  4640. case XML_ROLE_ATTRIBUTE_TYPE_ID:
  4641. parser->m_declAttributeIsId = XML_TRUE;
  4642. parser->m_declAttributeType = atypeID;
  4643. goto checkAttListDeclHandler;
  4644. case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
  4645. parser->m_declAttributeType = atypeIDREF;
  4646. goto checkAttListDeclHandler;
  4647. case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
  4648. parser->m_declAttributeType = atypeIDREFS;
  4649. goto checkAttListDeclHandler;
  4650. case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
  4651. parser->m_declAttributeType = atypeENTITY;
  4652. goto checkAttListDeclHandler;
  4653. case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
  4654. parser->m_declAttributeType = atypeENTITIES;
  4655. goto checkAttListDeclHandler;
  4656. case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
  4657. parser->m_declAttributeType = atypeNMTOKEN;
  4658. goto checkAttListDeclHandler;
  4659. case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
  4660. parser->m_declAttributeType = atypeNMTOKENS;
  4661. checkAttListDeclHandler:
  4662. if (dtd->keepProcessing && parser->m_attlistDeclHandler)
  4663. handleDefault = XML_FALSE;
  4664. break;
  4665. case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
  4666. case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
  4667. if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
  4668. const XML_Char *prefix;
  4669. if (parser->m_declAttributeType) {
  4670. prefix = enumValueSep;
  4671. } else {
  4672. prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
  4673. : enumValueStart);
  4674. }
  4675. if (! poolAppendString(&parser->m_tempPool, prefix))
  4676. return XML_ERROR_NO_MEMORY;
  4677. if (! poolAppend(&parser->m_tempPool, enc, s, next))
  4678. return XML_ERROR_NO_MEMORY;
  4679. parser->m_declAttributeType = parser->m_tempPool.start;
  4680. handleDefault = XML_FALSE;
  4681. }
  4682. break;
  4683. case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
  4684. case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
  4685. if (dtd->keepProcessing) {
  4686. if (! defineAttribute(parser->m_declElementType,
  4687. parser->m_declAttributeId,
  4688. parser->m_declAttributeIsCdata,
  4689. parser->m_declAttributeIsId, 0, parser))
  4690. return XML_ERROR_NO_MEMORY;
  4691. if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
  4692. if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
  4693. || (*parser->m_declAttributeType == XML_T(ASCII_N)
  4694. && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
  4695. /* Enumerated or Notation type */
  4696. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
  4697. || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  4698. return XML_ERROR_NO_MEMORY;
  4699. parser->m_declAttributeType = parser->m_tempPool.start;
  4700. poolFinish(&parser->m_tempPool);
  4701. }
  4702. *eventEndPP = s;
  4703. parser->m_attlistDeclHandler(
  4704. parser->m_handlerArg, parser->m_declElementType->name,
  4705. parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
  4706. role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
  4707. handleDefault = XML_FALSE;
  4708. }
  4709. }
  4710. poolClear(&parser->m_tempPool);
  4711. break;
  4712. case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
  4713. case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
  4714. if (dtd->keepProcessing) {
  4715. const XML_Char *attVal;
  4716. enum XML_Error result = storeAttributeValue(
  4717. parser, enc, parser->m_declAttributeIsCdata,
  4718. s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool,
  4719. XML_ACCOUNT_NONE);
  4720. if (result)
  4721. return result;
  4722. attVal = poolStart(&dtd->pool);
  4723. poolFinish(&dtd->pool);
  4724. /* ID attributes aren't allowed to have a default */
  4725. if (! defineAttribute(
  4726. parser->m_declElementType, parser->m_declAttributeId,
  4727. parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
  4728. return XML_ERROR_NO_MEMORY;
  4729. if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
  4730. if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
  4731. || (*parser->m_declAttributeType == XML_T(ASCII_N)
  4732. && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
  4733. /* Enumerated or Notation type */
  4734. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
  4735. || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  4736. return XML_ERROR_NO_MEMORY;
  4737. parser->m_declAttributeType = parser->m_tempPool.start;
  4738. poolFinish(&parser->m_tempPool);
  4739. }
  4740. *eventEndPP = s;
  4741. parser->m_attlistDeclHandler(
  4742. parser->m_handlerArg, parser->m_declElementType->name,
  4743. parser->m_declAttributeId->name, parser->m_declAttributeType,
  4744. attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
  4745. poolClear(&parser->m_tempPool);
  4746. handleDefault = XML_FALSE;
  4747. }
  4748. }
  4749. break;
  4750. case XML_ROLE_ENTITY_VALUE:
  4751. if (dtd->keepProcessing) {
  4752. #if XML_GE == 1
  4753. // This will store the given replacement text in
  4754. // parser->m_declEntity->textPtr.
  4755. enum XML_Error result
  4756. = storeEntityValue(parser, enc, s + enc->minBytesPerChar,
  4757. next - enc->minBytesPerChar, XML_ACCOUNT_NONE);
  4758. if (parser->m_declEntity) {
  4759. parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
  4760. parser->m_declEntity->textLen
  4761. = (int)(poolLength(&dtd->entityValuePool));
  4762. poolFinish(&dtd->entityValuePool);
  4763. if (parser->m_entityDeclHandler) {
  4764. *eventEndPP = s;
  4765. parser->m_entityDeclHandler(
  4766. parser->m_handlerArg, parser->m_declEntity->name,
  4767. parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
  4768. parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
  4769. handleDefault = XML_FALSE;
  4770. }
  4771. } else
  4772. poolDiscard(&dtd->entityValuePool);
  4773. if (result != XML_ERROR_NONE)
  4774. return result;
  4775. #else
  4776. // This will store "&amp;entity123;" in parser->m_declEntity->textPtr
  4777. // to end up as "&entity123;" in the handler.
  4778. if (parser->m_declEntity != NULL) {
  4779. const enum XML_Error result
  4780. = storeSelfEntityValue(parser, parser->m_declEntity);
  4781. if (result != XML_ERROR_NONE)
  4782. return result;
  4783. if (parser->m_entityDeclHandler) {
  4784. *eventEndPP = s;
  4785. parser->m_entityDeclHandler(
  4786. parser->m_handlerArg, parser->m_declEntity->name,
  4787. parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
  4788. parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
  4789. handleDefault = XML_FALSE;
  4790. }
  4791. }
  4792. #endif
  4793. }
  4794. break;
  4795. case XML_ROLE_DOCTYPE_SYSTEM_ID:
  4796. #ifdef XML_DTD
  4797. parser->m_useForeignDTD = XML_FALSE;
  4798. #endif /* XML_DTD */
  4799. dtd->hasParamEntityRefs = XML_TRUE;
  4800. if (parser->m_startDoctypeDeclHandler) {
  4801. parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
  4802. s + enc->minBytesPerChar,
  4803. next - enc->minBytesPerChar);
  4804. if (parser->m_doctypeSysid == NULL)
  4805. return XML_ERROR_NO_MEMORY;
  4806. poolFinish(&parser->m_tempPool);
  4807. handleDefault = XML_FALSE;
  4808. }
  4809. #ifdef XML_DTD
  4810. else
  4811. /* use externalSubsetName to make parser->m_doctypeSysid non-NULL
  4812. for the case where no parser->m_startDoctypeDeclHandler is set */
  4813. parser->m_doctypeSysid = externalSubsetName;
  4814. #endif /* XML_DTD */
  4815. if (! dtd->standalone
  4816. #ifdef XML_DTD
  4817. && ! parser->m_paramEntityParsing
  4818. #endif /* XML_DTD */
  4819. && parser->m_notStandaloneHandler
  4820. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  4821. return XML_ERROR_NOT_STANDALONE;
  4822. #ifndef XML_DTD
  4823. break;
  4824. #else /* XML_DTD */
  4825. if (! parser->m_declEntity) {
  4826. parser->m_declEntity = (ENTITY *)lookup(
  4827. parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
  4828. if (! parser->m_declEntity)
  4829. return XML_ERROR_NO_MEMORY;
  4830. parser->m_declEntity->publicId = NULL;
  4831. }
  4832. #endif /* XML_DTD */
  4833. /* fall through */
  4834. case XML_ROLE_ENTITY_SYSTEM_ID:
  4835. if (dtd->keepProcessing && parser->m_declEntity) {
  4836. parser->m_declEntity->systemId
  4837. = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  4838. next - enc->minBytesPerChar);
  4839. if (! parser->m_declEntity->systemId)
  4840. return XML_ERROR_NO_MEMORY;
  4841. parser->m_declEntity->base = parser->m_curBase;
  4842. poolFinish(&dtd->pool);
  4843. /* Don't suppress the default handler if we fell through from
  4844. * the XML_ROLE_DOCTYPE_SYSTEM_ID case.
  4845. */
  4846. if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
  4847. handleDefault = XML_FALSE;
  4848. }
  4849. break;
  4850. case XML_ROLE_ENTITY_COMPLETE:
  4851. #if XML_GE == 0
  4852. // This will store "&amp;entity123;" in entity->textPtr
  4853. // to end up as "&entity123;" in the handler.
  4854. if (parser->m_declEntity != NULL) {
  4855. const enum XML_Error result
  4856. = storeSelfEntityValue(parser, parser->m_declEntity);
  4857. if (result != XML_ERROR_NONE)
  4858. return result;
  4859. }
  4860. #endif
  4861. if (dtd->keepProcessing && parser->m_declEntity
  4862. && parser->m_entityDeclHandler) {
  4863. *eventEndPP = s;
  4864. parser->m_entityDeclHandler(
  4865. parser->m_handlerArg, parser->m_declEntity->name,
  4866. parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,
  4867. parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);
  4868. handleDefault = XML_FALSE;
  4869. }
  4870. break;
  4871. case XML_ROLE_ENTITY_NOTATION_NAME:
  4872. if (dtd->keepProcessing && parser->m_declEntity) {
  4873. parser->m_declEntity->notation
  4874. = poolStoreString(&dtd->pool, enc, s, next);
  4875. if (! parser->m_declEntity->notation)
  4876. return XML_ERROR_NO_MEMORY;
  4877. poolFinish(&dtd->pool);
  4878. if (parser->m_unparsedEntityDeclHandler) {
  4879. *eventEndPP = s;
  4880. parser->m_unparsedEntityDeclHandler(
  4881. parser->m_handlerArg, parser->m_declEntity->name,
  4882. parser->m_declEntity->base, parser->m_declEntity->systemId,
  4883. parser->m_declEntity->publicId, parser->m_declEntity->notation);
  4884. handleDefault = XML_FALSE;
  4885. } else if (parser->m_entityDeclHandler) {
  4886. *eventEndPP = s;
  4887. parser->m_entityDeclHandler(
  4888. parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,
  4889. parser->m_declEntity->base, parser->m_declEntity->systemId,
  4890. parser->m_declEntity->publicId, parser->m_declEntity->notation);
  4891. handleDefault = XML_FALSE;
  4892. }
  4893. }
  4894. break;
  4895. case XML_ROLE_GENERAL_ENTITY_NAME: {
  4896. if (XmlPredefinedEntityName(enc, s, next)) {
  4897. parser->m_declEntity = NULL;
  4898. break;
  4899. }
  4900. if (dtd->keepProcessing) {
  4901. const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
  4902. if (! name)
  4903. return XML_ERROR_NO_MEMORY;
  4904. parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,
  4905. name, sizeof(ENTITY));
  4906. if (! parser->m_declEntity)
  4907. return XML_ERROR_NO_MEMORY;
  4908. if (parser->m_declEntity->name != name) {
  4909. poolDiscard(&dtd->pool);
  4910. parser->m_declEntity = NULL;
  4911. } else {
  4912. poolFinish(&dtd->pool);
  4913. parser->m_declEntity->publicId = NULL;
  4914. parser->m_declEntity->is_param = XML_FALSE;
  4915. /* if we have a parent parser or are reading an internal parameter
  4916. entity, then the entity declaration is not considered "internal"
  4917. */
  4918. parser->m_declEntity->is_internal
  4919. = ! (parser->m_parentParser || parser->m_openInternalEntities);
  4920. if (parser->m_entityDeclHandler)
  4921. handleDefault = XML_FALSE;
  4922. }
  4923. } else {
  4924. poolDiscard(&dtd->pool);
  4925. parser->m_declEntity = NULL;
  4926. }
  4927. } break;
  4928. case XML_ROLE_PARAM_ENTITY_NAME:
  4929. #ifdef XML_DTD
  4930. if (dtd->keepProcessing) {
  4931. const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
  4932. if (! name)
  4933. return XML_ERROR_NO_MEMORY;
  4934. parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  4935. name, sizeof(ENTITY));
  4936. if (! parser->m_declEntity)
  4937. return XML_ERROR_NO_MEMORY;
  4938. if (parser->m_declEntity->name != name) {
  4939. poolDiscard(&dtd->pool);
  4940. parser->m_declEntity = NULL;
  4941. } else {
  4942. poolFinish(&dtd->pool);
  4943. parser->m_declEntity->publicId = NULL;
  4944. parser->m_declEntity->is_param = XML_TRUE;
  4945. /* if we have a parent parser or are reading an internal parameter
  4946. entity, then the entity declaration is not considered "internal"
  4947. */
  4948. parser->m_declEntity->is_internal
  4949. = ! (parser->m_parentParser || parser->m_openInternalEntities);
  4950. if (parser->m_entityDeclHandler)
  4951. handleDefault = XML_FALSE;
  4952. }
  4953. } else {
  4954. poolDiscard(&dtd->pool);
  4955. parser->m_declEntity = NULL;
  4956. }
  4957. #else /* not XML_DTD */
  4958. parser->m_declEntity = NULL;
  4959. #endif /* XML_DTD */
  4960. break;
  4961. case XML_ROLE_NOTATION_NAME:
  4962. parser->m_declNotationPublicId = NULL;
  4963. parser->m_declNotationName = NULL;
  4964. if (parser->m_notationDeclHandler) {
  4965. parser->m_declNotationName
  4966. = poolStoreString(&parser->m_tempPool, enc, s, next);
  4967. if (! parser->m_declNotationName)
  4968. return XML_ERROR_NO_MEMORY;
  4969. poolFinish(&parser->m_tempPool);
  4970. handleDefault = XML_FALSE;
  4971. }
  4972. break;
  4973. case XML_ROLE_NOTATION_PUBLIC_ID:
  4974. if (! XmlIsPublicId(enc, s, next, eventPP))
  4975. return XML_ERROR_PUBLICID;
  4976. if (parser
  4977. ->m_declNotationName) { /* means m_notationDeclHandler != NULL */
  4978. XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,
  4979. s + enc->minBytesPerChar,
  4980. next - enc->minBytesPerChar);
  4981. if (! tem)
  4982. return XML_ERROR_NO_MEMORY;
  4983. normalizePublicId(tem);
  4984. parser->m_declNotationPublicId = tem;
  4985. poolFinish(&parser->m_tempPool);
  4986. handleDefault = XML_FALSE;
  4987. }
  4988. break;
  4989. case XML_ROLE_NOTATION_SYSTEM_ID:
  4990. if (parser->m_declNotationName && parser->m_notationDeclHandler) {
  4991. const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,
  4992. s + enc->minBytesPerChar,
  4993. next - enc->minBytesPerChar);
  4994. if (! systemId)
  4995. return XML_ERROR_NO_MEMORY;
  4996. *eventEndPP = s;
  4997. parser->m_notationDeclHandler(
  4998. parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
  4999. systemId, parser->m_declNotationPublicId);
  5000. handleDefault = XML_FALSE;
  5001. }
  5002. poolClear(&parser->m_tempPool);
  5003. break;
  5004. case XML_ROLE_NOTATION_NO_SYSTEM_ID:
  5005. if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
  5006. *eventEndPP = s;
  5007. parser->m_notationDeclHandler(
  5008. parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
  5009. 0, parser->m_declNotationPublicId);
  5010. handleDefault = XML_FALSE;
  5011. }
  5012. poolClear(&parser->m_tempPool);
  5013. break;
  5014. case XML_ROLE_ERROR:
  5015. switch (tok) {
  5016. case XML_TOK_PARAM_ENTITY_REF:
  5017. /* PE references in internal subset are
  5018. not allowed within declarations. */
  5019. return XML_ERROR_PARAM_ENTITY_REF;
  5020. case XML_TOK_XML_DECL:
  5021. return XML_ERROR_MISPLACED_XML_PI;
  5022. default:
  5023. return XML_ERROR_SYNTAX;
  5024. }
  5025. #ifdef XML_DTD
  5026. case XML_ROLE_IGNORE_SECT: {
  5027. enum XML_Error result;
  5028. if (parser->m_defaultHandler)
  5029. reportDefault(parser, enc, s, next);
  5030. handleDefault = XML_FALSE;
  5031. result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
  5032. if (result != XML_ERROR_NONE)
  5033. return result;
  5034. else if (! next) {
  5035. parser->m_processor = ignoreSectionProcessor;
  5036. return result;
  5037. }
  5038. } break;
  5039. #endif /* XML_DTD */
  5040. case XML_ROLE_GROUP_OPEN:
  5041. if (parser->m_prologState.level >= parser->m_groupSize) {
  5042. if (parser->m_groupSize) {
  5043. {
  5044. /* Detect and prevent integer overflow */
  5045. if (parser->m_groupSize > (unsigned int)(-1) / 2u) {
  5046. return XML_ERROR_NO_MEMORY;
  5047. }
  5048. { // WINSCP
  5049. char *const new_connector = (char *)REALLOC(
  5050. parser, parser->m_groupConnector, parser->m_groupSize *= 2);
  5051. if (new_connector == NULL) {
  5052. parser->m_groupSize /= 2;
  5053. return XML_ERROR_NO_MEMORY;
  5054. }
  5055. parser->m_groupConnector = new_connector;
  5056. } // WINSCP
  5057. }
  5058. if (dtd->scaffIndex) {
  5059. /* Detect and prevent integer overflow.
  5060. * The preprocessor guard addresses the "always false" warning
  5061. * from -Wtype-limits on platforms where
  5062. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  5063. #if UINT_MAX >= SIZE_MAX
  5064. if (parser->m_groupSize > (size_t)(-1) / sizeof(int)) {
  5065. return XML_ERROR_NO_MEMORY;
  5066. }
  5067. #endif
  5068. { // WINSCP
  5069. int *const new_scaff_index = (int *)REALLOC(
  5070. parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));
  5071. if (new_scaff_index == NULL)
  5072. return XML_ERROR_NO_MEMORY;
  5073. dtd->scaffIndex = new_scaff_index;
  5074. } // WINSCP
  5075. }
  5076. } else {
  5077. parser->m_groupConnector
  5078. = (char *)MALLOC(parser, parser->m_groupSize = 32);
  5079. if (! parser->m_groupConnector) {
  5080. parser->m_groupSize = 0;
  5081. return XML_ERROR_NO_MEMORY;
  5082. }
  5083. }
  5084. }
  5085. parser->m_groupConnector[parser->m_prologState.level] = 0;
  5086. if (dtd->in_eldecl) {
  5087. int myindex = nextScaffoldPart(parser);
  5088. if (myindex < 0)
  5089. return XML_ERROR_NO_MEMORY;
  5090. assert(dtd->scaffIndex != NULL);
  5091. dtd->scaffIndex[dtd->scaffLevel] = myindex;
  5092. dtd->scaffLevel++;
  5093. dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
  5094. if (parser->m_elementDeclHandler)
  5095. handleDefault = XML_FALSE;
  5096. }
  5097. break;
  5098. case XML_ROLE_GROUP_SEQUENCE:
  5099. if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
  5100. return XML_ERROR_SYNTAX;
  5101. parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
  5102. if (dtd->in_eldecl && parser->m_elementDeclHandler)
  5103. handleDefault = XML_FALSE;
  5104. break;
  5105. case XML_ROLE_GROUP_CHOICE:
  5106. if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
  5107. return XML_ERROR_SYNTAX;
  5108. if (dtd->in_eldecl
  5109. && ! parser->m_groupConnector[parser->m_prologState.level]
  5110. && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5111. != XML_CTYPE_MIXED)) {
  5112. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5113. = XML_CTYPE_CHOICE;
  5114. if (parser->m_elementDeclHandler)
  5115. handleDefault = XML_FALSE;
  5116. }
  5117. parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
  5118. break;
  5119. case XML_ROLE_PARAM_ENTITY_REF:
  5120. #ifdef XML_DTD
  5121. case XML_ROLE_INNER_PARAM_ENTITY_REF:
  5122. dtd->hasParamEntityRefs = XML_TRUE;
  5123. if (! parser->m_paramEntityParsing)
  5124. dtd->keepProcessing = dtd->standalone;
  5125. else {
  5126. const XML_Char *name;
  5127. ENTITY *entity;
  5128. name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  5129. next - enc->minBytesPerChar);
  5130. if (! name)
  5131. return XML_ERROR_NO_MEMORY;
  5132. entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
  5133. poolDiscard(&dtd->pool);
  5134. /* first, determine if a check for an existing declaration is needed;
  5135. if yes, check that the entity exists, and that it is internal,
  5136. otherwise call the skipped entity handler
  5137. */
  5138. if (parser->m_prologState.documentEntity
  5139. && (dtd->standalone ? ! parser->m_openInternalEntities
  5140. : ! dtd->hasParamEntityRefs)) {
  5141. if (! entity)
  5142. return XML_ERROR_UNDEFINED_ENTITY;
  5143. else if (! entity->is_internal) {
  5144. /* It's hard to exhaustively search the code to be sure,
  5145. * but there doesn't seem to be a way of executing the
  5146. * following line. There are two cases:
  5147. *
  5148. * If 'standalone' is false, the DTD must have no
  5149. * parameter entities or we wouldn't have passed the outer
  5150. * 'if' statement. That means the only entity in the hash
  5151. * table is the external subset name "#" which cannot be
  5152. * given as a parameter entity name in XML syntax, so the
  5153. * lookup must have returned NULL and we don't even reach
  5154. * the test for an internal entity.
  5155. *
  5156. * If 'standalone' is true, it does not seem to be
  5157. * possible to create entities taking this code path that
  5158. * are not internal entities, so fail the test above.
  5159. *
  5160. * Because this analysis is very uncertain, the code is
  5161. * being left in place and merely removed from the
  5162. * coverage test statistics.
  5163. */
  5164. return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
  5165. }
  5166. } else if (! entity) {
  5167. dtd->keepProcessing = dtd->standalone;
  5168. /* cannot report skipped entities in declarations */
  5169. if ((role == XML_ROLE_PARAM_ENTITY_REF)
  5170. && parser->m_skippedEntityHandler) {
  5171. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
  5172. handleDefault = XML_FALSE;
  5173. }
  5174. break;
  5175. }
  5176. if (entity->open)
  5177. return XML_ERROR_RECURSIVE_ENTITY_REF;
  5178. if (entity->textPtr) {
  5179. enum XML_Error result;
  5180. XML_Bool betweenDecl
  5181. = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
  5182. result = processInternalEntity(parser, entity, betweenDecl);
  5183. if (result != XML_ERROR_NONE)
  5184. return result;
  5185. handleDefault = XML_FALSE;
  5186. break;
  5187. }
  5188. if (parser->m_externalEntityRefHandler) {
  5189. dtd->paramEntityRead = XML_FALSE;
  5190. entity->open = XML_TRUE;
  5191. entityTrackingOnOpen(parser, entity, __LINE__);
  5192. if (! parser->m_externalEntityRefHandler(
  5193. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  5194. entity->systemId, entity->publicId)) {
  5195. entityTrackingOnClose(parser, entity, __LINE__);
  5196. entity->open = XML_FALSE;
  5197. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  5198. }
  5199. entityTrackingOnClose(parser, entity, __LINE__);
  5200. entity->open = XML_FALSE;
  5201. handleDefault = XML_FALSE;
  5202. if (! dtd->paramEntityRead) {
  5203. dtd->keepProcessing = dtd->standalone;
  5204. break;
  5205. }
  5206. } else {
  5207. dtd->keepProcessing = dtd->standalone;
  5208. break;
  5209. }
  5210. }
  5211. #endif /* XML_DTD */
  5212. if (! dtd->standalone && parser->m_notStandaloneHandler
  5213. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  5214. return XML_ERROR_NOT_STANDALONE;
  5215. break;
  5216. /* Element declaration stuff */
  5217. case XML_ROLE_ELEMENT_NAME:
  5218. if (parser->m_elementDeclHandler) {
  5219. parser->m_declElementType = getElementType(parser, enc, s, next);
  5220. if (! parser->m_declElementType)
  5221. return XML_ERROR_NO_MEMORY;
  5222. dtd->scaffLevel = 0;
  5223. dtd->scaffCount = 0;
  5224. dtd->in_eldecl = XML_TRUE;
  5225. handleDefault = XML_FALSE;
  5226. }
  5227. break;
  5228. case XML_ROLE_CONTENT_ANY:
  5229. case XML_ROLE_CONTENT_EMPTY:
  5230. if (dtd->in_eldecl) {
  5231. if (parser->m_elementDeclHandler) {
  5232. XML_Content *content
  5233. = (XML_Content *)MALLOC(parser, sizeof(XML_Content));
  5234. if (! content)
  5235. return XML_ERROR_NO_MEMORY;
  5236. content->quant = XML_CQUANT_NONE;
  5237. content->name = NULL;
  5238. content->numchildren = 0;
  5239. content->children = NULL;
  5240. content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY
  5241. : XML_CTYPE_EMPTY);
  5242. *eventEndPP = s;
  5243. parser->m_elementDeclHandler(
  5244. parser->m_handlerArg, parser->m_declElementType->name, content);
  5245. handleDefault = XML_FALSE;
  5246. }
  5247. dtd->in_eldecl = XML_FALSE;
  5248. }
  5249. break;
  5250. case XML_ROLE_CONTENT_PCDATA:
  5251. if (dtd->in_eldecl) {
  5252. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5253. = XML_CTYPE_MIXED;
  5254. if (parser->m_elementDeclHandler)
  5255. handleDefault = XML_FALSE;
  5256. }
  5257. break;
  5258. case XML_ROLE_CONTENT_ELEMENT:
  5259. quant = XML_CQUANT_NONE;
  5260. goto elementContent;
  5261. case XML_ROLE_CONTENT_ELEMENT_OPT:
  5262. quant = XML_CQUANT_OPT;
  5263. goto elementContent;
  5264. case XML_ROLE_CONTENT_ELEMENT_REP:
  5265. quant = XML_CQUANT_REP;
  5266. goto elementContent;
  5267. case XML_ROLE_CONTENT_ELEMENT_PLUS:
  5268. quant = XML_CQUANT_PLUS;
  5269. elementContent:
  5270. if (dtd->in_eldecl) {
  5271. ELEMENT_TYPE *el;
  5272. const XML_Char *name;
  5273. size_t nameLen;
  5274. const char *nxt
  5275. = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
  5276. int myindex = nextScaffoldPart(parser);
  5277. if (myindex < 0)
  5278. return XML_ERROR_NO_MEMORY;
  5279. dtd->scaffold[myindex].type = XML_CTYPE_NAME;
  5280. dtd->scaffold[myindex].quant = quant;
  5281. el = getElementType(parser, enc, s, nxt);
  5282. if (! el)
  5283. return XML_ERROR_NO_MEMORY;
  5284. name = el->name;
  5285. dtd->scaffold[myindex].name = name;
  5286. nameLen = 0;
  5287. for (; name[nameLen++];)
  5288. ;
  5289. /* Detect and prevent integer overflow */
  5290. if (nameLen > UINT_MAX - dtd->contentStringLen) {
  5291. return XML_ERROR_NO_MEMORY;
  5292. }
  5293. dtd->contentStringLen += (unsigned)nameLen;
  5294. if (parser->m_elementDeclHandler)
  5295. handleDefault = XML_FALSE;
  5296. }
  5297. break;
  5298. case XML_ROLE_GROUP_CLOSE:
  5299. quant = XML_CQUANT_NONE;
  5300. goto closeGroup;
  5301. case XML_ROLE_GROUP_CLOSE_OPT:
  5302. quant = XML_CQUANT_OPT;
  5303. goto closeGroup;
  5304. case XML_ROLE_GROUP_CLOSE_REP:
  5305. quant = XML_CQUANT_REP;
  5306. goto closeGroup;
  5307. case XML_ROLE_GROUP_CLOSE_PLUS:
  5308. quant = XML_CQUANT_PLUS;
  5309. closeGroup:
  5310. if (dtd->in_eldecl) {
  5311. if (parser->m_elementDeclHandler)
  5312. handleDefault = XML_FALSE;
  5313. dtd->scaffLevel--;
  5314. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
  5315. if (dtd->scaffLevel == 0) {
  5316. if (! handleDefault) {
  5317. XML_Content *model = build_model(parser);
  5318. if (! model)
  5319. return XML_ERROR_NO_MEMORY;
  5320. *eventEndPP = s;
  5321. parser->m_elementDeclHandler(
  5322. parser->m_handlerArg, parser->m_declElementType->name, model);
  5323. }
  5324. dtd->in_eldecl = XML_FALSE;
  5325. dtd->contentStringLen = 0;
  5326. }
  5327. }
  5328. break;
  5329. /* End element declaration stuff */
  5330. case XML_ROLE_PI:
  5331. if (! reportProcessingInstruction(parser, enc, s, next))
  5332. return XML_ERROR_NO_MEMORY;
  5333. handleDefault = XML_FALSE;
  5334. break;
  5335. case XML_ROLE_COMMENT:
  5336. if (! reportComment(parser, enc, s, next))
  5337. return XML_ERROR_NO_MEMORY;
  5338. handleDefault = XML_FALSE;
  5339. break;
  5340. case XML_ROLE_NONE:
  5341. switch (tok) {
  5342. case XML_TOK_BOM:
  5343. handleDefault = XML_FALSE;
  5344. break;
  5345. }
  5346. break;
  5347. case XML_ROLE_DOCTYPE_NONE:
  5348. if (parser->m_startDoctypeDeclHandler)
  5349. handleDefault = XML_FALSE;
  5350. break;
  5351. case XML_ROLE_ENTITY_NONE:
  5352. if (dtd->keepProcessing && parser->m_entityDeclHandler)
  5353. handleDefault = XML_FALSE;
  5354. break;
  5355. case XML_ROLE_NOTATION_NONE:
  5356. if (parser->m_notationDeclHandler)
  5357. handleDefault = XML_FALSE;
  5358. break;
  5359. case XML_ROLE_ATTLIST_NONE:
  5360. if (dtd->keepProcessing && parser->m_attlistDeclHandler)
  5361. handleDefault = XML_FALSE;
  5362. break;
  5363. case XML_ROLE_ELEMENT_NONE:
  5364. if (parser->m_elementDeclHandler)
  5365. handleDefault = XML_FALSE;
  5366. break;
  5367. } /* end of big switch */
  5368. if (handleDefault && parser->m_defaultHandler)
  5369. reportDefault(parser, enc, s, next);
  5370. switch (parser->m_parsingStatus.parsing) {
  5371. case XML_SUSPENDED:
  5372. *nextPtr = next;
  5373. return XML_ERROR_NONE;
  5374. case XML_FINISHED:
  5375. return XML_ERROR_ABORTED;
  5376. default:
  5377. s = next;
  5378. tok = XmlPrologTok(enc, s, end, &next);
  5379. }
  5380. }
  5381. } // WINSCP
  5382. /* not reached */
  5383. }
  5384. static enum XML_Error PTRCALL
  5385. epilogProcessor(XML_Parser parser, const char *s, const char *end,
  5386. const char **nextPtr) {
  5387. parser->m_processor = epilogProcessor;
  5388. parser->m_eventPtr = s;
  5389. for (;;) {
  5390. const char *next = NULL;
  5391. int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  5392. #if XML_GE == 1
  5393. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  5394. XML_ACCOUNT_DIRECT)) {
  5395. accountingOnAbort(parser);
  5396. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  5397. }
  5398. #endif
  5399. parser->m_eventEndPtr = next;
  5400. switch (tok) {
  5401. /* report partial linebreak - it might be the last token */
  5402. case -XML_TOK_PROLOG_S:
  5403. if (parser->m_defaultHandler) {
  5404. reportDefault(parser, parser->m_encoding, s, next);
  5405. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  5406. return XML_ERROR_ABORTED;
  5407. }
  5408. *nextPtr = next;
  5409. return XML_ERROR_NONE;
  5410. case XML_TOK_NONE:
  5411. *nextPtr = s;
  5412. return XML_ERROR_NONE;
  5413. case XML_TOK_PROLOG_S:
  5414. if (parser->m_defaultHandler)
  5415. reportDefault(parser, parser->m_encoding, s, next);
  5416. break;
  5417. case XML_TOK_PI:
  5418. if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))
  5419. return XML_ERROR_NO_MEMORY;
  5420. break;
  5421. case XML_TOK_COMMENT:
  5422. if (! reportComment(parser, parser->m_encoding, s, next))
  5423. return XML_ERROR_NO_MEMORY;
  5424. break;
  5425. case XML_TOK_INVALID:
  5426. parser->m_eventPtr = next;
  5427. return XML_ERROR_INVALID_TOKEN;
  5428. case XML_TOK_PARTIAL:
  5429. if (! parser->m_parsingStatus.finalBuffer) {
  5430. *nextPtr = s;
  5431. return XML_ERROR_NONE;
  5432. }
  5433. return XML_ERROR_UNCLOSED_TOKEN;
  5434. case XML_TOK_PARTIAL_CHAR:
  5435. if (! parser->m_parsingStatus.finalBuffer) {
  5436. *nextPtr = s;
  5437. return XML_ERROR_NONE;
  5438. }
  5439. return XML_ERROR_PARTIAL_CHAR;
  5440. default:
  5441. return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
  5442. }
  5443. parser->m_eventPtr = s = next;
  5444. switch (parser->m_parsingStatus.parsing) {
  5445. case XML_SUSPENDED:
  5446. *nextPtr = next;
  5447. return XML_ERROR_NONE;
  5448. case XML_FINISHED:
  5449. return XML_ERROR_ABORTED;
  5450. default:;
  5451. }
  5452. }
  5453. }
  5454. static enum XML_Error
  5455. processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
  5456. const char *textStart, *textEnd;
  5457. const char *next;
  5458. enum XML_Error result;
  5459. OPEN_INTERNAL_ENTITY *openEntity;
  5460. if (parser->m_freeInternalEntities) {
  5461. openEntity = parser->m_freeInternalEntities;
  5462. parser->m_freeInternalEntities = openEntity->next;
  5463. } else {
  5464. openEntity
  5465. = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
  5466. if (! openEntity)
  5467. return XML_ERROR_NO_MEMORY;
  5468. }
  5469. entity->open = XML_TRUE;
  5470. #if XML_GE == 1
  5471. entityTrackingOnOpen(parser, entity, __LINE__);
  5472. #endif
  5473. entity->processed = 0;
  5474. openEntity->next = parser->m_openInternalEntities;
  5475. parser->m_openInternalEntities = openEntity;
  5476. openEntity->entity = entity;
  5477. openEntity->startTagLevel = parser->m_tagLevel;
  5478. openEntity->betweenDecl = betweenDecl;
  5479. openEntity->internalEventPtr = NULL;
  5480. openEntity->internalEventEndPtr = NULL;
  5481. textStart = (const char *)entity->textPtr;
  5482. textEnd = (const char *)(entity->textPtr + entity->textLen);
  5483. /* Set a safe default value in case 'next' does not get set */
  5484. next = textStart;
  5485. if (entity->is_param) {
  5486. int tok
  5487. = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
  5488. result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
  5489. tok, next, &next, XML_FALSE, XML_FALSE,
  5490. XML_ACCOUNT_ENTITY_EXPANSION);
  5491. } else {
  5492. result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
  5493. textStart, textEnd, &next, XML_FALSE,
  5494. XML_ACCOUNT_ENTITY_EXPANSION);
  5495. }
  5496. if (result == XML_ERROR_NONE) {
  5497. if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
  5498. entity->processed = (int)(next - textStart);
  5499. parser->m_processor = internalEntityProcessor;
  5500. } else if (parser->m_openInternalEntities->entity == entity) {
  5501. #if XML_GE == 1
  5502. entityTrackingOnClose(parser, entity, __LINE__);
  5503. #endif /* XML_GE == 1 */
  5504. entity->open = XML_FALSE;
  5505. parser->m_openInternalEntities = openEntity->next;
  5506. /* put openEntity back in list of free instances */
  5507. openEntity->next = parser->m_freeInternalEntities;
  5508. parser->m_freeInternalEntities = openEntity;
  5509. }
  5510. }
  5511. return result;
  5512. }
  5513. static enum XML_Error PTRCALL
  5514. internalEntityProcessor(XML_Parser parser, const char *s, const char *end,
  5515. const char **nextPtr) {
  5516. ENTITY *entity;
  5517. const char *textStart, *textEnd;
  5518. const char *next;
  5519. enum XML_Error result;
  5520. OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
  5521. if (! openEntity)
  5522. return XML_ERROR_UNEXPECTED_STATE;
  5523. entity = openEntity->entity;
  5524. textStart = ((const char *)entity->textPtr) + entity->processed;
  5525. textEnd = (const char *)(entity->textPtr + entity->textLen);
  5526. /* Set a safe default value in case 'next' does not get set */
  5527. next = textStart;
  5528. if (entity->is_param) {
  5529. int tok
  5530. = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
  5531. result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
  5532. tok, next, &next, XML_FALSE, XML_TRUE,
  5533. XML_ACCOUNT_ENTITY_EXPANSION);
  5534. } else {
  5535. result = doContent(parser, openEntity->startTagLevel,
  5536. parser->m_internalEncoding, textStart, textEnd, &next,
  5537. XML_FALSE, XML_ACCOUNT_ENTITY_EXPANSION);
  5538. }
  5539. if (result != XML_ERROR_NONE)
  5540. return result;
  5541. if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
  5542. entity->processed = (int)(next - (const char *)entity->textPtr);
  5543. return result;
  5544. }
  5545. #if XML_GE == 1
  5546. entityTrackingOnClose(parser, entity, __LINE__);
  5547. #endif
  5548. entity->open = XML_FALSE;
  5549. parser->m_openInternalEntities = openEntity->next;
  5550. /* put openEntity back in list of free instances */
  5551. openEntity->next = parser->m_freeInternalEntities;
  5552. parser->m_freeInternalEntities = openEntity;
  5553. // If there are more open entities we want to stop right here and have the
  5554. // upcoming call to XML_ResumeParser continue with entity content, or it would
  5555. // be ignored altogether.
  5556. if (parser->m_openInternalEntities != NULL
  5557. && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
  5558. return XML_ERROR_NONE;
  5559. }
  5560. if (entity->is_param) {
  5561. int tok;
  5562. parser->m_processor = prologProcessor;
  5563. tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  5564. return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
  5565. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
  5566. XML_ACCOUNT_DIRECT);
  5567. } else {
  5568. parser->m_processor = contentProcessor;
  5569. /* see externalEntityContentProcessor vs contentProcessor */
  5570. result = doContent(parser, parser->m_parentParser ? 1 : 0,
  5571. parser->m_encoding, s, end, nextPtr,
  5572. (XML_Bool)! parser->m_parsingStatus.finalBuffer,
  5573. XML_ACCOUNT_DIRECT);
  5574. if (result == XML_ERROR_NONE) {
  5575. if (! storeRawNames(parser))
  5576. return XML_ERROR_NO_MEMORY;
  5577. }
  5578. return result;
  5579. }
  5580. }
  5581. static enum XML_Error PTRCALL
  5582. errorProcessor(XML_Parser parser, const char *s, const char *end,
  5583. const char **nextPtr) {
  5584. UNUSED_P(s);
  5585. UNUSED_P(end);
  5586. UNUSED_P(nextPtr);
  5587. return parser->m_errorCode;
  5588. }
  5589. static enum XML_Error
  5590. storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
  5591. const char *ptr, const char *end, STRING_POOL *pool,
  5592. enum XML_Account account) {
  5593. enum XML_Error result
  5594. = appendAttributeValue(parser, enc, isCdata, ptr, end, pool, account);
  5595. if (result)
  5596. return result;
  5597. if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
  5598. poolChop(pool);
  5599. if (! poolAppendChar(pool, XML_T('\0')))
  5600. return XML_ERROR_NO_MEMORY;
  5601. return XML_ERROR_NONE;
  5602. }
  5603. static enum XML_Error
  5604. appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
  5605. const char *ptr, const char *end, STRING_POOL *pool,
  5606. enum XML_Account account) {
  5607. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  5608. #ifndef XML_DTD
  5609. UNUSED_P(account);
  5610. #endif
  5611. for (;;) {
  5612. const char *next
  5613. = ptr; /* XmlAttributeValueTok doesn't always set the last arg */
  5614. int tok = XmlAttributeValueTok(enc, ptr, end, &next);
  5615. #if XML_GE == 1
  5616. if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) {
  5617. accountingOnAbort(parser);
  5618. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  5619. }
  5620. #endif
  5621. switch (tok) {
  5622. case XML_TOK_NONE:
  5623. return XML_ERROR_NONE;
  5624. case XML_TOK_INVALID:
  5625. if (enc == parser->m_encoding)
  5626. parser->m_eventPtr = next;
  5627. return XML_ERROR_INVALID_TOKEN;
  5628. case XML_TOK_PARTIAL:
  5629. if (enc == parser->m_encoding)
  5630. parser->m_eventPtr = ptr;
  5631. return XML_ERROR_INVALID_TOKEN;
  5632. case XML_TOK_CHAR_REF: {
  5633. XML_Char buf[XML_ENCODE_MAX];
  5634. int i;
  5635. int n = XmlCharRefNumber(enc, ptr);
  5636. if (n < 0) {
  5637. if (enc == parser->m_encoding)
  5638. parser->m_eventPtr = ptr;
  5639. return XML_ERROR_BAD_CHAR_REF;
  5640. }
  5641. if (! isCdata && n == 0x20 /* space */
  5642. && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
  5643. break;
  5644. n = XmlEncode(n, (ICHAR *)buf);
  5645. /* The XmlEncode() functions can never return 0 here. That
  5646. * error return happens if the code point passed in is either
  5647. * negative or greater than or equal to 0x110000. The
  5648. * XmlCharRefNumber() functions will all return a number
  5649. * strictly less than 0x110000 or a negative value if an error
  5650. * occurred. The negative value is intercepted above, so
  5651. * XmlEncode() is never passed a value it might return an
  5652. * error for.
  5653. */
  5654. for (i = 0; i < n; i++) {
  5655. if (! poolAppendChar(pool, buf[i]))
  5656. return XML_ERROR_NO_MEMORY;
  5657. }
  5658. } break;
  5659. case XML_TOK_DATA_CHARS:
  5660. if (! poolAppend(pool, enc, ptr, next))
  5661. return XML_ERROR_NO_MEMORY;
  5662. break;
  5663. case XML_TOK_TRAILING_CR:
  5664. next = ptr + enc->minBytesPerChar;
  5665. /* fall through */
  5666. case XML_TOK_ATTRIBUTE_VALUE_S:
  5667. case XML_TOK_DATA_NEWLINE:
  5668. if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
  5669. break;
  5670. if (! poolAppendChar(pool, 0x20))
  5671. return XML_ERROR_NO_MEMORY;
  5672. break;
  5673. case XML_TOK_ENTITY_REF: {
  5674. const XML_Char *name;
  5675. ENTITY *entity;
  5676. char checkEntityDecl;
  5677. XML_Char ch = (XML_Char)XmlPredefinedEntityName(
  5678. enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);
  5679. if (ch) {
  5680. #if XML_GE == 1
  5681. /* NOTE: We are replacing 4-6 characters original input for 1 character
  5682. * so there is no amplification and hence recording without
  5683. * protection. */
  5684. accountingDiffTolerated(parser, tok, (char *)&ch,
  5685. ((char *)&ch) + sizeof(XML_Char), __LINE__,
  5686. XML_ACCOUNT_ENTITY_EXPANSION);
  5687. #endif /* XML_GE == 1 */
  5688. if (! poolAppendChar(pool, ch))
  5689. return XML_ERROR_NO_MEMORY;
  5690. break;
  5691. }
  5692. name = poolStoreString(&parser->m_temp2Pool, enc,
  5693. ptr + enc->minBytesPerChar,
  5694. next - enc->minBytesPerChar);
  5695. if (! name)
  5696. return XML_ERROR_NO_MEMORY;
  5697. entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
  5698. poolDiscard(&parser->m_temp2Pool);
  5699. /* First, determine if a check for an existing declaration is needed;
  5700. if yes, check that the entity exists, and that it is internal.
  5701. */
  5702. if (pool == &dtd->pool) /* are we called from prolog? */
  5703. checkEntityDecl =
  5704. #ifdef XML_DTD
  5705. parser->m_prologState.documentEntity &&
  5706. #endif /* XML_DTD */
  5707. (dtd->standalone ? ! parser->m_openInternalEntities
  5708. : ! dtd->hasParamEntityRefs);
  5709. else /* if (pool == &parser->m_tempPool): we are called from content */
  5710. checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;
  5711. if (checkEntityDecl) {
  5712. if (! entity)
  5713. return XML_ERROR_UNDEFINED_ENTITY;
  5714. else if (! entity->is_internal)
  5715. return XML_ERROR_ENTITY_DECLARED_IN_PE;
  5716. } else if (! entity) {
  5717. /* Cannot report skipped entity here - see comments on
  5718. parser->m_skippedEntityHandler.
  5719. if (parser->m_skippedEntityHandler)
  5720. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  5721. */
  5722. /* Cannot call the default handler because this would be
  5723. out of sync with the call to the startElementHandler.
  5724. if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
  5725. reportDefault(parser, enc, ptr, next);
  5726. */
  5727. break;
  5728. }
  5729. if (entity->open) {
  5730. if (enc == parser->m_encoding) {
  5731. /* It does not appear that this line can be executed.
  5732. *
  5733. * The "if (entity->open)" check catches recursive entity
  5734. * definitions. In order to be called with an open
  5735. * entity, it must have gone through this code before and
  5736. * been through the recursive call to
  5737. * appendAttributeValue() some lines below. That call
  5738. * sets the local encoding ("enc") to the parser's
  5739. * internal encoding (internal_utf8 or internal_utf16),
  5740. * which can never be the same as the principle encoding.
  5741. * It doesn't appear there is another code path that gets
  5742. * here with entity->open being TRUE.
  5743. *
  5744. * Since it is not certain that this logic is watertight,
  5745. * we keep the line and merely exclude it from coverage
  5746. * tests.
  5747. */
  5748. parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
  5749. }
  5750. return XML_ERROR_RECURSIVE_ENTITY_REF;
  5751. }
  5752. if (entity->notation) {
  5753. if (enc == parser->m_encoding)
  5754. parser->m_eventPtr = ptr;
  5755. return XML_ERROR_BINARY_ENTITY_REF;
  5756. }
  5757. if (! entity->textPtr) {
  5758. if (enc == parser->m_encoding)
  5759. parser->m_eventPtr = ptr;
  5760. return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
  5761. } else {
  5762. enum XML_Error result;
  5763. const XML_Char *textEnd = entity->textPtr + entity->textLen;
  5764. entity->open = XML_TRUE;
  5765. #if XML_GE == 1
  5766. entityTrackingOnOpen(parser, entity, __LINE__);
  5767. #endif
  5768. result = appendAttributeValue(parser, parser->m_internalEncoding,
  5769. isCdata, (const char *)entity->textPtr,
  5770. (const char *)textEnd, pool,
  5771. XML_ACCOUNT_ENTITY_EXPANSION);
  5772. #if XML_GE == 1
  5773. entityTrackingOnClose(parser, entity, __LINE__);
  5774. #endif
  5775. entity->open = XML_FALSE;
  5776. if (result)
  5777. return result;
  5778. }
  5779. } break;
  5780. default:
  5781. /* The only token returned by XmlAttributeValueTok() that does
  5782. * not have an explicit case here is XML_TOK_PARTIAL_CHAR.
  5783. * Getting that would require an entity name to contain an
  5784. * incomplete XML character (e.g. \xE2\x82); however previous
  5785. * tokenisers will have already recognised and rejected such
  5786. * names before XmlAttributeValueTok() gets a look-in. This
  5787. * default case should be retained as a safety net, but the code
  5788. * excluded from coverage tests.
  5789. *
  5790. * LCOV_EXCL_START
  5791. */
  5792. if (enc == parser->m_encoding)
  5793. parser->m_eventPtr = ptr;
  5794. return XML_ERROR_UNEXPECTED_STATE;
  5795. /* LCOV_EXCL_STOP */
  5796. }
  5797. ptr = next;
  5798. }
  5799. /* not reached */
  5800. }
  5801. #if XML_GE == 1
  5802. static enum XML_Error
  5803. storeEntityValue(XML_Parser parser, const ENCODING *enc,
  5804. const char *entityTextPtr, const char *entityTextEnd,
  5805. enum XML_Account account) {
  5806. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  5807. STRING_POOL *pool = &(dtd->entityValuePool);
  5808. enum XML_Error result = XML_ERROR_NONE;
  5809. # ifdef XML_DTD
  5810. int oldInEntityValue = parser->m_prologState.inEntityValue;
  5811. parser->m_prologState.inEntityValue = 1;
  5812. # else
  5813. UNUSED_P(account);
  5814. # endif /* XML_DTD */
  5815. /* never return Null for the value argument in EntityDeclHandler,
  5816. since this would indicate an external entity; therefore we
  5817. have to make sure that entityValuePool.start is not null */
  5818. if (! pool->blocks) {
  5819. if (! poolGrow(pool))
  5820. return XML_ERROR_NO_MEMORY;
  5821. }
  5822. for (;;) {
  5823. const char *next
  5824. = entityTextPtr; /* XmlEntityValueTok doesn't always set the last arg */
  5825. int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
  5826. if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__,
  5827. account)) {
  5828. accountingOnAbort(parser);
  5829. result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  5830. goto endEntityValue;
  5831. }
  5832. switch (tok) {
  5833. case XML_TOK_PARAM_ENTITY_REF:
  5834. # ifdef XML_DTD
  5835. if (parser->m_isParamEntity || enc != parser->m_encoding) {
  5836. const XML_Char *name;
  5837. ENTITY *entity;
  5838. name = poolStoreString(&parser->m_tempPool, enc,
  5839. entityTextPtr + enc->minBytesPerChar,
  5840. next - enc->minBytesPerChar);
  5841. if (! name) {
  5842. result = XML_ERROR_NO_MEMORY;
  5843. goto endEntityValue;
  5844. }
  5845. entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
  5846. poolDiscard(&parser->m_tempPool);
  5847. if (! entity) {
  5848. /* not a well-formedness error - see XML 1.0: WFC Entity Declared */
  5849. /* cannot report skipped entity here - see comments on
  5850. parser->m_skippedEntityHandler
  5851. if (parser->m_skippedEntityHandler)
  5852. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  5853. */
  5854. dtd->keepProcessing = dtd->standalone;
  5855. goto endEntityValue;
  5856. }
  5857. if (entity->open || (entity == parser->m_declEntity)) {
  5858. if (enc == parser->m_encoding)
  5859. parser->m_eventPtr = entityTextPtr;
  5860. result = XML_ERROR_RECURSIVE_ENTITY_REF;
  5861. goto endEntityValue;
  5862. }
  5863. if (entity->systemId) {
  5864. if (parser->m_externalEntityRefHandler) {
  5865. dtd->paramEntityRead = XML_FALSE;
  5866. entity->open = XML_TRUE;
  5867. entityTrackingOnOpen(parser, entity, __LINE__);
  5868. if (! parser->m_externalEntityRefHandler(
  5869. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  5870. entity->systemId, entity->publicId)) {
  5871. entityTrackingOnClose(parser, entity, __LINE__);
  5872. entity->open = XML_FALSE;
  5873. result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  5874. goto endEntityValue;
  5875. }
  5876. entityTrackingOnClose(parser, entity, __LINE__);
  5877. entity->open = XML_FALSE;
  5878. if (! dtd->paramEntityRead)
  5879. dtd->keepProcessing = dtd->standalone;
  5880. } else
  5881. dtd->keepProcessing = dtd->standalone;
  5882. } else {
  5883. entity->open = XML_TRUE;
  5884. entityTrackingOnOpen(parser, entity, __LINE__);
  5885. result = storeEntityValue(
  5886. parser, parser->m_internalEncoding, (const char *)entity->textPtr,
  5887. (const char *)(entity->textPtr + entity->textLen),
  5888. XML_ACCOUNT_ENTITY_EXPANSION);
  5889. entityTrackingOnClose(parser, entity, __LINE__);
  5890. entity->open = XML_FALSE;
  5891. if (result)
  5892. goto endEntityValue;
  5893. }
  5894. break;
  5895. }
  5896. # endif /* XML_DTD */
  5897. /* In the internal subset, PE references are not legal
  5898. within markup declarations, e.g entity values in this case. */
  5899. parser->m_eventPtr = entityTextPtr;
  5900. result = XML_ERROR_PARAM_ENTITY_REF;
  5901. goto endEntityValue;
  5902. case XML_TOK_NONE:
  5903. result = XML_ERROR_NONE;
  5904. goto endEntityValue;
  5905. case XML_TOK_ENTITY_REF:
  5906. case XML_TOK_DATA_CHARS:
  5907. if (! poolAppend(pool, enc, entityTextPtr, next)) {
  5908. result = XML_ERROR_NO_MEMORY;
  5909. goto endEntityValue;
  5910. }
  5911. break;
  5912. case XML_TOK_TRAILING_CR:
  5913. next = entityTextPtr + enc->minBytesPerChar;
  5914. /* fall through */
  5915. case XML_TOK_DATA_NEWLINE:
  5916. if (pool->end == pool->ptr && ! poolGrow(pool)) {
  5917. result = XML_ERROR_NO_MEMORY;
  5918. goto endEntityValue;
  5919. }
  5920. *(pool->ptr)++ = 0xA;
  5921. break;
  5922. case XML_TOK_CHAR_REF: {
  5923. XML_Char buf[XML_ENCODE_MAX];
  5924. int i;
  5925. int n = XmlCharRefNumber(enc, entityTextPtr);
  5926. if (n < 0) {
  5927. if (enc == parser->m_encoding)
  5928. parser->m_eventPtr = entityTextPtr;
  5929. result = XML_ERROR_BAD_CHAR_REF;
  5930. goto endEntityValue;
  5931. }
  5932. n = XmlEncode(n, (ICHAR *)buf);
  5933. /* The XmlEncode() functions can never return 0 here. That
  5934. * error return happens if the code point passed in is either
  5935. * negative or greater than or equal to 0x110000. The
  5936. * XmlCharRefNumber() functions will all return a number
  5937. * strictly less than 0x110000 or a negative value if an error
  5938. * occurred. The negative value is intercepted above, so
  5939. * XmlEncode() is never passed a value it might return an
  5940. * error for.
  5941. */
  5942. for (i = 0; i < n; i++) {
  5943. if (pool->end == pool->ptr && ! poolGrow(pool)) {
  5944. result = XML_ERROR_NO_MEMORY;
  5945. goto endEntityValue;
  5946. }
  5947. *(pool->ptr)++ = buf[i];
  5948. }
  5949. } break;
  5950. case XML_TOK_PARTIAL:
  5951. if (enc == parser->m_encoding)
  5952. parser->m_eventPtr = entityTextPtr;
  5953. result = XML_ERROR_INVALID_TOKEN;
  5954. goto endEntityValue;
  5955. case XML_TOK_INVALID:
  5956. if (enc == parser->m_encoding)
  5957. parser->m_eventPtr = next;
  5958. result = XML_ERROR_INVALID_TOKEN;
  5959. goto endEntityValue;
  5960. default:
  5961. /* This default case should be unnecessary -- all the tokens
  5962. * that XmlEntityValueTok() can return have their own explicit
  5963. * cases -- but should be retained for safety. We do however
  5964. * exclude it from the coverage statistics.
  5965. *
  5966. * LCOV_EXCL_START
  5967. */
  5968. if (enc == parser->m_encoding)
  5969. parser->m_eventPtr = entityTextPtr;
  5970. result = XML_ERROR_UNEXPECTED_STATE;
  5971. goto endEntityValue;
  5972. /* LCOV_EXCL_STOP */
  5973. }
  5974. entityTextPtr = next;
  5975. }
  5976. endEntityValue:
  5977. # ifdef XML_DTD
  5978. parser->m_prologState.inEntityValue = oldInEntityValue;
  5979. # endif /* XML_DTD */
  5980. return result;
  5981. }
  5982. #else /* XML_GE == 0 */
  5983. static enum XML_Error
  5984. storeSelfEntityValue(XML_Parser parser, ENTITY *entity) {
  5985. // This will store "&amp;entity123;" in entity->textPtr
  5986. // to end up as "&entity123;" in the handler.
  5987. const char *const entity_start = "&amp;";
  5988. const char *const entity_end = ";";
  5989. STRING_POOL *const pool = &(parser->m_dtd->entityValuePool);
  5990. if (! poolAppendString(pool, entity_start)
  5991. || ! poolAppendString(pool, entity->name)
  5992. || ! poolAppendString(pool, entity_end)) {
  5993. poolDiscard(pool);
  5994. return XML_ERROR_NO_MEMORY;
  5995. }
  5996. entity->textPtr = poolStart(pool);
  5997. entity->textLen = (int)(poolLength(pool));
  5998. poolFinish(pool);
  5999. return XML_ERROR_NONE;
  6000. }
  6001. #endif /* XML_GE == 0 */
  6002. static void FASTCALL
  6003. normalizeLines(XML_Char *s) {
  6004. XML_Char *p;
  6005. for (;; s++) {
  6006. if (*s == XML_T('\0'))
  6007. return;
  6008. if (*s == 0xD)
  6009. break;
  6010. }
  6011. p = s;
  6012. do {
  6013. if (*s == 0xD) {
  6014. *p++ = 0xA;
  6015. if (*++s == 0xA)
  6016. s++;
  6017. } else
  6018. *p++ = *s++;
  6019. } while (*s);
  6020. *p = XML_T('\0');
  6021. }
  6022. static int
  6023. reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
  6024. const char *start, const char *end) {
  6025. const XML_Char *target;
  6026. XML_Char *data;
  6027. const char *tem;
  6028. if (! parser->m_processingInstructionHandler) {
  6029. if (parser->m_defaultHandler)
  6030. reportDefault(parser, enc, start, end);
  6031. return 1;
  6032. }
  6033. start += enc->minBytesPerChar * 2;
  6034. tem = start + XmlNameLength(enc, start);
  6035. target = poolStoreString(&parser->m_tempPool, enc, start, tem);
  6036. if (! target)
  6037. return 0;
  6038. poolFinish(&parser->m_tempPool);
  6039. data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),
  6040. end - enc->minBytesPerChar * 2);
  6041. if (! data)
  6042. return 0;
  6043. normalizeLines(data);
  6044. parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
  6045. poolClear(&parser->m_tempPool);
  6046. return 1;
  6047. }
  6048. static int
  6049. reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
  6050. const char *end) {
  6051. XML_Char *data;
  6052. if (! parser->m_commentHandler) {
  6053. if (parser->m_defaultHandler)
  6054. reportDefault(parser, enc, start, end);
  6055. return 1;
  6056. }
  6057. data = poolStoreString(&parser->m_tempPool, enc,
  6058. start + enc->minBytesPerChar * 4,
  6059. end - enc->minBytesPerChar * 3);
  6060. if (! data)
  6061. return 0;
  6062. normalizeLines(data);
  6063. parser->m_commentHandler(parser->m_handlerArg, data);
  6064. poolClear(&parser->m_tempPool);
  6065. return 1;
  6066. }
  6067. static void
  6068. reportDefault(XML_Parser parser, const ENCODING *enc, const char *s,
  6069. const char *end) {
  6070. if (MUST_CONVERT(enc, s)) {
  6071. enum XML_Convert_Result convert_res;
  6072. const char **eventPP;
  6073. const char **eventEndPP;
  6074. if (enc == parser->m_encoding) {
  6075. eventPP = &parser->m_eventPtr;
  6076. eventEndPP = &parser->m_eventEndPtr;
  6077. } else {
  6078. /* To get here, two things must be true; the parser must be
  6079. * using a character encoding that is not the same as the
  6080. * encoding passed in, and the encoding passed in must need
  6081. * conversion to the internal format (UTF-8 unless XML_UNICODE
  6082. * is defined). The only occasions on which the encoding passed
  6083. * in is not the same as the parser's encoding are when it is
  6084. * the internal encoding (e.g. a previously defined parameter
  6085. * entity, already converted to internal format). This by
  6086. * definition doesn't need conversion, so the whole branch never
  6087. * gets executed.
  6088. *
  6089. * For safety's sake we don't delete these lines and merely
  6090. * exclude them from coverage statistics.
  6091. *
  6092. * LCOV_EXCL_START
  6093. */
  6094. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  6095. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  6096. /* LCOV_EXCL_STOP */
  6097. }
  6098. do {
  6099. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  6100. convert_res
  6101. = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  6102. *eventEndPP = s;
  6103. parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,
  6104. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  6105. *eventPP = s;
  6106. } while ((convert_res != XML_CONVERT_COMPLETED)
  6107. && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
  6108. } else
  6109. parser->m_defaultHandler(
  6110. parser->m_handlerArg, (const XML_Char *)s,
  6111. (int)((const XML_Char *)end - (const XML_Char *)s));
  6112. }
  6113. static int
  6114. defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
  6115. XML_Bool isId, const XML_Char *value, XML_Parser parser) {
  6116. DEFAULT_ATTRIBUTE *att;
  6117. if (value || isId) {
  6118. /* The handling of default attributes gets messed up if we have
  6119. a default which duplicates a non-default. */
  6120. int i;
  6121. for (i = 0; i < type->nDefaultAtts; i++)
  6122. if (attId == type->defaultAtts[i].id)
  6123. return 1;
  6124. if (isId && ! type->idAtt && ! attId->xmlns)
  6125. type->idAtt = attId;
  6126. }
  6127. if (type->nDefaultAtts == type->allocDefaultAtts) {
  6128. if (type->allocDefaultAtts == 0) {
  6129. type->allocDefaultAtts = 8;
  6130. type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(
  6131. parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
  6132. if (! type->defaultAtts) {
  6133. type->allocDefaultAtts = 0;
  6134. return 0;
  6135. }
  6136. } else {
  6137. DEFAULT_ATTRIBUTE *temp;
  6138. /* Detect and prevent integer overflow */
  6139. if (type->allocDefaultAtts > INT_MAX / 2) {
  6140. return 0;
  6141. }
  6142. { // WINSCP
  6143. int count = type->allocDefaultAtts * 2;
  6144. /* Detect and prevent integer overflow.
  6145. * The preprocessor guard addresses the "always false" warning
  6146. * from -Wtype-limits on platforms where
  6147. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  6148. #if UINT_MAX >= SIZE_MAX
  6149. if ((unsigned)count > (size_t)(-1) / sizeof(DEFAULT_ATTRIBUTE)) {
  6150. return 0;
  6151. }
  6152. #endif
  6153. temp = (DEFAULT_ATTRIBUTE *)REALLOC(parser, type->defaultAtts,
  6154. (count * sizeof(DEFAULT_ATTRIBUTE)));
  6155. if (temp == NULL)
  6156. return 0;
  6157. type->allocDefaultAtts = count;
  6158. type->defaultAtts = temp;
  6159. } // WINSCP
  6160. }
  6161. }
  6162. att = type->defaultAtts + type->nDefaultAtts;
  6163. att->id = attId;
  6164. att->value = value;
  6165. att->isCdata = isCdata;
  6166. if (! isCdata)
  6167. attId->maybeTokenized = XML_TRUE;
  6168. type->nDefaultAtts += 1;
  6169. return 1;
  6170. }
  6171. static int
  6172. setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {
  6173. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6174. const XML_Char *name;
  6175. for (name = elementType->name; *name; name++) {
  6176. if (*name == XML_T(ASCII_COLON)) {
  6177. PREFIX *prefix;
  6178. const XML_Char *s;
  6179. for (s = elementType->name; s != name; s++) {
  6180. if (! poolAppendChar(&dtd->pool, *s))
  6181. return 0;
  6182. }
  6183. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6184. return 0;
  6185. prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
  6186. sizeof(PREFIX));
  6187. if (! prefix)
  6188. return 0;
  6189. if (prefix->name == poolStart(&dtd->pool))
  6190. poolFinish(&dtd->pool);
  6191. else
  6192. poolDiscard(&dtd->pool);
  6193. elementType->prefix = prefix;
  6194. break;
  6195. }
  6196. }
  6197. return 1;
  6198. }
  6199. static ATTRIBUTE_ID *
  6200. getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
  6201. const char *end) {
  6202. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6203. ATTRIBUTE_ID *id;
  6204. const XML_Char *name;
  6205. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6206. return NULL;
  6207. name = poolStoreString(&dtd->pool, enc, start, end);
  6208. if (! name)
  6209. return NULL;
  6210. /* skip quotation mark - its storage will be reused (like in name[-1]) */
  6211. ++name;
  6212. id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,
  6213. sizeof(ATTRIBUTE_ID));
  6214. if (! id)
  6215. return NULL;
  6216. if (id->name != name)
  6217. poolDiscard(&dtd->pool);
  6218. else {
  6219. poolFinish(&dtd->pool);
  6220. if (! parser->m_ns)
  6221. ;
  6222. else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)
  6223. && name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)
  6224. && name[4] == XML_T(ASCII_s)
  6225. && (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
  6226. if (name[5] == XML_T('\0'))
  6227. id->prefix = &dtd->defaultPrefix;
  6228. else
  6229. id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,
  6230. sizeof(PREFIX));
  6231. id->xmlns = XML_TRUE;
  6232. } else {
  6233. int i;
  6234. for (i = 0; name[i]; i++) {
  6235. /* attributes without prefix are *not* in the default namespace */
  6236. if (name[i] == XML_T(ASCII_COLON)) {
  6237. int j;
  6238. for (j = 0; j < i; j++) {
  6239. if (! poolAppendChar(&dtd->pool, name[j]))
  6240. return NULL;
  6241. }
  6242. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6243. return NULL;
  6244. id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,
  6245. poolStart(&dtd->pool), sizeof(PREFIX));
  6246. if (! id->prefix)
  6247. return NULL;
  6248. if (id->prefix->name == poolStart(&dtd->pool))
  6249. poolFinish(&dtd->pool);
  6250. else
  6251. poolDiscard(&dtd->pool);
  6252. break;
  6253. }
  6254. }
  6255. }
  6256. }
  6257. return id;
  6258. }
  6259. #define CONTEXT_SEP XML_T(ASCII_FF)
  6260. static const XML_Char *
  6261. getContext(XML_Parser parser) {
  6262. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6263. HASH_TABLE_ITER iter;
  6264. XML_Bool needSep = XML_FALSE;
  6265. if (dtd->defaultPrefix.binding) {
  6266. int i;
  6267. int len;
  6268. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
  6269. return NULL;
  6270. len = dtd->defaultPrefix.binding->uriLen;
  6271. if (parser->m_namespaceSeparator)
  6272. len--;
  6273. for (i = 0; i < len; i++) {
  6274. if (! poolAppendChar(&parser->m_tempPool,
  6275. dtd->defaultPrefix.binding->uri[i])) {
  6276. /* Because of memory caching, I don't believe this line can be
  6277. * executed.
  6278. *
  6279. * This is part of a loop copying the default prefix binding
  6280. * URI into the parser's temporary string pool. Previously,
  6281. * that URI was copied into the same string pool, with a
  6282. * terminating NUL character, as part of setContext(). When
  6283. * the pool was cleared, that leaves a block definitely big
  6284. * enough to hold the URI on the free block list of the pool.
  6285. * The URI copy in getContext() therefore cannot run out of
  6286. * memory.
  6287. *
  6288. * If the pool is used between the setContext() and
  6289. * getContext() calls, the worst it can do is leave a bigger
  6290. * block on the front of the free list. Given that this is
  6291. * all somewhat inobvious and program logic can be changed, we
  6292. * don't delete the line but we do exclude it from the test
  6293. * coverage statistics.
  6294. */
  6295. return NULL; /* LCOV_EXCL_LINE */
  6296. }
  6297. }
  6298. needSep = XML_TRUE;
  6299. }
  6300. hashTableIterInit(&iter, &(dtd->prefixes));
  6301. for (;;) {
  6302. int i;
  6303. int len;
  6304. const XML_Char *s;
  6305. PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
  6306. if (! prefix)
  6307. break;
  6308. if (! prefix->binding) {
  6309. /* This test appears to be (justifiable) paranoia. There does
  6310. * not seem to be a way of injecting a prefix without a binding
  6311. * that doesn't get errored long before this function is called.
  6312. * The test should remain for safety's sake, so we instead
  6313. * exclude the following line from the coverage statistics.
  6314. */
  6315. continue; /* LCOV_EXCL_LINE */
  6316. }
  6317. if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
  6318. return NULL;
  6319. for (s = prefix->name; *s; s++)
  6320. if (! poolAppendChar(&parser->m_tempPool, *s))
  6321. return NULL;
  6322. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
  6323. return NULL;
  6324. len = prefix->binding->uriLen;
  6325. if (parser->m_namespaceSeparator)
  6326. len--;
  6327. for (i = 0; i < len; i++)
  6328. if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
  6329. return NULL;
  6330. needSep = XML_TRUE;
  6331. }
  6332. hashTableIterInit(&iter, &(dtd->generalEntities));
  6333. for (;;) {
  6334. const XML_Char *s;
  6335. ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
  6336. if (! e)
  6337. break;
  6338. if (! e->open)
  6339. continue;
  6340. if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
  6341. return NULL;
  6342. for (s = e->name; *s; s++)
  6343. if (! poolAppendChar(&parser->m_tempPool, *s))
  6344. return 0;
  6345. needSep = XML_TRUE;
  6346. }
  6347. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6348. return NULL;
  6349. return parser->m_tempPool.start;
  6350. }
  6351. static XML_Bool
  6352. setContext(XML_Parser parser, const XML_Char *context) {
  6353. if (context == NULL) {
  6354. return XML_FALSE;
  6355. }
  6356. { // WINSCP
  6357. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6358. const XML_Char *s = context;
  6359. while (*context != XML_T('\0')) {
  6360. if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
  6361. ENTITY *e;
  6362. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6363. return XML_FALSE;
  6364. e = (ENTITY *)lookup(parser, &dtd->generalEntities,
  6365. poolStart(&parser->m_tempPool), 0);
  6366. if (e)
  6367. e->open = XML_TRUE;
  6368. if (*s != XML_T('\0'))
  6369. s++;
  6370. context = s;
  6371. poolDiscard(&parser->m_tempPool);
  6372. } else if (*s == XML_T(ASCII_EQUALS)) {
  6373. PREFIX *prefix;
  6374. if (poolLength(&parser->m_tempPool) == 0)
  6375. prefix = &dtd->defaultPrefix;
  6376. else {
  6377. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6378. return XML_FALSE;
  6379. prefix
  6380. = (PREFIX *)lookup(parser, &dtd->prefixes,
  6381. poolStart(&parser->m_tempPool), sizeof(PREFIX));
  6382. if (! prefix)
  6383. return XML_FALSE;
  6384. if (prefix->name == poolStart(&parser->m_tempPool)) {
  6385. prefix->name = poolCopyString(&dtd->pool, prefix->name);
  6386. if (! prefix->name)
  6387. return XML_FALSE;
  6388. }
  6389. poolDiscard(&parser->m_tempPool);
  6390. }
  6391. for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\0');
  6392. context++)
  6393. if (! poolAppendChar(&parser->m_tempPool, *context))
  6394. return XML_FALSE;
  6395. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6396. return XML_FALSE;
  6397. if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
  6398. &parser->m_inheritedBindings)
  6399. != XML_ERROR_NONE)
  6400. return XML_FALSE;
  6401. poolDiscard(&parser->m_tempPool);
  6402. if (*context != XML_T('\0'))
  6403. ++context;
  6404. s = context;
  6405. } else {
  6406. if (! poolAppendChar(&parser->m_tempPool, *s))
  6407. return XML_FALSE;
  6408. s++;
  6409. }
  6410. }
  6411. return XML_TRUE;
  6412. } // WINSCP
  6413. }
  6414. static void FASTCALL
  6415. normalizePublicId(XML_Char *publicId) {
  6416. XML_Char *p = publicId;
  6417. XML_Char *s;
  6418. for (s = publicId; *s; s++) {
  6419. switch (*s) {
  6420. case 0x20:
  6421. case 0xD:
  6422. case 0xA:
  6423. if (p != publicId && p[-1] != 0x20)
  6424. *p++ = 0x20;
  6425. break;
  6426. default:
  6427. *p++ = *s;
  6428. }
  6429. }
  6430. if (p != publicId && p[-1] == 0x20)
  6431. --p;
  6432. *p = XML_T('\0');
  6433. }
  6434. static DTD *
  6435. dtdCreate(const XML_Memory_Handling_Suite *ms) {
  6436. DTD *p = ms->malloc_fcn(sizeof(DTD));
  6437. if (p == NULL)
  6438. return p;
  6439. poolInit(&(p->pool), ms);
  6440. poolInit(&(p->entityValuePool), ms);
  6441. hashTableInit(&(p->generalEntities), ms);
  6442. hashTableInit(&(p->elementTypes), ms);
  6443. hashTableInit(&(p->attributeIds), ms);
  6444. hashTableInit(&(p->prefixes), ms);
  6445. #ifdef XML_DTD
  6446. p->paramEntityRead = XML_FALSE;
  6447. hashTableInit(&(p->paramEntities), ms);
  6448. #endif /* XML_DTD */
  6449. p->defaultPrefix.name = NULL;
  6450. p->defaultPrefix.binding = NULL;
  6451. p->in_eldecl = XML_FALSE;
  6452. p->scaffIndex = NULL;
  6453. p->scaffold = NULL;
  6454. p->scaffLevel = 0;
  6455. p->scaffSize = 0;
  6456. p->scaffCount = 0;
  6457. p->contentStringLen = 0;
  6458. p->keepProcessing = XML_TRUE;
  6459. p->hasParamEntityRefs = XML_FALSE;
  6460. p->standalone = XML_FALSE;
  6461. return p;
  6462. }
  6463. static void
  6464. dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms) {
  6465. HASH_TABLE_ITER iter;
  6466. hashTableIterInit(&iter, &(p->elementTypes));
  6467. for (;;) {
  6468. ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  6469. if (! e)
  6470. break;
  6471. if (e->allocDefaultAtts != 0)
  6472. ms->free_fcn(e->defaultAtts);
  6473. }
  6474. hashTableClear(&(p->generalEntities));
  6475. #ifdef XML_DTD
  6476. p->paramEntityRead = XML_FALSE;
  6477. hashTableClear(&(p->paramEntities));
  6478. #endif /* XML_DTD */
  6479. hashTableClear(&(p->elementTypes));
  6480. hashTableClear(&(p->attributeIds));
  6481. hashTableClear(&(p->prefixes));
  6482. poolClear(&(p->pool));
  6483. poolClear(&(p->entityValuePool));
  6484. p->defaultPrefix.name = NULL;
  6485. p->defaultPrefix.binding = NULL;
  6486. p->in_eldecl = XML_FALSE;
  6487. ms->free_fcn(p->scaffIndex);
  6488. p->scaffIndex = NULL;
  6489. ms->free_fcn(p->scaffold);
  6490. p->scaffold = NULL;
  6491. p->scaffLevel = 0;
  6492. p->scaffSize = 0;
  6493. p->scaffCount = 0;
  6494. p->contentStringLen = 0;
  6495. p->keepProcessing = XML_TRUE;
  6496. p->hasParamEntityRefs = XML_FALSE;
  6497. p->standalone = XML_FALSE;
  6498. }
  6499. static void
  6500. dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms) {
  6501. HASH_TABLE_ITER iter;
  6502. hashTableIterInit(&iter, &(p->elementTypes));
  6503. for (;;) {
  6504. ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  6505. if (! e)
  6506. break;
  6507. if (e->allocDefaultAtts != 0)
  6508. ms->free_fcn(e->defaultAtts);
  6509. }
  6510. hashTableDestroy(&(p->generalEntities));
  6511. #ifdef XML_DTD
  6512. hashTableDestroy(&(p->paramEntities));
  6513. #endif /* XML_DTD */
  6514. hashTableDestroy(&(p->elementTypes));
  6515. hashTableDestroy(&(p->attributeIds));
  6516. hashTableDestroy(&(p->prefixes));
  6517. poolDestroy(&(p->pool));
  6518. poolDestroy(&(p->entityValuePool));
  6519. if (isDocEntity) {
  6520. ms->free_fcn(p->scaffIndex);
  6521. ms->free_fcn(p->scaffold);
  6522. }
  6523. ms->free_fcn(p);
  6524. }
  6525. /* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
  6526. The new DTD has already been initialized.
  6527. */
  6528. static int
  6529. dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
  6530. const XML_Memory_Handling_Suite *ms) {
  6531. HASH_TABLE_ITER iter;
  6532. /* Copy the prefix table. */
  6533. hashTableIterInit(&iter, &(oldDtd->prefixes));
  6534. for (;;) {
  6535. const XML_Char *name;
  6536. const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
  6537. if (! oldP)
  6538. break;
  6539. name = poolCopyString(&(newDtd->pool), oldP->name);
  6540. if (! name)
  6541. return 0;
  6542. if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
  6543. return 0;
  6544. }
  6545. hashTableIterInit(&iter, &(oldDtd->attributeIds));
  6546. /* Copy the attribute id table. */
  6547. for (;;) {
  6548. ATTRIBUTE_ID *newA;
  6549. const XML_Char *name;
  6550. const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
  6551. if (! oldA)
  6552. break;
  6553. /* Remember to allocate the scratch byte before the name. */
  6554. if (! poolAppendChar(&(newDtd->pool), XML_T('\0')))
  6555. return 0;
  6556. name = poolCopyString(&(newDtd->pool), oldA->name);
  6557. if (! name)
  6558. return 0;
  6559. ++name;
  6560. newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
  6561. sizeof(ATTRIBUTE_ID));
  6562. if (! newA)
  6563. return 0;
  6564. newA->maybeTokenized = oldA->maybeTokenized;
  6565. if (oldA->prefix) {
  6566. newA->xmlns = oldA->xmlns;
  6567. if (oldA->prefix == &oldDtd->defaultPrefix)
  6568. newA->prefix = &newDtd->defaultPrefix;
  6569. else
  6570. newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
  6571. oldA->prefix->name, 0);
  6572. }
  6573. }
  6574. /* Copy the element type table. */
  6575. hashTableIterInit(&iter, &(oldDtd->elementTypes));
  6576. for (;;) {
  6577. int i;
  6578. ELEMENT_TYPE *newE;
  6579. const XML_Char *name;
  6580. const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  6581. if (! oldE)
  6582. break;
  6583. name = poolCopyString(&(newDtd->pool), oldE->name);
  6584. if (! name)
  6585. return 0;
  6586. newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
  6587. sizeof(ELEMENT_TYPE));
  6588. if (! newE)
  6589. return 0;
  6590. if (oldE->nDefaultAtts) {
  6591. /* Detect and prevent integer overflow.
  6592. * The preprocessor guard addresses the "always false" warning
  6593. * from -Wtype-limits on platforms where
  6594. * sizeof(int) < sizeof(size_t), e.g. on x86_64. */
  6595. #if UINT_MAX >= SIZE_MAX
  6596. if ((size_t)oldE->nDefaultAtts
  6597. > ((size_t)(-1) / sizeof(DEFAULT_ATTRIBUTE))) {
  6598. return 0;
  6599. }
  6600. #endif
  6601. newE->defaultAtts
  6602. = ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
  6603. if (! newE->defaultAtts) {
  6604. return 0;
  6605. }
  6606. }
  6607. if (oldE->idAtt)
  6608. newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),
  6609. oldE->idAtt->name, 0);
  6610. newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
  6611. if (oldE->prefix)
  6612. newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
  6613. oldE->prefix->name, 0);
  6614. for (i = 0; i < newE->nDefaultAtts; i++) {
  6615. newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(
  6616. oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
  6617. newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
  6618. if (oldE->defaultAtts[i].value) {
  6619. newE->defaultAtts[i].value
  6620. = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
  6621. if (! newE->defaultAtts[i].value)
  6622. return 0;
  6623. } else
  6624. newE->defaultAtts[i].value = NULL;
  6625. }
  6626. }
  6627. /* Copy the entity tables. */
  6628. if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),
  6629. &(oldDtd->generalEntities)))
  6630. return 0;
  6631. #ifdef XML_DTD
  6632. if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),
  6633. &(oldDtd->paramEntities)))
  6634. return 0;
  6635. newDtd->paramEntityRead = oldDtd->paramEntityRead;
  6636. #endif /* XML_DTD */
  6637. newDtd->keepProcessing = oldDtd->keepProcessing;
  6638. newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
  6639. newDtd->standalone = oldDtd->standalone;
  6640. /* Don't want deep copying for scaffolding */
  6641. newDtd->in_eldecl = oldDtd->in_eldecl;
  6642. newDtd->scaffold = oldDtd->scaffold;
  6643. newDtd->contentStringLen = oldDtd->contentStringLen;
  6644. newDtd->scaffSize = oldDtd->scaffSize;
  6645. newDtd->scaffLevel = oldDtd->scaffLevel;
  6646. newDtd->scaffIndex = oldDtd->scaffIndex;
  6647. return 1;
  6648. } /* End dtdCopy */
  6649. static int
  6650. copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
  6651. STRING_POOL *newPool, const HASH_TABLE *oldTable) {
  6652. HASH_TABLE_ITER iter;
  6653. const XML_Char *cachedOldBase = NULL;
  6654. const XML_Char *cachedNewBase = NULL;
  6655. hashTableIterInit(&iter, oldTable);
  6656. for (;;) {
  6657. ENTITY *newE;
  6658. const XML_Char *name;
  6659. const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
  6660. if (! oldE)
  6661. break;
  6662. name = poolCopyString(newPool, oldE->name);
  6663. if (! name)
  6664. return 0;
  6665. newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
  6666. if (! newE)
  6667. return 0;
  6668. if (oldE->systemId) {
  6669. const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
  6670. if (! tem)
  6671. return 0;
  6672. newE->systemId = tem;
  6673. if (oldE->base) {
  6674. if (oldE->base == cachedOldBase)
  6675. newE->base = cachedNewBase;
  6676. else {
  6677. cachedOldBase = oldE->base;
  6678. tem = poolCopyString(newPool, cachedOldBase);
  6679. if (! tem)
  6680. return 0;
  6681. cachedNewBase = newE->base = tem;
  6682. }
  6683. }
  6684. if (oldE->publicId) {
  6685. tem = poolCopyString(newPool, oldE->publicId);
  6686. if (! tem)
  6687. return 0;
  6688. newE->publicId = tem;
  6689. }
  6690. } else {
  6691. const XML_Char *tem
  6692. = poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);
  6693. if (! tem)
  6694. return 0;
  6695. newE->textPtr = tem;
  6696. newE->textLen = oldE->textLen;
  6697. }
  6698. if (oldE->notation) {
  6699. const XML_Char *tem = poolCopyString(newPool, oldE->notation);
  6700. if (! tem)
  6701. return 0;
  6702. newE->notation = tem;
  6703. }
  6704. newE->is_param = oldE->is_param;
  6705. newE->is_internal = oldE->is_internal;
  6706. }
  6707. return 1;
  6708. }
  6709. #define INIT_POWER 6
  6710. static XML_Bool FASTCALL
  6711. keyeq(KEY s1, KEY s2) {
  6712. for (; *s1 == *s2; s1++, s2++)
  6713. if (*s1 == 0)
  6714. return XML_TRUE;
  6715. return XML_FALSE;
  6716. }
  6717. static size_t
  6718. keylen(KEY s) {
  6719. size_t len = 0;
  6720. for (; *s; s++, len++)
  6721. ;
  6722. return len;
  6723. }
  6724. static void
  6725. copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {
  6726. key->k[0] = 0;
  6727. key->k[1] = get_hash_secret_salt(parser);
  6728. }
  6729. static unsigned long FASTCALL
  6730. hash(XML_Parser parser, KEY s) {
  6731. struct siphash state;
  6732. struct sipkey key;
  6733. (void)sip24_valid;
  6734. copy_salt_to_sipkey(parser, &key);
  6735. sip24_init(&state, &key);
  6736. sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
  6737. return (unsigned long)sip24_final(&state);
  6738. }
  6739. static NAMED *
  6740. lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {
  6741. size_t i;
  6742. if (table->size == 0) {
  6743. size_t tsize;
  6744. if (! createSize)
  6745. return NULL;
  6746. table->power = INIT_POWER;
  6747. /* table->size is a power of 2 */
  6748. table->size = (size_t)1 << INIT_POWER;
  6749. tsize = table->size * sizeof(NAMED *);
  6750. table->v = table->mem->malloc_fcn(tsize);
  6751. if (! table->v) {
  6752. table->size = 0;
  6753. return NULL;
  6754. }
  6755. memset(table->v, 0, tsize);
  6756. i = hash(parser, name) & ((unsigned long)table->size - 1);
  6757. } else {
  6758. unsigned long h = hash(parser, name);
  6759. unsigned long mask = (unsigned long)table->size - 1;
  6760. unsigned char step = 0;
  6761. i = h & mask;
  6762. while (table->v[i]) {
  6763. if (keyeq(name, table->v[i]->name))
  6764. return table->v[i];
  6765. if (! step)
  6766. step = PROBE_STEP(h, mask, table->power);
  6767. i < step ? (i += table->size - step) : (i -= step);
  6768. }
  6769. if (! createSize)
  6770. return NULL;
  6771. /* check for overflow (table is half full) */
  6772. if (table->used >> (table->power - 1)) {
  6773. unsigned char newPower = table->power + 1;
  6774. /* Detect and prevent invalid shift */
  6775. if (newPower >= sizeof(unsigned long) * 8 /* bits per byte */) {
  6776. return NULL;
  6777. }
  6778. { // WINSCP
  6779. size_t newSize = (size_t)1 << newPower;
  6780. unsigned long newMask = (unsigned long)newSize - 1;
  6781. /* Detect and prevent integer overflow */
  6782. if (newSize > (size_t)(-1) / sizeof(NAMED *)) {
  6783. return NULL;
  6784. }
  6785. { // WINSCP
  6786. size_t tsize = newSize * sizeof(NAMED *);
  6787. NAMED **newV = table->mem->malloc_fcn(tsize);
  6788. if (! newV)
  6789. return NULL;
  6790. memset(newV, 0, tsize);
  6791. for (i = 0; i < table->size; i++)
  6792. if (table->v[i]) {
  6793. unsigned long newHash = hash(parser, table->v[i]->name);
  6794. size_t j = newHash & newMask;
  6795. step = 0;
  6796. while (newV[j]) {
  6797. if (! step)
  6798. step = PROBE_STEP(newHash, newMask, newPower);
  6799. j < step ? (j += newSize - step) : (j -= step);
  6800. }
  6801. newV[j] = table->v[i];
  6802. }
  6803. table->mem->free_fcn(table->v);
  6804. table->v = newV;
  6805. table->power = newPower;
  6806. table->size = newSize;
  6807. i = h & newMask;
  6808. step = 0;
  6809. while (table->v[i]) {
  6810. if (! step)
  6811. step = PROBE_STEP(h, newMask, newPower);
  6812. i < step ? (i += newSize - step) : (i -= step);
  6813. }
  6814. } // WINSCP
  6815. } // WINSCP
  6816. }
  6817. }
  6818. table->v[i] = table->mem->malloc_fcn(createSize);
  6819. if (! table->v[i])
  6820. return NULL;
  6821. memset(table->v[i], 0, createSize);
  6822. table->v[i]->name = name;
  6823. (table->used)++;
  6824. return table->v[i];
  6825. }
  6826. static void FASTCALL
  6827. hashTableClear(HASH_TABLE *table) {
  6828. size_t i;
  6829. for (i = 0; i < table->size; i++) {
  6830. table->mem->free_fcn(table->v[i]);
  6831. table->v[i] = NULL;
  6832. }
  6833. table->used = 0;
  6834. }
  6835. static void FASTCALL
  6836. hashTableDestroy(HASH_TABLE *table) {
  6837. size_t i;
  6838. for (i = 0; i < table->size; i++)
  6839. table->mem->free_fcn(table->v[i]);
  6840. table->mem->free_fcn(table->v);
  6841. }
  6842. static void FASTCALL
  6843. hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms) {
  6844. p->power = 0;
  6845. p->size = 0;
  6846. p->used = 0;
  6847. p->v = NULL;
  6848. p->mem = ms;
  6849. }
  6850. static void FASTCALL
  6851. hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {
  6852. iter->p = table->v;
  6853. iter->end = iter->p ? iter->p + table->size : NULL;
  6854. }
  6855. static NAMED *FASTCALL
  6856. hashTableIterNext(HASH_TABLE_ITER *iter) {
  6857. while (iter->p != iter->end) {
  6858. NAMED *tem = *(iter->p)++;
  6859. if (tem)
  6860. return tem;
  6861. }
  6862. return NULL;
  6863. }
  6864. static void FASTCALL
  6865. poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) {
  6866. pool->blocks = NULL;
  6867. pool->freeBlocks = NULL;
  6868. pool->start = NULL;
  6869. pool->ptr = NULL;
  6870. pool->end = NULL;
  6871. pool->mem = ms;
  6872. }
  6873. static void FASTCALL
  6874. poolClear(STRING_POOL *pool) {
  6875. if (! pool->freeBlocks)
  6876. pool->freeBlocks = pool->blocks;
  6877. else {
  6878. BLOCK *p = pool->blocks;
  6879. while (p) {
  6880. BLOCK *tem = p->next;
  6881. p->next = pool->freeBlocks;
  6882. pool->freeBlocks = p;
  6883. p = tem;
  6884. }
  6885. }
  6886. pool->blocks = NULL;
  6887. pool->start = NULL;
  6888. pool->ptr = NULL;
  6889. pool->end = NULL;
  6890. }
  6891. static void FASTCALL
  6892. poolDestroy(STRING_POOL *pool) {
  6893. BLOCK *p = pool->blocks;
  6894. while (p) {
  6895. BLOCK *tem = p->next;
  6896. pool->mem->free_fcn(p);
  6897. p = tem;
  6898. }
  6899. p = pool->freeBlocks;
  6900. while (p) {
  6901. BLOCK *tem = p->next;
  6902. pool->mem->free_fcn(p);
  6903. p = tem;
  6904. }
  6905. }
  6906. static XML_Char *
  6907. poolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
  6908. const char *end) {
  6909. if (! pool->ptr && ! poolGrow(pool))
  6910. return NULL;
  6911. for (;;) {
  6912. const enum XML_Convert_Result convert_res = XmlConvert(
  6913. enc, &ptr, end, (ICHAR **)&(pool->ptr), (const ICHAR *)pool->end);
  6914. if ((convert_res == XML_CONVERT_COMPLETED)
  6915. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  6916. break;
  6917. if (! poolGrow(pool))
  6918. return NULL;
  6919. }
  6920. return pool->start;
  6921. }
  6922. static const XML_Char *FASTCALL
  6923. poolCopyString(STRING_POOL *pool, const XML_Char *s) {
  6924. do {
  6925. if (! poolAppendChar(pool, *s))
  6926. return NULL;
  6927. } while (*s++);
  6928. s = pool->start;
  6929. poolFinish(pool);
  6930. return s;
  6931. }
  6932. static const XML_Char *
  6933. poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {
  6934. if (! pool->ptr && ! poolGrow(pool)) {
  6935. /* The following line is unreachable given the current usage of
  6936. * poolCopyStringN(). Currently it is called from exactly one
  6937. * place to copy the text of a simple general entity. By that
  6938. * point, the name of the entity is already stored in the pool, so
  6939. * pool->ptr cannot be NULL.
  6940. *
  6941. * If poolCopyStringN() is used elsewhere as it well might be,
  6942. * this line may well become executable again. Regardless, this
  6943. * sort of check shouldn't be removed lightly, so we just exclude
  6944. * it from the coverage statistics.
  6945. */
  6946. return NULL; /* LCOV_EXCL_LINE */
  6947. }
  6948. for (; n > 0; --n, s++) {
  6949. if (! poolAppendChar(pool, *s))
  6950. return NULL;
  6951. }
  6952. s = pool->start;
  6953. poolFinish(pool);
  6954. return s;
  6955. }
  6956. static const XML_Char *FASTCALL
  6957. poolAppendString(STRING_POOL *pool, const XML_Char *s) {
  6958. while (*s) {
  6959. if (! poolAppendChar(pool, *s))
  6960. return NULL;
  6961. s++;
  6962. }
  6963. return pool->start;
  6964. }
  6965. static XML_Char *
  6966. poolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
  6967. const char *end) {
  6968. if (! poolAppend(pool, enc, ptr, end))
  6969. return NULL;
  6970. if (pool->ptr == pool->end && ! poolGrow(pool))
  6971. return NULL;
  6972. *(pool->ptr)++ = 0;
  6973. return pool->start;
  6974. }
  6975. static size_t
  6976. poolBytesToAllocateFor(int blockSize) {
  6977. /* Unprotected math would be:
  6978. ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
  6979. **
  6980. ** Detect overflow, avoiding _signed_ overflow undefined behavior
  6981. ** For a + b * c we check b * c in isolation first, so that addition of a
  6982. ** on top has no chance of making us accept a small non-negative number
  6983. */
  6984. const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
  6985. if (blockSize <= 0)
  6986. return 0;
  6987. if (blockSize > (int)(INT_MAX / stretch))
  6988. return 0;
  6989. {
  6990. const int stretchedBlockSize = blockSize * (int)stretch;
  6991. const int bytesToAllocate
  6992. = (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
  6993. if (bytesToAllocate < 0)
  6994. return 0;
  6995. return (size_t)bytesToAllocate;
  6996. }
  6997. }
  6998. static XML_Bool FASTCALL
  6999. poolGrow(STRING_POOL *pool) {
  7000. if (pool->freeBlocks) {
  7001. if (pool->start == 0) {
  7002. pool->blocks = pool->freeBlocks;
  7003. pool->freeBlocks = pool->freeBlocks->next;
  7004. pool->blocks->next = NULL;
  7005. pool->start = pool->blocks->s;
  7006. pool->end = pool->start + pool->blocks->size;
  7007. pool->ptr = pool->start;
  7008. return XML_TRUE;
  7009. }
  7010. if (pool->end - pool->start < pool->freeBlocks->size) {
  7011. BLOCK *tem = pool->freeBlocks->next;
  7012. pool->freeBlocks->next = pool->blocks;
  7013. pool->blocks = pool->freeBlocks;
  7014. pool->freeBlocks = tem;
  7015. memcpy(pool->blocks->s, pool->start,
  7016. (pool->end - pool->start) * sizeof(XML_Char));
  7017. pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
  7018. pool->start = pool->blocks->s;
  7019. pool->end = pool->start + pool->blocks->size;
  7020. return XML_TRUE;
  7021. }
  7022. }
  7023. if (pool->blocks && pool->start == pool->blocks->s) {
  7024. BLOCK *temp;
  7025. int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);
  7026. size_t bytesToAllocate;
  7027. /* NOTE: Needs to be calculated prior to calling `realloc`
  7028. to avoid dangling pointers: */
  7029. const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
  7030. if (blockSize < 0) {
  7031. /* This condition traps a situation where either more than
  7032. * INT_MAX/2 bytes have already been allocated. This isn't
  7033. * readily testable, since it is unlikely that an average
  7034. * machine will have that much memory, so we exclude it from the
  7035. * coverage statistics.
  7036. */
  7037. return XML_FALSE; /* LCOV_EXCL_LINE */
  7038. }
  7039. bytesToAllocate = poolBytesToAllocateFor(blockSize);
  7040. if (bytesToAllocate == 0)
  7041. return XML_FALSE;
  7042. temp = (BLOCK *)pool->mem->realloc_fcn(pool->blocks,
  7043. (unsigned)bytesToAllocate);
  7044. if (temp == NULL)
  7045. return XML_FALSE;
  7046. pool->blocks = temp;
  7047. pool->blocks->size = blockSize;
  7048. pool->ptr = pool->blocks->s + offsetInsideBlock;
  7049. pool->start = pool->blocks->s;
  7050. pool->end = pool->start + blockSize;
  7051. } else {
  7052. BLOCK *tem;
  7053. int blockSize = (int)(pool->end - pool->start);
  7054. size_t bytesToAllocate;
  7055. if (blockSize < 0) {
  7056. /* This condition traps a situation where either more than
  7057. * INT_MAX bytes have already been allocated (which is prevented
  7058. * by various pieces of program logic, not least this one, never
  7059. * mind the unlikelihood of actually having that much memory) or
  7060. * the pool control fields have been corrupted (which could
  7061. * conceivably happen in an extremely buggy user handler
  7062. * function). Either way it isn't readily testable, so we
  7063. * exclude it from the coverage statistics.
  7064. */
  7065. return XML_FALSE; /* LCOV_EXCL_LINE */
  7066. }
  7067. if (blockSize < INIT_BLOCK_SIZE)
  7068. blockSize = INIT_BLOCK_SIZE;
  7069. else {
  7070. /* Detect overflow, avoiding _signed_ overflow undefined behavior */
  7071. if ((int)((unsigned)blockSize * 2U) < 0) {
  7072. return XML_FALSE;
  7073. }
  7074. blockSize *= 2;
  7075. }
  7076. bytesToAllocate = poolBytesToAllocateFor(blockSize);
  7077. if (bytesToAllocate == 0)
  7078. return XML_FALSE;
  7079. tem = pool->mem->malloc_fcn(bytesToAllocate);
  7080. if (! tem)
  7081. return XML_FALSE;
  7082. tem->size = blockSize;
  7083. tem->next = pool->blocks;
  7084. pool->blocks = tem;
  7085. if (pool->ptr != pool->start)
  7086. memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));
  7087. pool->ptr = tem->s + (pool->ptr - pool->start);
  7088. pool->start = tem->s;
  7089. pool->end = tem->s + blockSize;
  7090. }
  7091. return XML_TRUE;
  7092. }
  7093. static int FASTCALL
  7094. nextScaffoldPart(XML_Parser parser) {
  7095. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7096. CONTENT_SCAFFOLD *me;
  7097. int next;
  7098. if (! dtd->scaffIndex) {
  7099. /* Detect and prevent integer overflow.
  7100. * The preprocessor guard addresses the "always false" warning
  7101. * from -Wtype-limits on platforms where
  7102. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7103. #if UINT_MAX >= SIZE_MAX
  7104. if (parser->m_groupSize > ((size_t)(-1) / sizeof(int))) {
  7105. return -1;
  7106. }
  7107. #endif
  7108. dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
  7109. if (! dtd->scaffIndex)
  7110. return -1;
  7111. dtd->scaffIndex[0] = 0;
  7112. }
  7113. if (dtd->scaffCount >= dtd->scaffSize) {
  7114. CONTENT_SCAFFOLD *temp;
  7115. if (dtd->scaffold) {
  7116. /* Detect and prevent integer overflow */
  7117. if (dtd->scaffSize > UINT_MAX / 2u) {
  7118. return -1;
  7119. }
  7120. /* Detect and prevent integer overflow.
  7121. * The preprocessor guard addresses the "always false" warning
  7122. * from -Wtype-limits on platforms where
  7123. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7124. #if UINT_MAX >= SIZE_MAX
  7125. if (dtd->scaffSize > (size_t)(-1) / 2u / sizeof(CONTENT_SCAFFOLD)) {
  7126. return -1;
  7127. }
  7128. #endif
  7129. temp = (CONTENT_SCAFFOLD *)REALLOC(
  7130. parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
  7131. if (temp == NULL)
  7132. return -1;
  7133. dtd->scaffSize *= 2;
  7134. } else {
  7135. temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
  7136. * sizeof(CONTENT_SCAFFOLD));
  7137. if (temp == NULL)
  7138. return -1;
  7139. dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
  7140. }
  7141. dtd->scaffold = temp;
  7142. }
  7143. next = dtd->scaffCount++;
  7144. me = &dtd->scaffold[next];
  7145. if (dtd->scaffLevel) {
  7146. CONTENT_SCAFFOLD *parent
  7147. = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];
  7148. if (parent->lastchild) {
  7149. dtd->scaffold[parent->lastchild].nextsib = next;
  7150. }
  7151. if (! parent->childcnt)
  7152. parent->firstchild = next;
  7153. parent->lastchild = next;
  7154. parent->childcnt++;
  7155. }
  7156. me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
  7157. return next;
  7158. }
  7159. static XML_Content *
  7160. build_model(XML_Parser parser) {
  7161. /* Function build_model transforms the existing parser->m_dtd->scaffold
  7162. * array of CONTENT_SCAFFOLD tree nodes into a new array of
  7163. * XML_Content tree nodes followed by a gapless list of zero-terminated
  7164. * strings. */
  7165. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7166. XML_Content *ret;
  7167. XML_Char *str; /* the current string writing location */
  7168. /* Detect and prevent integer overflow.
  7169. * The preprocessor guard addresses the "always false" warning
  7170. * from -Wtype-limits on platforms where
  7171. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7172. #if UINT_MAX >= SIZE_MAX
  7173. if (dtd->scaffCount > (size_t)(-1) / sizeof(XML_Content)) {
  7174. return NULL;
  7175. }
  7176. if (dtd->contentStringLen > (size_t)(-1) / sizeof(XML_Char)) {
  7177. return NULL;
  7178. }
  7179. #endif
  7180. if (dtd->scaffCount * sizeof(XML_Content)
  7181. > (size_t)(-1) - dtd->contentStringLen * sizeof(XML_Char)) {
  7182. return NULL;
  7183. }
  7184. { // WINSCP
  7185. const size_t allocsize = (dtd->scaffCount * sizeof(XML_Content)
  7186. + (dtd->contentStringLen * sizeof(XML_Char)));
  7187. ret = (XML_Content *)MALLOC(parser, allocsize);
  7188. if (! ret)
  7189. return NULL;
  7190. /* What follows is an iterative implementation (of what was previously done
  7191. * recursively in a dedicated function called "build_node". The old recursive
  7192. * build_node could be forced into stack exhaustion from input as small as a
  7193. * few megabyte, and so that was a security issue. Hence, a function call
  7194. * stack is avoided now by resolving recursion.)
  7195. *
  7196. * The iterative approach works as follows:
  7197. *
  7198. * - We have two writing pointers, both walking up the result array; one does
  7199. * the work, the other creates "jobs" for its colleague to do, and leads
  7200. * the way:
  7201. *
  7202. * - The faster one, pointer jobDest, always leads and writes "what job
  7203. * to do" by the other, once they reach that place in the
  7204. * array: leader "jobDest" stores the source node array index (relative
  7205. * to array dtd->scaffold) in field "numchildren".
  7206. *
  7207. * - The slower one, pointer dest, looks at the value stored in the
  7208. * "numchildren" field (which actually holds a source node array index
  7209. * at that time) and puts the real data from dtd->scaffold in.
  7210. *
  7211. * - Before the loop starts, jobDest writes source array index 0
  7212. * (where the root node is located) so that dest will have something to do
  7213. * when it starts operation.
  7214. *
  7215. * - Whenever nodes with children are encountered, jobDest appends
  7216. * them as new jobs, in order. As a result, tree node siblings are
  7217. * adjacent in the resulting array, for example:
  7218. *
  7219. * [0] root, has two children
  7220. * [1] first child of 0, has three children
  7221. * [3] first child of 1, does not have children
  7222. * [4] second child of 1, does not have children
  7223. * [5] third child of 1, does not have children
  7224. * [2] second child of 0, does not have children
  7225. *
  7226. * Or (the same data) presented in flat array view:
  7227. *
  7228. * [0] root, has two children
  7229. *
  7230. * [1] first child of 0, has three children
  7231. * [2] second child of 0, does not have children
  7232. *
  7233. * [3] first child of 1, does not have children
  7234. * [4] second child of 1, does not have children
  7235. * [5] third child of 1, does not have children
  7236. *
  7237. * - The algorithm repeats until all target array indices have been processed.
  7238. */
  7239. { // WINSCP
  7240. XML_Content *dest = ret; /* tree node writing location, moves upwards */
  7241. XML_Content *const destLimit = &ret[dtd->scaffCount];
  7242. XML_Content *jobDest = ret; /* next free writing location in target array */
  7243. str = (XML_Char *)&ret[dtd->scaffCount];
  7244. /* Add the starting job, the root node (index 0) of the source tree */
  7245. (jobDest++)->numchildren = 0;
  7246. for (; dest < destLimit; dest++) {
  7247. /* Retrieve source tree array index from job storage */
  7248. const int src_node = (int)dest->numchildren;
  7249. /* Convert item */
  7250. dest->type = dtd->scaffold[src_node].type;
  7251. dest->quant = dtd->scaffold[src_node].quant;
  7252. if (dest->type == XML_CTYPE_NAME) {
  7253. const XML_Char *src;
  7254. dest->name = str;
  7255. src = dtd->scaffold[src_node].name;
  7256. for (;;) {
  7257. *str++ = *src;
  7258. if (! *src)
  7259. break;
  7260. src++;
  7261. }
  7262. dest->numchildren = 0;
  7263. dest->children = NULL;
  7264. } else {
  7265. unsigned int i;
  7266. int cn;
  7267. dest->name = NULL;
  7268. dest->numchildren = dtd->scaffold[src_node].childcnt;
  7269. dest->children = jobDest;
  7270. /* Append scaffold indices of children to array */
  7271. for (i = 0, cn = dtd->scaffold[src_node].firstchild;
  7272. i < dest->numchildren; i++, cn = dtd->scaffold[cn].nextsib)
  7273. (jobDest++)->numchildren = (unsigned int)cn;
  7274. }
  7275. }
  7276. return ret;
  7277. } // WINSCP
  7278. } // WINSCP
  7279. }
  7280. static ELEMENT_TYPE *
  7281. getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,
  7282. const char *end) {
  7283. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7284. const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
  7285. ELEMENT_TYPE *ret;
  7286. if (! name)
  7287. return NULL;
  7288. ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
  7289. sizeof(ELEMENT_TYPE));
  7290. if (! ret)
  7291. return NULL;
  7292. if (ret->name != name)
  7293. poolDiscard(&dtd->pool);
  7294. else {
  7295. poolFinish(&dtd->pool);
  7296. if (! setElementTypePrefix(parser, ret))
  7297. return NULL;
  7298. }
  7299. return ret;
  7300. }
  7301. static XML_Char *
  7302. copyString(const XML_Char *s, const XML_Memory_Handling_Suite *memsuite) {
  7303. size_t charsRequired = 0;
  7304. XML_Char *result;
  7305. /* First determine how long the string is */
  7306. while (s[charsRequired] != 0) {
  7307. charsRequired++;
  7308. }
  7309. /* Include the terminator */
  7310. charsRequired++;
  7311. /* Now allocate space for the copy */
  7312. result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
  7313. if (result == NULL)
  7314. return NULL;
  7315. /* Copy the original into place */
  7316. memcpy(result, s, charsRequired * sizeof(XML_Char));
  7317. return result;
  7318. }
  7319. #if XML_GE == 1
  7320. static float
  7321. accountingGetCurrentAmplification(XML_Parser rootParser) {
  7322. // 1.........1.........12 => 22
  7323. const size_t lenOfShortestInclude = sizeof("<!ENTITY a SYSTEM 'b'>") - 1;
  7324. const XmlBigCount countBytesOutput
  7325. = rootParser->m_accounting.countBytesDirect
  7326. + rootParser->m_accounting.countBytesIndirect;
  7327. const float amplificationFactor
  7328. = rootParser->m_accounting.countBytesDirect
  7329. ? (countBytesOutput
  7330. / (float)(rootParser->m_accounting.countBytesDirect))
  7331. : ((lenOfShortestInclude
  7332. + rootParser->m_accounting.countBytesIndirect)
  7333. / (float)lenOfShortestInclude);
  7334. assert(! rootParser->m_parentParser);
  7335. return amplificationFactor;
  7336. }
  7337. static void
  7338. accountingReportStats(XML_Parser originParser, const char *epilog) {
  7339. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  7340. assert(! rootParser->m_parentParser);
  7341. if (rootParser->m_accounting.debugLevel == 0u) {
  7342. return;
  7343. }
  7344. { // WINSCP
  7345. const float amplificationFactor
  7346. = accountingGetCurrentAmplification(rootParser);
  7347. fprintf(stderr,
  7348. "expat: Accounting(%p): Direct " EXPAT_FMT_ULL(
  7349. "10") ", indirect " EXPAT_FMT_ULL("10") ", amplification %8.2f%s",
  7350. (void *)rootParser, rootParser->m_accounting.countBytesDirect,
  7351. rootParser->m_accounting.countBytesIndirect,
  7352. (double)amplificationFactor, epilog);
  7353. } // WINSCP
  7354. }
  7355. static void
  7356. accountingOnAbort(XML_Parser originParser) {
  7357. accountingReportStats(originParser, " ABORTING\n");
  7358. }
  7359. static void
  7360. accountingReportDiff(XML_Parser rootParser,
  7361. unsigned int levelsAwayFromRootParser, const char *before,
  7362. const char *after, ptrdiff_t bytesMore, int source_line,
  7363. enum XML_Account account) {
  7364. assert(! rootParser->m_parentParser);
  7365. fprintf(stderr,
  7366. " (+" EXPAT_FMT_PTRDIFF_T("6") " bytes %s|%d, xmlparse.c:%d) %*s\"",
  7367. bytesMore, (account == XML_ACCOUNT_DIRECT) ? "DIR" : "EXP",
  7368. levelsAwayFromRootParser, source_line, 10, "");
  7369. { // WINSCP
  7370. const char ellipis[] = "[..]";
  7371. const size_t ellipsisLength = sizeof(ellipis) /* because compile-time */ - 1;
  7372. const unsigned int contextLength = 10;
  7373. /* Note: Performance is of no concern here */
  7374. const char *walker = before;
  7375. if ((rootParser->m_accounting.debugLevel >= 3u)
  7376. || (after - before)
  7377. <= (ptrdiff_t)(contextLength + ellipsisLength + contextLength)) {
  7378. for (; walker < after; walker++) {
  7379. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7380. }
  7381. } else {
  7382. for (; walker < before + contextLength; walker++) {
  7383. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7384. }
  7385. fprintf(stderr, ellipis);
  7386. walker = after - contextLength;
  7387. for (; walker < after; walker++) {
  7388. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7389. }
  7390. }
  7391. fprintf(stderr, "\"\n");
  7392. } // WINSCP
  7393. }
  7394. static XML_Bool
  7395. accountingDiffTolerated(XML_Parser originParser, int tok, const char *before,
  7396. const char *after, int source_line,
  7397. enum XML_Account account) {
  7398. /* Note: We need to check the token type *first* to be sure that
  7399. * we can even access variable <after>, safely.
  7400. * E.g. for XML_TOK_NONE <after> may hold an invalid pointer. */
  7401. switch (tok) {
  7402. case XML_TOK_INVALID:
  7403. case XML_TOK_PARTIAL:
  7404. case XML_TOK_PARTIAL_CHAR:
  7405. case XML_TOK_NONE:
  7406. return XML_TRUE;
  7407. }
  7408. if (account == XML_ACCOUNT_NONE)
  7409. return XML_TRUE; /* because these bytes have been accounted for, already */
  7410. { // WINSCP
  7411. unsigned int levelsAwayFromRootParser;
  7412. const XML_Parser rootParser
  7413. = getRootParserOf(originParser, &levelsAwayFromRootParser);
  7414. assert(! rootParser->m_parentParser);
  7415. { // WINSCP
  7416. const int isDirect
  7417. = (account == XML_ACCOUNT_DIRECT) && (originParser == rootParser);
  7418. const ptrdiff_t bytesMore = after - before;
  7419. XmlBigCount *const additionTarget
  7420. = isDirect ? &rootParser->m_accounting.countBytesDirect
  7421. : &rootParser->m_accounting.countBytesIndirect;
  7422. /* Detect and avoid integer overflow */
  7423. if (*additionTarget > (XmlBigCount)(-1) - (XmlBigCount)bytesMore)
  7424. return XML_FALSE;
  7425. *additionTarget += bytesMore;
  7426. { // WINSCP
  7427. const XmlBigCount countBytesOutput
  7428. = rootParser->m_accounting.countBytesDirect
  7429. + rootParser->m_accounting.countBytesIndirect;
  7430. const float amplificationFactor
  7431. = accountingGetCurrentAmplification(rootParser);
  7432. const XML_Bool tolerated
  7433. = (countBytesOutput < rootParser->m_accounting.activationThresholdBytes)
  7434. || (amplificationFactor
  7435. <= rootParser->m_accounting.maximumAmplificationFactor);
  7436. if (rootParser->m_accounting.debugLevel >= 2u) {
  7437. accountingReportStats(rootParser, "");
  7438. accountingReportDiff(rootParser, levelsAwayFromRootParser, before, after,
  7439. bytesMore, source_line, account);
  7440. }
  7441. return tolerated;
  7442. } // WINSCP
  7443. } // WINSCP
  7444. } // WINSCP
  7445. }
  7446. unsigned long long
  7447. testingAccountingGetCountBytesDirect(XML_Parser parser) {
  7448. if (! parser)
  7449. return 0;
  7450. return parser->m_accounting.countBytesDirect;
  7451. }
  7452. unsigned long long
  7453. testingAccountingGetCountBytesIndirect(XML_Parser parser) {
  7454. if (! parser)
  7455. return 0;
  7456. return parser->m_accounting.countBytesIndirect;
  7457. }
  7458. static void
  7459. entityTrackingReportStats(XML_Parser rootParser, ENTITY *entity,
  7460. const char *action, int sourceLine) {
  7461. assert(! rootParser->m_parentParser);
  7462. if (rootParser->m_entity_stats.debugLevel == 0u)
  7463. return;
  7464. { // WINSCP
  7465. # if defined(XML_UNICODE)
  7466. const char *const entityName = "[..]";
  7467. # else
  7468. const char *const entityName = entity->name;
  7469. # endif
  7470. fprintf(
  7471. stderr,
  7472. "expat: Entities(%p): Count %9d, depth %2d/%2d %*s%s%s; %s length %d (xmlparse.c:%d)\n",
  7473. (void *)rootParser, rootParser->m_entity_stats.countEverOpened,
  7474. rootParser->m_entity_stats.currentDepth,
  7475. rootParser->m_entity_stats.maximumDepthSeen,
  7476. (rootParser->m_entity_stats.currentDepth - 1) * 2, "",
  7477. entity->is_param ? "%" : "&", entityName, action, entity->textLen,
  7478. sourceLine);
  7479. } // WINSCP
  7480. }
  7481. static void
  7482. entityTrackingOnOpen(XML_Parser originParser, ENTITY *entity, int sourceLine) {
  7483. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  7484. assert(! rootParser->m_parentParser);
  7485. rootParser->m_entity_stats.countEverOpened++;
  7486. rootParser->m_entity_stats.currentDepth++;
  7487. if (rootParser->m_entity_stats.currentDepth
  7488. > rootParser->m_entity_stats.maximumDepthSeen) {
  7489. rootParser->m_entity_stats.maximumDepthSeen++;
  7490. }
  7491. entityTrackingReportStats(rootParser, entity, "OPEN ", sourceLine);
  7492. }
  7493. static void
  7494. entityTrackingOnClose(XML_Parser originParser, ENTITY *entity, int sourceLine) {
  7495. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  7496. assert(! rootParser->m_parentParser);
  7497. entityTrackingReportStats(rootParser, entity, "CLOSE", sourceLine);
  7498. rootParser->m_entity_stats.currentDepth--;
  7499. }
  7500. static XML_Parser
  7501. getRootParserOf(XML_Parser parser, unsigned int *outLevelDiff) {
  7502. XML_Parser rootParser = parser;
  7503. unsigned int stepsTakenUpwards = 0;
  7504. while (rootParser->m_parentParser) {
  7505. rootParser = rootParser->m_parentParser;
  7506. stepsTakenUpwards++;
  7507. }
  7508. assert(! rootParser->m_parentParser);
  7509. if (outLevelDiff != NULL) {
  7510. *outLevelDiff = stepsTakenUpwards;
  7511. }
  7512. return rootParser;
  7513. }
  7514. const char *
  7515. unsignedCharToPrintable(unsigned char c) {
  7516. switch (c) {
  7517. case 0:
  7518. return "\\0";
  7519. case 1:
  7520. return "\\x1";
  7521. case 2:
  7522. return "\\x2";
  7523. case 3:
  7524. return "\\x3";
  7525. case 4:
  7526. return "\\x4";
  7527. case 5:
  7528. return "\\x5";
  7529. case 6:
  7530. return "\\x6";
  7531. case 7:
  7532. return "\\x7";
  7533. case 8:
  7534. return "\\x8";
  7535. case 9:
  7536. return "\\t";
  7537. case 10:
  7538. return "\\n";
  7539. case 11:
  7540. return "\\xB";
  7541. case 12:
  7542. return "\\xC";
  7543. case 13:
  7544. return "\\r";
  7545. case 14:
  7546. return "\\xE";
  7547. case 15:
  7548. return "\\xF";
  7549. case 16:
  7550. return "\\x10";
  7551. case 17:
  7552. return "\\x11";
  7553. case 18:
  7554. return "\\x12";
  7555. case 19:
  7556. return "\\x13";
  7557. case 20:
  7558. return "\\x14";
  7559. case 21:
  7560. return "\\x15";
  7561. case 22:
  7562. return "\\x16";
  7563. case 23:
  7564. return "\\x17";
  7565. case 24:
  7566. return "\\x18";
  7567. case 25:
  7568. return "\\x19";
  7569. case 26:
  7570. return "\\x1A";
  7571. case 27:
  7572. return "\\x1B";
  7573. case 28:
  7574. return "\\x1C";
  7575. case 29:
  7576. return "\\x1D";
  7577. case 30:
  7578. return "\\x1E";
  7579. case 31:
  7580. return "\\x1F";
  7581. case 32:
  7582. return " ";
  7583. case 33:
  7584. return "!";
  7585. case 34:
  7586. return "\\\"";
  7587. case 35:
  7588. return "#";
  7589. case 36:
  7590. return "$";
  7591. case 37:
  7592. return "%";
  7593. case 38:
  7594. return "&";
  7595. case 39:
  7596. return "'";
  7597. case 40:
  7598. return "(";
  7599. case 41:
  7600. return ")";
  7601. case 42:
  7602. return "*";
  7603. case 43:
  7604. return "+";
  7605. case 44:
  7606. return ",";
  7607. case 45:
  7608. return "-";
  7609. case 46:
  7610. return ".";
  7611. case 47:
  7612. return "/";
  7613. case 48:
  7614. return "0";
  7615. case 49:
  7616. return "1";
  7617. case 50:
  7618. return "2";
  7619. case 51:
  7620. return "3";
  7621. case 52:
  7622. return "4";
  7623. case 53:
  7624. return "5";
  7625. case 54:
  7626. return "6";
  7627. case 55:
  7628. return "7";
  7629. case 56:
  7630. return "8";
  7631. case 57:
  7632. return "9";
  7633. case 58:
  7634. return ":";
  7635. case 59:
  7636. return ";";
  7637. case 60:
  7638. return "<";
  7639. case 61:
  7640. return "=";
  7641. case 62:
  7642. return ">";
  7643. case 63:
  7644. return "?";
  7645. case 64:
  7646. return "@";
  7647. case 65:
  7648. return "A";
  7649. case 66:
  7650. return "B";
  7651. case 67:
  7652. return "C";
  7653. case 68:
  7654. return "D";
  7655. case 69:
  7656. return "E";
  7657. case 70:
  7658. return "F";
  7659. case 71:
  7660. return "G";
  7661. case 72:
  7662. return "H";
  7663. case 73:
  7664. return "I";
  7665. case 74:
  7666. return "J";
  7667. case 75:
  7668. return "K";
  7669. case 76:
  7670. return "L";
  7671. case 77:
  7672. return "M";
  7673. case 78:
  7674. return "N";
  7675. case 79:
  7676. return "O";
  7677. case 80:
  7678. return "P";
  7679. case 81:
  7680. return "Q";
  7681. case 82:
  7682. return "R";
  7683. case 83:
  7684. return "S";
  7685. case 84:
  7686. return "T";
  7687. case 85:
  7688. return "U";
  7689. case 86:
  7690. return "V";
  7691. case 87:
  7692. return "W";
  7693. case 88:
  7694. return "X";
  7695. case 89:
  7696. return "Y";
  7697. case 90:
  7698. return "Z";
  7699. case 91:
  7700. return "[";
  7701. case 92:
  7702. return "\\\\";
  7703. case 93:
  7704. return "]";
  7705. case 94:
  7706. return "^";
  7707. case 95:
  7708. return "_";
  7709. case 96:
  7710. return "`";
  7711. case 97:
  7712. return "a";
  7713. case 98:
  7714. return "b";
  7715. case 99:
  7716. return "c";
  7717. case 100:
  7718. return "d";
  7719. case 101:
  7720. return "e";
  7721. case 102:
  7722. return "f";
  7723. case 103:
  7724. return "g";
  7725. case 104:
  7726. return "h";
  7727. case 105:
  7728. return "i";
  7729. case 106:
  7730. return "j";
  7731. case 107:
  7732. return "k";
  7733. case 108:
  7734. return "l";
  7735. case 109:
  7736. return "m";
  7737. case 110:
  7738. return "n";
  7739. case 111:
  7740. return "o";
  7741. case 112:
  7742. return "p";
  7743. case 113:
  7744. return "q";
  7745. case 114:
  7746. return "r";
  7747. case 115:
  7748. return "s";
  7749. case 116:
  7750. return "t";
  7751. case 117:
  7752. return "u";
  7753. case 118:
  7754. return "v";
  7755. case 119:
  7756. return "w";
  7757. case 120:
  7758. return "x";
  7759. case 121:
  7760. return "y";
  7761. case 122:
  7762. return "z";
  7763. case 123:
  7764. return "{";
  7765. case 124:
  7766. return "|";
  7767. case 125:
  7768. return "}";
  7769. case 126:
  7770. return "~";
  7771. case 127:
  7772. return "\\x7F";
  7773. case 128:
  7774. return "\\x80";
  7775. case 129:
  7776. return "\\x81";
  7777. case 130:
  7778. return "\\x82";
  7779. case 131:
  7780. return "\\x83";
  7781. case 132:
  7782. return "\\x84";
  7783. case 133:
  7784. return "\\x85";
  7785. case 134:
  7786. return "\\x86";
  7787. case 135:
  7788. return "\\x87";
  7789. case 136:
  7790. return "\\x88";
  7791. case 137:
  7792. return "\\x89";
  7793. case 138:
  7794. return "\\x8A";
  7795. case 139:
  7796. return "\\x8B";
  7797. case 140:
  7798. return "\\x8C";
  7799. case 141:
  7800. return "\\x8D";
  7801. case 142:
  7802. return "\\x8E";
  7803. case 143:
  7804. return "\\x8F";
  7805. case 144:
  7806. return "\\x90";
  7807. case 145:
  7808. return "\\x91";
  7809. case 146:
  7810. return "\\x92";
  7811. case 147:
  7812. return "\\x93";
  7813. case 148:
  7814. return "\\x94";
  7815. case 149:
  7816. return "\\x95";
  7817. case 150:
  7818. return "\\x96";
  7819. case 151:
  7820. return "\\x97";
  7821. case 152:
  7822. return "\\x98";
  7823. case 153:
  7824. return "\\x99";
  7825. case 154:
  7826. return "\\x9A";
  7827. case 155:
  7828. return "\\x9B";
  7829. case 156:
  7830. return "\\x9C";
  7831. case 157:
  7832. return "\\x9D";
  7833. case 158:
  7834. return "\\x9E";
  7835. case 159:
  7836. return "\\x9F";
  7837. case 160:
  7838. return "\\xA0";
  7839. case 161:
  7840. return "\\xA1";
  7841. case 162:
  7842. return "\\xA2";
  7843. case 163:
  7844. return "\\xA3";
  7845. case 164:
  7846. return "\\xA4";
  7847. case 165:
  7848. return "\\xA5";
  7849. case 166:
  7850. return "\\xA6";
  7851. case 167:
  7852. return "\\xA7";
  7853. case 168:
  7854. return "\\xA8";
  7855. case 169:
  7856. return "\\xA9";
  7857. case 170:
  7858. return "\\xAA";
  7859. case 171:
  7860. return "\\xAB";
  7861. case 172:
  7862. return "\\xAC";
  7863. case 173:
  7864. return "\\xAD";
  7865. case 174:
  7866. return "\\xAE";
  7867. case 175:
  7868. return "\\xAF";
  7869. case 176:
  7870. return "\\xB0";
  7871. case 177:
  7872. return "\\xB1";
  7873. case 178:
  7874. return "\\xB2";
  7875. case 179:
  7876. return "\\xB3";
  7877. case 180:
  7878. return "\\xB4";
  7879. case 181:
  7880. return "\\xB5";
  7881. case 182:
  7882. return "\\xB6";
  7883. case 183:
  7884. return "\\xB7";
  7885. case 184:
  7886. return "\\xB8";
  7887. case 185:
  7888. return "\\xB9";
  7889. case 186:
  7890. return "\\xBA";
  7891. case 187:
  7892. return "\\xBB";
  7893. case 188:
  7894. return "\\xBC";
  7895. case 189:
  7896. return "\\xBD";
  7897. case 190:
  7898. return "\\xBE";
  7899. case 191:
  7900. return "\\xBF";
  7901. case 192:
  7902. return "\\xC0";
  7903. case 193:
  7904. return "\\xC1";
  7905. case 194:
  7906. return "\\xC2";
  7907. case 195:
  7908. return "\\xC3";
  7909. case 196:
  7910. return "\\xC4";
  7911. case 197:
  7912. return "\\xC5";
  7913. case 198:
  7914. return "\\xC6";
  7915. case 199:
  7916. return "\\xC7";
  7917. case 200:
  7918. return "\\xC8";
  7919. case 201:
  7920. return "\\xC9";
  7921. case 202:
  7922. return "\\xCA";
  7923. case 203:
  7924. return "\\xCB";
  7925. case 204:
  7926. return "\\xCC";
  7927. case 205:
  7928. return "\\xCD";
  7929. case 206:
  7930. return "\\xCE";
  7931. case 207:
  7932. return "\\xCF";
  7933. case 208:
  7934. return "\\xD0";
  7935. case 209:
  7936. return "\\xD1";
  7937. case 210:
  7938. return "\\xD2";
  7939. case 211:
  7940. return "\\xD3";
  7941. case 212:
  7942. return "\\xD4";
  7943. case 213:
  7944. return "\\xD5";
  7945. case 214:
  7946. return "\\xD6";
  7947. case 215:
  7948. return "\\xD7";
  7949. case 216:
  7950. return "\\xD8";
  7951. case 217:
  7952. return "\\xD9";
  7953. case 218:
  7954. return "\\xDA";
  7955. case 219:
  7956. return "\\xDB";
  7957. case 220:
  7958. return "\\xDC";
  7959. case 221:
  7960. return "\\xDD";
  7961. case 222:
  7962. return "\\xDE";
  7963. case 223:
  7964. return "\\xDF";
  7965. case 224:
  7966. return "\\xE0";
  7967. case 225:
  7968. return "\\xE1";
  7969. case 226:
  7970. return "\\xE2";
  7971. case 227:
  7972. return "\\xE3";
  7973. case 228:
  7974. return "\\xE4";
  7975. case 229:
  7976. return "\\xE5";
  7977. case 230:
  7978. return "\\xE6";
  7979. case 231:
  7980. return "\\xE7";
  7981. case 232:
  7982. return "\\xE8";
  7983. case 233:
  7984. return "\\xE9";
  7985. case 234:
  7986. return "\\xEA";
  7987. case 235:
  7988. return "\\xEB";
  7989. case 236:
  7990. return "\\xEC";
  7991. case 237:
  7992. return "\\xED";
  7993. case 238:
  7994. return "\\xEE";
  7995. case 239:
  7996. return "\\xEF";
  7997. case 240:
  7998. return "\\xF0";
  7999. case 241:
  8000. return "\\xF1";
  8001. case 242:
  8002. return "\\xF2";
  8003. case 243:
  8004. return "\\xF3";
  8005. case 244:
  8006. return "\\xF4";
  8007. case 245:
  8008. return "\\xF5";
  8009. case 246:
  8010. return "\\xF6";
  8011. case 247:
  8012. return "\\xF7";
  8013. case 248:
  8014. return "\\xF8";
  8015. case 249:
  8016. return "\\xF9";
  8017. case 250:
  8018. return "\\xFA";
  8019. case 251:
  8020. return "\\xFB";
  8021. case 252:
  8022. return "\\xFC";
  8023. case 253:
  8024. return "\\xFD";
  8025. case 254:
  8026. return "\\xFE";
  8027. case 255:
  8028. return "\\xFF";
  8029. default:
  8030. assert(0); /* never gets here */
  8031. return "dead code";
  8032. }
  8033. // WINSCP assert(0); /* never gets here */
  8034. }
  8035. #endif /* XML_GE == 1 */
  8036. static unsigned long
  8037. getDebugLevel(const char *variableName, unsigned long defaultDebugLevel) {
  8038. const char *const valueOrNull = getenv(variableName);
  8039. if (valueOrNull == NULL) {
  8040. return defaultDebugLevel;
  8041. }
  8042. { // WINSCP
  8043. const char *const value = valueOrNull;
  8044. errno = 0;
  8045. { // WINSCP
  8046. char *afterValue = NULL;
  8047. unsigned long debugLevel = strtoul(value, &afterValue, 10);
  8048. if ((errno != 0) || (afterValue == value) || (afterValue[0] != '\0')) {
  8049. errno = 0;
  8050. return defaultDebugLevel;
  8051. }
  8052. return debugLevel;
  8053. } // WINSCP
  8054. } // WINSCP
  8055. }