xmlparse.c 275 KB

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