xmlparse.c 303 KB

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