test.cc 1018 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2318. auto host = "unresolvableaddress.local";
  2319. auto path = std::string{"/"};
  2320. #ifdef CPPHTTPLIB_SSL_ENABLED
  2321. auto port = 443;
  2322. SSLClient cli(host, port);
  2323. #else
  2324. auto port = 80;
  2325. Client cli(host, port);
  2326. #endif
  2327. cli.set_connection_timeout(1);
  2328. {
  2329. auto res = cli.Get(path);
  2330. ASSERT_FALSE(res);
  2331. }
  2332. std::this_thread::sleep_for(std::chrono::seconds(8));
  2333. }
  2334. #if defined(__linux__) && defined(__GLIBC__) && \
  2335. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2336. // Forward declaration: in split builds split.py strips `inline` and moves the
  2337. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2338. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2339. // against the symbol in both header-only and split builds.
  2340. namespace httplib {
  2341. namespace detail {
  2342. int getaddrinfo_with_timeout(const char *node, const char *service,
  2343. const struct addrinfo *hints,
  2344. struct addrinfo **res, time_t timeout_sec);
  2345. } // namespace detail
  2346. } // namespace httplib
  2347. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2348. //
  2349. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2350. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2351. // gai_suspend() call hits the connection timeout the function calls
  2352. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2353. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2354. // still alive and still references the now-destroyed stack frame.
  2355. //
  2356. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2357. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2358. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2359. // and runs them in a container.
  2360. namespace {
  2361. bool should_run_issue_2431_tests() {
  2362. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2363. return v && *v && std::string(v) != "0";
  2364. }
  2365. std::string unique_unresolvable_host(int n) {
  2366. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2367. // glibc still asks the configured nameserver — which is exactly the path
  2368. // we want to exercise. A unique label per call avoids the resolver cache.
  2369. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2370. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2371. std::to_string(n) + ".invalid";
  2372. }
  2373. } // namespace
  2374. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2375. if (!should_run_issue_2431_tests()) {
  2376. GTEST_SKIP()
  2377. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2378. }
  2379. for (int i = 0; i < 8; ++i) {
  2380. struct addrinfo hints;
  2381. memset(&hints, 0, sizeof(hints));
  2382. hints.ai_family = AF_UNSPEC;
  2383. hints.ai_socktype = SOCK_STREAM;
  2384. auto host = unique_unresolvable_host(i);
  2385. struct addrinfo *result = nullptr;
  2386. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2387. &result, /*timeout_sec=*/1);
  2388. if (rc == 0 && result) { freeaddrinfo(result); }
  2389. }
  2390. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2391. // stack region they still believe holds their gaicb.
  2392. std::this_thread::sleep_for(std::chrono::seconds(3));
  2393. }
  2394. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2395. if (!should_run_issue_2431_tests()) {
  2396. GTEST_SKIP()
  2397. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2398. }
  2399. std::atomic<bool> stop{false};
  2400. std::vector<std::thread> threads;
  2401. for (int t = 0; t < 8; ++t) {
  2402. threads.emplace_back([t, &stop] {
  2403. int i = 0;
  2404. while (!stop.load(std::memory_order_relaxed)) {
  2405. struct addrinfo hints;
  2406. memset(&hints, 0, sizeof(hints));
  2407. hints.ai_family = AF_UNSPEC;
  2408. hints.ai_socktype = SOCK_STREAM;
  2409. auto host = unique_unresolvable_host(t * 100000 + i++);
  2410. struct addrinfo *result = nullptr;
  2411. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2412. &result, /*timeout_sec=*/1);
  2413. if (rc == 0 && result) { freeaddrinfo(result); }
  2414. }
  2415. });
  2416. }
  2417. std::this_thread::sleep_for(std::chrono::seconds(8));
  2418. stop.store(true, std::memory_order_relaxed);
  2419. for (auto &th : threads) {
  2420. th.join();
  2421. }
  2422. std::this_thread::sleep_for(std::chrono::seconds(3));
  2423. }
  2424. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2425. if (!should_run_issue_2431_tests()) {
  2426. GTEST_SKIP()
  2427. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2428. }
  2429. std::atomic<bool> stop{false};
  2430. std::vector<std::thread> threads;
  2431. for (int t = 0; t < 8; ++t) {
  2432. threads.emplace_back([t, &stop] {
  2433. int i = 0;
  2434. while (!stop.load(std::memory_order_relaxed)) {
  2435. auto host = unique_unresolvable_host(t * 100000 + i++);
  2436. Client cli(host, 80);
  2437. cli.set_connection_timeout(1, 0);
  2438. cli.set_read_timeout(1, 0);
  2439. cli.set_write_timeout(1, 0);
  2440. (void)cli.Get("/");
  2441. }
  2442. });
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(8));
  2445. stop.store(true, std::memory_order_relaxed);
  2446. for (auto &th : threads) {
  2447. th.join();
  2448. }
  2449. std::this_thread::sleep_for(std::chrono::seconds(3));
  2450. }
  2451. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2452. TEST(ConnectionErrorTest, InvalidHost) {
  2453. auto host = "-abcde.com";
  2454. #ifdef CPPHTTPLIB_SSL_ENABLED
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. #else
  2458. auto port = 80;
  2459. Client cli(host, port);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. EXPECT_EQ(Error::Connection, res.error());
  2465. }
  2466. TEST(ConnectionErrorTest, InvalidHost2) {
  2467. auto host = "httpcan.org/";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. stringstream s;
  2489. s << "error code: " << res.error();
  2490. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2491. }
  2492. TEST(ConnectionErrorTest, InvalidPort) {
  2493. auto host = "localhost";
  2494. auto port = 44380;
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host, port);
  2497. #else
  2498. Client cli(host, port);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. EXPECT_TRUE(Error::Connection == res.error() ||
  2504. Error::ConnectionTimeout == res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, Timeout_Online) {
  2507. auto host = "google.com";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. auto port = 44380;
  2510. SSLClient cli(host, port);
  2511. #else
  2512. auto port = 8080;
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. // only probe one address type so that the error reason
  2517. // correlates to the timed-out IPv4, not the unsupported
  2518. // IPv6 connection attempt
  2519. cli.set_address_family(AF_INET);
  2520. auto res = cli.Get("/");
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2523. }
  2524. TEST(CancelTest, NoCancel_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/range/32"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. auto port = 443;
  2529. SSLClient cli(host, port);
  2530. #else
  2531. auto port = 80;
  2532. Client cli(host, port);
  2533. #endif
  2534. cli.set_connection_timeout(std::chrono::seconds(5));
  2535. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2538. EXPECT_EQ(StatusCode::OK_200, res->status);
  2539. }
  2540. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2541. // Use /bytes with a large payload so that the DownloadProgress callback
  2542. // (which only fires for Content-Length responses) is invoked before the
  2543. // entire body is received, giving cancellation a chance to fire.
  2544. auto host = "httpbingo.org";
  2545. auto path = std::string{"/bytes/524288"};
  2546. #ifdef CPPHTTPLIB_SSL_ENABLED
  2547. auto port = 443;
  2548. SSLClient cli(host, port);
  2549. #else
  2550. auto port = 80;
  2551. Client cli(host, port);
  2552. #endif
  2553. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2554. cli.set_connection_timeout(std::chrono::seconds(5));
  2555. ASSERT_TRUE(!res);
  2556. EXPECT_EQ(Error::Canceled, res.error());
  2557. }
  2558. TEST(CancelTest, WithCancelLargePayload_Online) {
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. cli.set_connection_timeout(std::chrono::seconds(5));
  2569. uint32_t count = 0;
  2570. auto res =
  2571. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_EQ(Error::Canceled, res.error());
  2574. }
  2575. TEST(CancelTest, NoCancelPost) {
  2576. Server svr;
  2577. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_connection_timeout(std::chrono::seconds(5));
  2589. auto res =
  2590. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2591. "application/json", [](uint64_t, uint64_t) { return true; });
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ("Hello World!", res->body);
  2594. EXPECT_EQ(StatusCode::OK_200, res->status);
  2595. }
  2596. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2597. Server svr;
  2598. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return false; });
  2613. ASSERT_TRUE(!res);
  2614. EXPECT_EQ(Error::Canceled, res.error());
  2615. }
  2616. TEST(CancelTest, WithCancelLargePayloadPost) {
  2617. Server svr;
  2618. svr.set_payload_max_length(200 * 1024 * 1024);
  2619. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content(LARGE_DATA, "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_payload_max_length(200 * 1024 * 1024);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, NoCancelPut) {
  2639. Server svr;
  2640. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content("Hello World!", "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_connection_timeout(std::chrono::seconds(5));
  2652. auto res =
  2653. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2654. "application/json", [](uint64_t, uint64_t) { return true; });
  2655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2656. EXPECT_EQ("Hello World!", res->body);
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2660. Server svr;
  2661. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return false; });
  2676. ASSERT_TRUE(!res);
  2677. EXPECT_EQ(Error::Canceled, res.error());
  2678. }
  2679. TEST(CancelTest, WithCancelLargePayloadPut) {
  2680. Server svr;
  2681. svr.set_payload_max_length(200 * 1024 * 1024);
  2682. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content(LARGE_DATA, "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_payload_max_length(200 * 1024 * 1024);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, NoCancelPatch) {
  2702. Server svr;
  2703. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_connection_timeout(std::chrono::seconds(5));
  2715. auto res =
  2716. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2717. "application/json", [](uint64_t, uint64_t) { return true; });
  2718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2719. EXPECT_EQ("Hello World!", res->body);
  2720. EXPECT_EQ(StatusCode::OK_200, res->status);
  2721. }
  2722. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2723. Server svr;
  2724. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2725. res.set_content("Hello World!", "text/plain");
  2726. });
  2727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2728. auto se = detail::scope_exit([&] {
  2729. svr.stop();
  2730. thread.join();
  2731. ASSERT_FALSE(svr.is_running());
  2732. });
  2733. svr.wait_until_ready();
  2734. Client cli(HOST, PORT);
  2735. cli.set_connection_timeout(std::chrono::seconds(5));
  2736. auto res =
  2737. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2738. "application/json", [](uint64_t, uint64_t) { return false; });
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Canceled, res.error());
  2741. }
  2742. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2743. Server svr;
  2744. svr.set_payload_max_length(200 * 1024 * 1024);
  2745. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2746. res.set_content(LARGE_DATA, "text/plain");
  2747. });
  2748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2749. auto se = detail::scope_exit([&] {
  2750. svr.stop();
  2751. thread.join();
  2752. ASSERT_FALSE(svr.is_running());
  2753. });
  2754. svr.wait_until_ready();
  2755. Client cli(HOST, PORT);
  2756. cli.set_payload_max_length(200 * 1024 * 1024);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, NoCancelDelete) {
  2765. Server svr;
  2766. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2767. res.set_content("Hello World!", "text/plain");
  2768. });
  2769. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2770. auto se = detail::scope_exit([&] {
  2771. svr.stop();
  2772. thread.join();
  2773. ASSERT_FALSE(svr.is_running());
  2774. });
  2775. svr.wait_until_ready();
  2776. Client cli(HOST, PORT);
  2777. cli.set_connection_timeout(std::chrono::seconds(5));
  2778. auto res =
  2779. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2780. "application/json", [](uint64_t, uint64_t) { return true; });
  2781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2782. EXPECT_EQ("Hello World!", res->body);
  2783. EXPECT_EQ(StatusCode::OK_200, res->status);
  2784. }
  2785. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2786. Server svr;
  2787. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2788. res.set_content("Hello World!", "text/plain");
  2789. });
  2790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2791. auto se = detail::scope_exit([&] {
  2792. svr.stop();
  2793. thread.join();
  2794. ASSERT_FALSE(svr.is_running());
  2795. });
  2796. svr.wait_until_ready();
  2797. Client cli(HOST, PORT);
  2798. cli.set_connection_timeout(std::chrono::seconds(5));
  2799. auto res =
  2800. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2801. "application/json", [](uint64_t, uint64_t) { return false; });
  2802. ASSERT_TRUE(!res);
  2803. EXPECT_EQ(Error::Canceled, res.error());
  2804. }
  2805. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2806. Server svr;
  2807. svr.set_payload_max_length(200 * 1024 * 1024);
  2808. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2809. res.set_content(LARGE_DATA, "text/plain");
  2810. });
  2811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2812. auto se = detail::scope_exit([&] {
  2813. svr.stop();
  2814. thread.join();
  2815. ASSERT_FALSE(svr.is_running());
  2816. });
  2817. svr.wait_until_ready();
  2818. Client cli(HOST, PORT);
  2819. cli.set_payload_max_length(200 * 1024 * 1024);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. static std::string remove_whitespace(const std::string &input) {
  2828. std::string output;
  2829. output.reserve(input.size());
  2830. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2831. [](unsigned char c) { return !std::isspace(c); });
  2832. return output;
  2833. }
  2834. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2835. auto host = "httpbingo.org";
  2836. auto path = std::string{"/basic-auth/hello/world"};
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. auto port = 443;
  2839. SSLClient cli(host, port);
  2840. #else
  2841. auto port = 80;
  2842. Client cli(host, port);
  2843. #endif
  2844. {
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. auto res = cli.Get(
  2851. path, Headers{make_basic_authentication_header("hello", "world")});
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. auto body = remove_whitespace(res->body);
  2854. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2855. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. }
  2858. {
  2859. cli.set_basic_auth("hello", "world");
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. auto body = remove_whitespace(res->body);
  2863. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2864. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. {
  2868. cli.set_basic_auth("hello", "bad");
  2869. auto res = cli.Get(path);
  2870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2871. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("bad", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2878. }
  2879. }
  2880. #ifdef CPPHTTPLIB_SSL_ENABLED
  2881. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2882. auto host = "httpbingo.org";
  2883. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2884. auto paths = std::vector<std::string>{
  2885. "/digest-auth/auth/hello/world/MD5",
  2886. "/digest-auth/auth/hello/world/SHA-256",
  2887. };
  2888. auto port = 443;
  2889. SSLClient cli(host, port);
  2890. {
  2891. auto res = cli.Get(unauth_path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_digest_auth("hello", "world");
  2897. for (const auto &path : paths) {
  2898. auto res = cli.Get(path.c_str());
  2899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2900. auto body = remove_whitespace(res->body);
  2901. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2902. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. }
  2905. cli.set_digest_auth("hello", "bad");
  2906. for (const auto &path : paths) {
  2907. auto res = cli.Get(path.c_str());
  2908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2909. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2910. }
  2911. }
  2912. }
  2913. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2914. // comma-separated list of challenges, and each challenge may itself carry a
  2915. // comma-separated auth-param list, so a server can legally offer Basic
  2916. // before Digest, either as two field lines or packed into one. Runs one 401
  2917. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2918. // value() joins them in receipt order) and checks that the retry carries a
  2919. // well-formed Digest Authorization header naming expected_realm.
  2920. static void
  2921. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2922. const std::string &expected_realm) {
  2923. std::atomic<int> hits{0};
  2924. Server svr;
  2925. svr.Get("/x", [&](const Request &req, Response &res) {
  2926. if (++hits == 1) {
  2927. res.status = StatusCode::Unauthorized_401;
  2928. for (const auto &challenge : challenges) {
  2929. res.set_header("WWW-Authenticate", challenge);
  2930. }
  2931. } else {
  2932. auto authorization = req.get_header_value("Authorization");
  2933. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2934. EXPECT_NE(std::string::npos,
  2935. authorization.find("realm=\"" + expected_realm + "\""));
  2936. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2937. res.set_content("ok", "text/plain");
  2938. }
  2939. });
  2940. auto port = svr.bind_to_any_port(HOST);
  2941. std::thread t([&]() { svr.listen_after_bind(); });
  2942. auto se = detail::scope_exit([&] {
  2943. svr.stop();
  2944. t.join();
  2945. });
  2946. svr.wait_until_ready();
  2947. Client cli(HOST, port);
  2948. cli.set_digest_auth("hello", "world");
  2949. auto res = cli.Get("/x");
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(2, hits.load());
  2952. }
  2953. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2954. static const char *kDigestChallenge =
  2955. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2956. "algorithm=MD5";
  2957. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2958. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2959. "testrealm");
  2960. }
  2961. // Same challenge list with the schemes in the opposite order, to make sure
  2962. // the fix above didn't just special-case "Basic first".
  2963. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2964. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2965. "testrealm");
  2966. }
  2967. // A comma inside a quoted auth-param value must not be mistaken for the
  2968. // separator between two challenges (or two auth-params).
  2969. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2970. run_digest_challenge_list_test(
  2971. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2972. "algorithm=MD5"},
  2973. "test,realm");
  2974. }
  2975. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2976. // the params and leaves out the fragment.
  2977. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2978. Server svr;
  2979. std::string uri, target;
  2980. svr.Get("/a b", [&](const Request &req, Response &res) {
  2981. auto auth = req.get_header_value("Authorization");
  2982. if (auth.empty()) {
  2983. res.status = StatusCode::Unauthorized_401;
  2984. res.set_header("WWW-Authenticate",
  2985. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2986. return;
  2987. }
  2988. auto b = auth.find("uri=\"") + 5;
  2989. uri = auth.substr(b, auth.find('"', b) - b);
  2990. target = req.target;
  2991. });
  2992. auto port = svr.bind_to_any_port(HOST);
  2993. std::thread t([&]() { svr.listen_after_bind(); });
  2994. auto se = detail::scope_exit([&] {
  2995. svr.stop();
  2996. t.join();
  2997. });
  2998. svr.wait_until_ready();
  2999. Client cli(HOST, port);
  3000. cli.set_digest_auth("hello", "world");
  3001. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ("/a%20b?x=1", target);
  3004. EXPECT_EQ(target, uri);
  3005. }
  3006. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3007. // make_digest_authentication_header() dereferences both unconditionally, so
  3008. // a server sending a challenge missing either one must not be treated as
  3009. // usable -- doing so used to crash the client with std::out_of_range.
  3010. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3011. Server svr;
  3012. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3013. res.status = StatusCode::Unauthorized_401;
  3014. res.set_header("WWW-Authenticate", challenge);
  3015. });
  3016. auto port = svr.bind_to_any_port(HOST);
  3017. std::thread t([&]() { svr.listen_after_bind(); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. t.join();
  3021. });
  3022. svr.wait_until_ready();
  3023. Client cli(HOST, port);
  3024. cli.set_digest_auth("hello", "world");
  3025. auto res = cli.Get("/x");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3028. }
  3029. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3030. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3031. }
  3032. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3033. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3034. }
  3035. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3036. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3037. }
  3038. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3039. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3040. // when storing the values, so the header builder has to re-escape them (and
  3041. // keep algorithm a bare token); otherwise the value breaks out of its
  3042. // quoted-string and injects extra auth-params into the client's Authorization.
  3043. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3044. std::atomic<int> hits{0};
  3045. std::string authorization;
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request &req, Response &res) {
  3048. if (++hits == 1) {
  3049. res.status = StatusCode::Unauthorized_401;
  3050. // On the wire the quotes embedded in the values are backslash-escaped.
  3051. res.set_header("WWW-Authenticate",
  3052. "Digest realm=\"testrealm\", "
  3053. "nonce=\"n\\\"; injected=\\\"x\", "
  3054. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3055. } else {
  3056. authorization = req.get_header_value("Authorization");
  3057. res.set_content("ok", "text/plain");
  3058. }
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. std::thread t([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. t.join();
  3065. });
  3066. svr.wait_until_ready();
  3067. Client cli(HOST, port);
  3068. cli.set_digest_auth("hello", "world");
  3069. auto res = cli.Get("/x");
  3070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3071. EXPECT_EQ(2, hits.load());
  3072. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3073. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3074. // inside its quoted-string rather than starting an "injected" auth-param.
  3075. EXPECT_NE(std::string::npos,
  3076. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3077. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3078. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3079. }
  3080. #endif
  3081. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3082. auto host = "google.com";
  3083. auto another_host = "example.com";
  3084. auto wrong_ip = "0.0.0.0";
  3085. #ifdef CPPHTTPLIB_SSL_ENABLED
  3086. SSLClient cli(host);
  3087. #else
  3088. Client cli(host);
  3089. #endif
  3090. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3091. auto res = cli.Get("/");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3094. }
  3095. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3096. auto host = "google.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(!res);
  3106. EXPECT_EQ(Error::Connection, res.error());
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3109. // A mapped value that is not an IP literal must be resolved. "localhost"
  3110. // resolves from the hosts file, so this test needs no external DNS.
  3111. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3112. auto host = "target.invalid";
  3113. Server svr;
  3114. std::string received_host;
  3115. svr.Get("/hi", [&](const Request &req, Response &res) {
  3116. received_host = req.get_header_value("Host");
  3117. res.set_content("Hello World!", "text/plain");
  3118. });
  3119. auto port = svr.bind_to_any_port(HOST);
  3120. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3121. auto se = detail::scope_exit([&] {
  3122. svr.stop();
  3123. thread.join();
  3124. ASSERT_FALSE(svr.is_running());
  3125. });
  3126. svr.wait_until_ready();
  3127. Client cli(host, port);
  3128. cli.set_hostname_addr_map({{host, HOST}});
  3129. auto res = cli.Get("/hi");
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. // The mapping only redirects the connection; the identity stays host_.
  3133. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3134. }
  3135. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3136. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3137. auto host = "target.invalid";
  3138. Server svr;
  3139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3140. res.set_content("Hello World!", "text/plain");
  3141. });
  3142. auto port = svr.bind_to_any_port("127.0.0.1");
  3143. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3144. auto se = detail::scope_exit([&] {
  3145. svr.stop();
  3146. thread.join();
  3147. ASSERT_FALSE(svr.is_running());
  3148. });
  3149. svr.wait_until_ready();
  3150. Client cli(host, port);
  3151. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3152. auto res = cli.Get("/hi");
  3153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3154. EXPECT_EQ(StatusCode::OK_200, res->status);
  3155. }
  3156. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3157. // An empty mapped value must leave host_ as the connection target. Without
  3158. // that guard the empty value would become the host argument, getaddrinfo
  3159. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3160. // loopback - silently connecting somewhere the caller never asked for.
  3161. // The server listens on loopback, so such a fallback would succeed and is
  3162. // therefore observable as a failure of this test.
  3163. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3164. Server svr;
  3165. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3166. res.set_content("Hello World!", "text/plain");
  3167. });
  3168. auto port = svr.bind_to_any_port(HOST);
  3169. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. Client cli(blackhole, port);
  3177. cli.set_hostname_addr_map({{blackhole, ""}});
  3178. cli.set_connection_timeout(1);
  3179. auto res = cli.Get("/hi");
  3180. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3181. }
  3182. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3183. auto host = "httpbingo.org";
  3184. auto path = std::string{"/absolute-redirect/3"};
  3185. #ifdef CPPHTTPLIB_SSL_ENABLED
  3186. SSLClient cli(host);
  3187. #else
  3188. Client cli(host);
  3189. #endif
  3190. cli.set_follow_location(true);
  3191. auto res = cli.Get(path);
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. }
  3195. TEST(RedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RelativeRedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/relative-redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(TooManyRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/redirect/21"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(!res);
  3232. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3233. }
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. TEST(YahooRedirectTest, Redirect_Online) {
  3236. Client cli("yahoo.com");
  3237. auto res = cli.Get("/");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3240. cli.set_follow_location(true);
  3241. res = cli.Get("/");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3245. }
  3246. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3247. #define REDIR_HOST "httpbingo.org"
  3248. #define REDIR_PATH "/redirect-to"
  3249. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3250. SSLClient cli(REDIR_HOST);
  3251. cli.set_follow_location(true);
  3252. auto res =
  3253. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. }
  3257. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3258. SSLClient cli(REDIR_HOST);
  3259. cli.set_follow_location(true);
  3260. Params params;
  3261. params.emplace("url", "http://example.com");
  3262. params.emplace("status_code", "302");
  3263. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. }
  3267. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3268. SSLClient cli(REDIR_HOST);
  3269. cli.set_follow_location(true);
  3270. Params params;
  3271. params.emplace("url", "http://example.com");
  3272. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::OK_200, res->status);
  3275. }
  3276. TEST(UrlWithSpace, Redirect_Online) {
  3277. SSLClient cli("edge.forgecdn.net");
  3278. cli.set_follow_location(true);
  3279. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3281. EXPECT_EQ(StatusCode::OK_200, res->status);
  3282. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3283. }
  3284. #endif
  3285. #if !defined(_WIN32) && !defined(_WIN64)
  3286. TEST(ReceiveSignals, Signal) {
  3287. auto setupSignalHandlers = []() {
  3288. struct sigaction act;
  3289. sigemptyset(&act.sa_mask);
  3290. act.sa_flags = SA_SIGINFO;
  3291. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3292. switch (sig) {
  3293. case SIGINT:
  3294. default: break;
  3295. }
  3296. };
  3297. ::sigaction(SIGINT, &act, nullptr);
  3298. };
  3299. Server svr;
  3300. int port = 0;
  3301. auto thread = std::thread([&]() {
  3302. setupSignalHandlers();
  3303. port = svr.bind_to_any_port(HOST);
  3304. svr.listen_after_bind();
  3305. });
  3306. auto se = detail::scope_exit([&] {
  3307. svr.stop();
  3308. thread.join();
  3309. ASSERT_FALSE(svr.is_running());
  3310. });
  3311. svr.wait_until_ready();
  3312. ASSERT_TRUE(svr.is_running());
  3313. pthread_kill(thread.native_handle(), SIGINT);
  3314. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3315. ASSERT_TRUE(svr.is_running());
  3316. }
  3317. #endif
  3318. TEST(RedirectToDifferentPort, Redirect) {
  3319. Server svr1;
  3320. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3321. res.set_content("Hello World!", "text/plain");
  3322. });
  3323. int svr1_port = 0;
  3324. auto thread1 = std::thread([&]() {
  3325. svr1_port = svr1.bind_to_any_port(HOST);
  3326. svr1.listen_after_bind();
  3327. });
  3328. Server svr2;
  3329. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3330. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3331. });
  3332. int svr2_port = 0;
  3333. auto thread2 = std::thread([&]() {
  3334. svr2_port = svr2.bind_to_any_port(HOST);
  3335. svr2.listen_after_bind();
  3336. });
  3337. auto se = detail::scope_exit([&] {
  3338. svr2.stop();
  3339. thread2.join();
  3340. svr1.stop();
  3341. thread1.join();
  3342. ASSERT_FALSE(svr2.is_running());
  3343. ASSERT_FALSE(svr1.is_running());
  3344. });
  3345. svr1.wait_until_ready();
  3346. svr2.wait_until_ready();
  3347. Client cli("localhost", svr2_port);
  3348. cli.set_follow_location(true);
  3349. auto res = cli.Get("/2");
  3350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("Hello World!", res->body);
  3353. }
  3354. // GET /redir on one server redirects to /target on another port, so the
  3355. // client follows it with a new client.
  3356. static Result
  3357. GetThroughRedirectToDifferentPort(Server::Handler target,
  3358. const std::function<void(Client &)> &setup,
  3359. const Headers &headers = Headers()) {
  3360. Server target_svr;
  3361. target_svr.Get("/target", target);
  3362. int target_port = 0;
  3363. auto target_thread = std::thread([&]() {
  3364. target_port = target_svr.bind_to_any_port(HOST);
  3365. target_svr.listen_after_bind();
  3366. });
  3367. Server origin_svr;
  3368. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3369. res.set_redirect(
  3370. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3371. });
  3372. int origin_port = 0;
  3373. auto origin_thread = std::thread([&]() {
  3374. origin_port = origin_svr.bind_to_any_port(HOST);
  3375. origin_svr.listen_after_bind();
  3376. });
  3377. auto se = detail::scope_exit([&] {
  3378. origin_svr.stop();
  3379. origin_thread.join();
  3380. target_svr.stop();
  3381. target_thread.join();
  3382. });
  3383. target_svr.wait_until_ready();
  3384. origin_svr.wait_until_ready();
  3385. Client cli("localhost", origin_port);
  3386. cli.set_follow_location(true);
  3387. setup(cli);
  3388. return cli.Get("/redir", headers);
  3389. }
  3390. static void
  3391. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3392. std::string captured_authorization;
  3393. auto result = GetThroughRedirectToDifferentPort(
  3394. [&](const Request &req, Response &res) {
  3395. captured_authorization = req.get_header_value("Authorization");
  3396. res.set_content("OK", "text/plain");
  3397. },
  3398. set_auth);
  3399. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3400. EXPECT_EQ(StatusCode::OK_200, result->status);
  3401. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3402. EXPECT_TRUE(captured_authorization.empty());
  3403. }
  3404. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3405. TestDoNotForwardCredentialsOnRedirect(
  3406. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3407. }
  3408. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3409. TestDoNotForwardCredentialsOnRedirect(
  3410. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3411. }
  3412. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3413. std::string captured_cookie;
  3414. auto result = GetThroughRedirectToDifferentPort(
  3415. [&](const Request &req, Response &res) {
  3416. captured_cookie = req.get_header_value("Cookie");
  3417. res.set_content("OK", "text/plain");
  3418. },
  3419. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3420. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3421. EXPECT_EQ(StatusCode::OK_200, result->status);
  3422. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3423. EXPECT_TRUE(captured_cookie.empty());
  3424. }
  3425. TEST(RedirectToSamePort, ForwardCookie) {
  3426. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3427. // header so that ordinary session flows keep working.
  3428. Server svr;
  3429. std::string captured_cookie;
  3430. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3431. res.set_redirect("/target", 302);
  3432. });
  3433. svr.Get("/target", [&](const Request &req, Response &res) {
  3434. captured_cookie = req.get_header_value("Cookie");
  3435. res.set_content("OK", "text/plain");
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. Client cli(HOST, port);
  3446. cli.set_follow_location(true);
  3447. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3448. auto res = cli.Get("/redir", headers);
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3452. }
  3453. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3454. std::string authorization;
  3455. std::string trace_id;
  3456. auto result = GetThroughRedirectToDifferentPort(
  3457. [&](const Request &req, Response &res) {
  3458. authorization = req.get_header_value("Authorization");
  3459. trace_id = req.get_header_value("X-Trace-Id");
  3460. res.set_content("OK", "text/plain");
  3461. },
  3462. [](Client &cli) {
  3463. cli.set_default_headers(
  3464. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3465. });
  3466. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3467. EXPECT_EQ(StatusCode::OK_200, result->status);
  3468. // Like a header given with the request, a default one goes along unless it
  3469. // carries credentials (RFC 9110 15.4).
  3470. EXPECT_TRUE(authorization.empty());
  3471. EXPECT_EQ("42", trace_id);
  3472. }
  3473. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3474. auto result = GetThroughRedirectToDifferentPort(
  3475. [](const Request &, Response &res) {
  3476. res.set_content(std::string(2048, 'x'), "text/plain");
  3477. },
  3478. [](Client &cli) { cli.set_payload_max_length(1024); });
  3479. EXPECT_FALSE(result);
  3480. }
  3481. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3482. auto result = GetThroughRedirectToDifferentPort(
  3483. [](const Request &req, Response &res) {
  3484. // Answer after a second, or once the client gives up.
  3485. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3487. }
  3488. res.set_content("late", "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3491. ASSERT_FALSE(result);
  3492. EXPECT_EQ(Error::Read, result.error());
  3493. }
  3494. #ifdef CPPHTTPLIB_SSL_ENABLED
  3495. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.status = StatusCode::Unauthorized_401;
  3499. res.set_header("WWW-Authenticate",
  3500. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3501. },
  3502. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3503. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3504. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3505. }
  3506. #endif
  3507. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3508. Server svr;
  3509. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3510. // Port number that overflows int — should not crash
  3511. res.set_redirect("http://localhost:99999999999999999999/target");
  3512. });
  3513. auto port = svr.bind_to_any_port(HOST);
  3514. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. Client cli(HOST, port);
  3522. cli.set_follow_location(true);
  3523. auto res = cli.Get("/redir");
  3524. // Should fail gracefully, not crash (no valid response due to bad port)
  3525. EXPECT_FALSE(res);
  3526. }
  3527. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3528. Server svr;
  3529. auto port = svr.bind_to_any_port(HOST);
  3530. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3531. // The server's own port followed by junk must not be followed
  3532. res.set_redirect("http://" + std::string(HOST) + ":" +
  3533. std::to_string(port) + "junk/target");
  3534. });
  3535. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3536. res.set_content("target", "text/plain");
  3537. });
  3538. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. thread.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. svr.wait_until_ready();
  3545. Client cli(HOST, port);
  3546. cli.set_follow_location(true);
  3547. auto res = cli.Get("/redir");
  3548. EXPECT_FALSE(res);
  3549. }
  3550. TEST(RedirectFromPageWithContent, Redirect) {
  3551. Server svr;
  3552. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3553. res.set_content("___", "text/plain");
  3554. res.set_redirect("/2");
  3555. });
  3556. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3557. res.set_content("Hello World!", "text/plain");
  3558. });
  3559. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. th.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. Client cli("localhost", PORT);
  3568. cli.set_follow_location(true);
  3569. std::string body;
  3570. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3571. body.append(data, data_length);
  3572. return true;
  3573. });
  3574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("Hello World!", body);
  3577. }
  3578. {
  3579. Client cli("localhost", PORT);
  3580. std::string body;
  3581. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3582. body.append(data, data_length);
  3583. return true;
  3584. });
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ(StatusCode::Found_302, res->status);
  3587. EXPECT_EQ("___", body);
  3588. }
  3589. }
  3590. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3591. Server svr;
  3592. auto port_str = std::to_string(PORT);
  3593. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3594. auto expected_host = "[::1]:" + port_str;
  3595. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3596. res.set_content("___", "text/plain");
  3597. // res.set_redirect("/2");
  3598. res.set_redirect(redirect_url);
  3599. });
  3600. svr.Get("/2", [&](const Request &req, Response &res) {
  3601. auto host_header = req.headers.find("Host");
  3602. ASSERT_TRUE(host_header != req.headers.end());
  3603. EXPECT_EQ(expected_host, host_header->second);
  3604. res.set_content("Hello World!", "text/plain");
  3605. });
  3606. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3607. auto se = detail::scope_exit([&] {
  3608. svr.stop();
  3609. th.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. });
  3612. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3613. // actually starts anything, so the condition !svr.is_running() will
  3614. // always remain true, and the loop never stops.
  3615. // This basically counts how many milliseconds have passed since the
  3616. // call to svr.listen(), and if after 5 seconds nothing started yet
  3617. // aborts the test.
  3618. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3619. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3620. ASSERT_LT(milliseconds, 5000U);
  3621. }
  3622. {
  3623. Client cli("::1", PORT);
  3624. cli.set_follow_location(true);
  3625. std::string body;
  3626. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3627. body.append(data, data_length);
  3628. return true;
  3629. });
  3630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. EXPECT_EQ("Hello World!", body);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::Found_302, res->status);
  3643. EXPECT_EQ("___", body);
  3644. }
  3645. }
  3646. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3647. Server svr;
  3648. svr.Get("/foo", [](const Request &req, Response &res) {
  3649. auto a = req.params.find("a");
  3650. if (a != req.params.end()) {
  3651. res.set_content((*a).second, "text/plain");
  3652. res.status = StatusCode::OK_200;
  3653. } else {
  3654. res.status = StatusCode::BadRequest_400;
  3655. }
  3656. });
  3657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3658. auto se = detail::scope_exit([&] {
  3659. svr.stop();
  3660. thread.join();
  3661. ASSERT_FALSE(svr.is_running());
  3662. });
  3663. svr.wait_until_ready();
  3664. {
  3665. Client cli(HOST, PORT);
  3666. cli.set_path_encode(false);
  3667. auto res = cli.Get("/foo?a=explicitly+encoded");
  3668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. // This expects it back with a space, as the `+` won't have been
  3671. // url-encoded, and server-side the params get decoded turning `+`
  3672. // into spaces.
  3673. EXPECT_EQ("explicitly encoded", res->body);
  3674. }
  3675. }
  3676. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3677. // When path encoding is disabled the client must transmit the supplied
  3678. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3679. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3680. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3681. // than a space (0x20). Assert on the raw wire target to catch this.
  3682. Server svr;
  3683. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3684. svr.Get("/foo", [&](const Request &req, Response &res) {
  3685. EXPECT_EQ(expected_target, req.target);
  3686. res.status = StatusCode::OK_200;
  3687. });
  3688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3689. auto se = detail::scope_exit([&] {
  3690. svr.stop();
  3691. thread.join();
  3692. ASSERT_FALSE(svr.is_running());
  3693. });
  3694. svr.wait_until_ready();
  3695. {
  3696. Client cli(HOST, PORT);
  3697. cli.set_path_encode(false);
  3698. auto res = cli.Get(expected_target.c_str());
  3699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. }
  3703. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3704. // `open_stream()` used to skip the path encoding that the buffered send
  3705. // path applies, so the same `path` produced different bytes in the request
  3706. // line depending on which API was used. Assert the two agree.
  3707. Server svr;
  3708. std::string target;
  3709. svr.Get(".*", [&](const Request &req, Response &res) {
  3710. target = req.target;
  3711. res.status = StatusCode::OK_200;
  3712. });
  3713. auto port = svr.bind_to_any_port(HOST);
  3714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3715. auto se = detail::scope_exit([&] {
  3716. svr.stop();
  3717. thread.join();
  3718. ASSERT_FALSE(svr.is_running());
  3719. });
  3720. svr.wait_until_ready();
  3721. struct {
  3722. const char *path;
  3723. const char *expected;
  3724. } cases[] = {
  3725. {"/a b?x=1", "/a%20b?x=1"},
  3726. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3727. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3728. };
  3729. for (const auto &c : cases) {
  3730. Client cli(HOST, port);
  3731. target.clear();
  3732. auto res = cli.Get(c.path);
  3733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3734. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3735. auto buffered_target = target;
  3736. target.clear();
  3737. auto handle = cli.open_stream("GET", c.path);
  3738. EXPECT_TRUE(handle.is_valid())
  3739. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3740. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3744. // The `set_path_encode(false)` contract — transmit the supplied target
  3745. // verbatim — must hold for the streaming API too.
  3746. Server svr;
  3747. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3748. std::string target;
  3749. svr.Get("/foo", [&](const Request &req, Response &res) {
  3750. target = req.target;
  3751. res.status = StatusCode::OK_200;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. cli.set_path_encode(false);
  3764. auto handle = cli.open_stream("GET", expected_target);
  3765. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3766. EXPECT_EQ(expected_target, target);
  3767. }
  3768. }
  3769. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3770. // With path encoding enabled a CR/LF in the target is percent-encoded
  3771. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3772. // write_request_line still backstops `set_path_encode(false)`, which is
  3773. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3774. Server svr;
  3775. // Captured before routing: the decoded path contains a newline, which a
  3776. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3777. std::string target;
  3778. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3779. target = req.target;
  3780. res.status = StatusCode::OK_200;
  3781. return Server::HandlerResponse::Handled;
  3782. });
  3783. auto port = svr.bind_to_any_port(HOST);
  3784. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, port);
  3793. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3794. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3795. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3796. }
  3797. }
  3798. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3799. // Every control character is percent-encoded, not just CR/LF, so the target
  3800. // passes the request-target check in write_request_line.
  3801. Server svr;
  3802. std::string target;
  3803. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3804. target = req.target;
  3805. res.status = StatusCode::OK_200;
  3806. return Server::HandlerResponse::Handled;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. Client cli(HOST, port);
  3818. auto res = cli.Get("/a\tb\x1b\x7f");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ("/a%09b%1B%7F", target);
  3821. }
  3822. }
  3823. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3824. // Nothing may reach the wire: a raw CR/LF target would split the request
  3825. // line and inject headers.
  3826. Server svr;
  3827. // Pre-routing so that "not called" means nothing reached the server at all,
  3828. // rather than merely failing to match a handler pattern.
  3829. auto handler_called = false;
  3830. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3831. handler_called = true;
  3832. res.status = StatusCode::OK_200;
  3833. return Server::HandlerResponse::Handled;
  3834. });
  3835. auto port = svr.bind_to_any_port(HOST);
  3836. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. {
  3844. Client cli(HOST, port);
  3845. cli.set_path_encode(false);
  3846. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3847. EXPECT_FALSE(handle.is_valid());
  3848. EXPECT_EQ(Error::Write, handle.error);
  3849. EXPECT_FALSE(handler_called);
  3850. }
  3851. }
  3852. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3853. // Which of the two branches runs is decided by whether the query component
  3854. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3855. // an empty query and must still fall back to building one from
  3856. // `req.params`, while a non-empty query must win over `req.params`.
  3857. Server svr;
  3858. std::string target;
  3859. svr.Get("/foo", [&](const Request &req, Response &res) {
  3860. target = req.target;
  3861. res.status = StatusCode::OK_200;
  3862. });
  3863. auto port = svr.bind_to_any_port(HOST);
  3864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3865. auto se = detail::scope_exit([&] {
  3866. svr.stop();
  3867. thread.join();
  3868. ASSERT_FALSE(svr.is_running());
  3869. });
  3870. svr.wait_until_ready();
  3871. {
  3872. // Trailing `?` -> empty query component -> `req.params` is used.
  3873. Client cli(HOST, port);
  3874. Request req;
  3875. req.method = "GET";
  3876. req.path = "/foo?";
  3877. req.params.emplace("a", "1");
  3878. target.clear();
  3879. auto res = cli.send(req);
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ("/foo?a=1", target);
  3882. }
  3883. {
  3884. // Non-empty query in `req.path` -> `req.params` is not appended.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?b=2";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?b=2", target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3897. Server svr;
  3898. svr.Get("/", [](const Request &req, Response &) {
  3899. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3900. });
  3901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3902. auto se = detail::scope_exit([&] {
  3903. svr.stop();
  3904. thread.join();
  3905. ASSERT_FALSE(svr.is_running());
  3906. });
  3907. svr.wait_until_ready();
  3908. {
  3909. Client cli(HOST, PORT);
  3910. cli.set_path_encode(false);
  3911. auto res = cli.Get("/?something=%0A");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. }
  3916. TEST(BindServerTest, BindDualStack) {
  3917. Server svr;
  3918. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3919. res.set_content("Hello World!", "text/plain");
  3920. });
  3921. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3922. auto se = detail::scope_exit([&] {
  3923. svr.stop();
  3924. thread.join();
  3925. ASSERT_FALSE(svr.is_running());
  3926. });
  3927. svr.wait_until_ready();
  3928. {
  3929. Client cli("127.0.0.1", PORT);
  3930. auto res = cli.Get("/1");
  3931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3932. EXPECT_EQ(StatusCode::OK_200, res->status);
  3933. EXPECT_EQ("Hello World!", res->body);
  3934. }
  3935. {
  3936. Client cli("::1", PORT);
  3937. auto res = cli.Get("/1");
  3938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3939. EXPECT_EQ(StatusCode::OK_200, res->status);
  3940. EXPECT_EQ("Hello World!", res->body);
  3941. }
  3942. }
  3943. TEST(BindServerTest, BindAndListenSeparately) {
  3944. Server svr;
  3945. int port = svr.bind_to_any_port("0.0.0.0");
  3946. ASSERT_TRUE(svr.is_valid());
  3947. ASSERT_TRUE(port > 0);
  3948. svr.stop();
  3949. }
  3950. // Reports whether anything is still listening on a loopback port. A plain
  3951. // connect() is used instead of a Client request because a socket left bound by
  3952. // mistake accepts the connection into its backlog and never answers, which
  3953. // would hang the test instead of failing it.
  3954. static bool is_loopback_port_accepting(int port) {
  3955. sockaddr_in addr{};
  3956. addr.sin_family = AF_INET;
  3957. addr.sin_port = htons(static_cast<uint16_t>(port));
  3958. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3959. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3960. EXPECT_NE(sock, INVALID_SOCKET);
  3961. if (sock == INVALID_SOCKET) { return false; }
  3962. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3963. static_cast<socklen_t>(sizeof(addr)));
  3964. detail::close_socket(sock);
  3965. return ret == 0;
  3966. }
  3967. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3968. Server svr;
  3969. auto port = svr.bind_to_any_port("127.0.0.1");
  3970. ASSERT_TRUE(port > 0);
  3971. svr.stop();
  3972. // bind_to_any_port() already called listen(2), so until stop() closed the
  3973. // descriptor the port kept accepting connections into the backlog. ASSERT
  3974. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3975. // below blocks forever in the accept loop.
  3976. ASSERT_FALSE(is_loopback_port_accepting(port));
  3977. // Nothing is left to accept on, so listen_after_bind() must report failure
  3978. // instead of returning success without ever serving.
  3979. EXPECT_FALSE(svr.listen_after_bind());
  3980. // The failed listen marks the server decommissioned, so a waiter returns
  3981. // instead of spinning forever.
  3982. svr.wait_until_ready();
  3983. }
  3984. #ifdef CPPHTTPLIB_SSL_ENABLED
  3985. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3987. CLIENT_CA_CERT_DIR);
  3988. int port = svr.bind_to_any_port("0.0.0.0");
  3989. ASSERT_TRUE(svr.is_valid());
  3990. ASSERT_TRUE(port > 0);
  3991. svr.stop();
  3992. }
  3993. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3994. // or a rejected CustomRoute() registration would not stop the server binding.
  3995. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3997. CLIENT_CA_CERT_DIR);
  3998. ASSERT_TRUE(svr.is_valid());
  3999. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4000. EXPECT_FALSE(svr.is_valid());
  4001. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4002. }
  4003. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4004. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4005. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4006. int port = svr.bind_to_any_port("0.0.0.0");
  4007. ASSERT_TRUE(svr.is_valid());
  4008. ASSERT_TRUE(port > 0);
  4009. svr.stop();
  4010. }
  4011. TEST(BindServerTest, UpdateCertsPem) {
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4013. int port = svr.bind_to_any_port("0.0.0.0");
  4014. ASSERT_TRUE(svr.is_valid());
  4015. ASSERT_TRUE(port > 0);
  4016. // Read PEM files
  4017. std::string cert_pem, key_pem, ca_pem;
  4018. read_file(SERVER_CERT_FILE, cert_pem);
  4019. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4020. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4021. // Update server certificates using PEM API
  4022. ASSERT_TRUE(
  4023. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4024. ASSERT_TRUE(svr.is_valid());
  4025. svr.stop();
  4026. }
  4027. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4028. // Start server with client CA (enables client auth)
  4029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4030. ASSERT_TRUE(svr.is_valid());
  4031. bool handler_called = false;
  4032. svr.Get("/test", [&](const Request &req, Response &res) {
  4033. handler_called = true;
  4034. // Verify client certificate is present
  4035. auto cert = req.peer_cert();
  4036. EXPECT_TRUE(static_cast<bool>(cert));
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // Read PEM files
  4047. std::string cert_pem, key_pem, ca_pem;
  4048. read_file(SERVER_CERT_FILE, cert_pem);
  4049. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4050. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4051. // Update server certificates and client CA using PEM API while server running
  4052. ASSERT_TRUE(
  4053. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4054. // Connect with client certificate
  4055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4056. cli.enable_server_certificate_verification(false);
  4057. cli.set_connection_timeout(30);
  4058. auto res = cli.Get("/test");
  4059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_TRUE(handler_called);
  4062. EXPECT_EQ("ok", res->body);
  4063. }
  4064. // Puts a CA that did not sign the client's certificate in the old one's place.
  4065. static bool replace_client_ca(SSLServer &svr) {
  4066. std::string cert_pem, key_pem, ca_pem;
  4067. read_file(SERVER_CERT_FILE, cert_pem);
  4068. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4069. read_file(SERVER_CERT2_FILE, ca_pem);
  4070. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4071. ca_pem.c_str());
  4072. }
  4073. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4075. ASSERT_TRUE(svr.is_valid());
  4076. svr.Get("/test", [](const Request &, Response &res) {
  4077. res.set_content("ok", "text/plain");
  4078. });
  4079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. t.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. auto get = [] {
  4087. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4088. cli.enable_server_certificate_verification(false);
  4089. return cli.Get("/test");
  4090. };
  4091. ASSERT_TRUE(get());
  4092. ASSERT_TRUE(replace_client_ca(svr));
  4093. EXPECT_FALSE(get());
  4094. }
  4095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4096. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4098. ASSERT_TRUE(svr.is_valid());
  4099. tls::set_verify_callback(svr.tls_context(),
  4100. [](const tls::VerifyContext &) -> bool {
  4101. throw std::runtime_error("verify");
  4102. });
  4103. svr.Get("/test", [](const Request &, Response &res) {
  4104. res.set_content("ok", "text/plain");
  4105. });
  4106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4107. auto se = detail::scope_exit([&] {
  4108. svr.stop();
  4109. t.join();
  4110. ASSERT_FALSE(svr.is_running());
  4111. });
  4112. svr.wait_until_ready();
  4113. auto get = [] {
  4114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4115. cli.enable_server_certificate_verification(false);
  4116. return cli.Get("/test");
  4117. };
  4118. EXPECT_FALSE(get());
  4119. // The handshake is over, so an update does not wait for it.
  4120. std::string cert_pem, key_pem;
  4121. read_file(SERVER_CERT_FILE, cert_pem);
  4122. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4123. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4124. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4125. return v.preverify_ok;
  4126. });
  4127. auto res = get();
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ("ok", res->body);
  4130. }
  4131. #endif
  4132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4133. // Sends each request over a new connection with a client certificate,
  4134. // resuming the session of the one before when there is one.
  4135. class ResumingClient {
  4136. public:
  4137. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4138. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4139. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4140. SSL_FILETYPE_PEM);
  4141. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4142. // callback, not through SSL_get1_session().
  4143. SSL_CTX_set_app_data(ctx_, this);
  4144. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4145. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4146. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4147. auto self = static_cast<ResumingClient *>(
  4148. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4149. SSL_SESSION_free(self->session_);
  4150. self->session_ = session;
  4151. return 1; // Keeps the reference
  4152. });
  4153. }
  4154. ~ResumingClient() {
  4155. SSL_SESSION_free(session_);
  4156. SSL_CTX_free(ctx_);
  4157. }
  4158. // Tells whether the request was answered.
  4159. bool get() {
  4160. auto error = Error::Success;
  4161. auto sock = detail::create_client_socket(
  4162. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4163. /*connection_timeout_sec=*/5, 0,
  4164. /*read_timeout_sec=*/5, 0,
  4165. /*write_timeout_sec=*/5, 0, std::string(), error);
  4166. if (sock == INVALID_SOCKET) { return false; }
  4167. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4168. auto ssl = SSL_new(ctx_);
  4169. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4170. SSL_set_fd(ssl, static_cast<int>(sock));
  4171. if (session_) { SSL_set_session(ssl, session_); }
  4172. if (SSL_connect(ssl) != 1) { return false; }
  4173. reused_ = SSL_session_reused(ssl) == 1;
  4174. // Reading the response also takes in a TLS 1.3 session ticket.
  4175. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4176. "Connection: close\r\n\r\n";
  4177. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4178. std::string res;
  4179. char buf[256];
  4180. int n;
  4181. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4182. res.append(buf, static_cast<size_t>(n));
  4183. }
  4184. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4185. SSL_shutdown(ssl);
  4186. return res.find("200 OK") != std::string::npos;
  4187. }
  4188. // Whether the last connection resumed a session
  4189. bool reused() const { return reused_; }
  4190. private:
  4191. SSL_CTX *ctx_;
  4192. SSL_SESSION *session_ = nullptr;
  4193. bool reused_ = false;
  4194. };
  4195. // A client that resumes its session gets through, but not once the client CA
  4196. // has changed, as a resumed session does not show the certificate again.
  4197. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4199. ASSERT_TRUE(svr.is_valid());
  4200. svr.Get("/test", [](const Request &, Response &res) {
  4201. res.set_content("ok", "text/plain");
  4202. });
  4203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. t.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. ResumingClient cli;
  4211. ASSERT_TRUE(cli.get());
  4212. ASSERT_TRUE(cli.get());
  4213. EXPECT_TRUE(cli.reused());
  4214. ASSERT_TRUE(replace_client_ca(svr));
  4215. EXPECT_FALSE(cli.get());
  4216. }
  4217. // A resumed session does not show the certificate again, so the server does
  4218. // not resume one with a verify callback to run on it.
  4219. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4223. return v.preverify_ok;
  4224. });
  4225. svr.Get("/test", [](const Request &, Response &res) {
  4226. res.set_content("ok", "text/plain");
  4227. });
  4228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4229. auto se = detail::scope_exit([&] {
  4230. svr.stop();
  4231. t.join();
  4232. ASSERT_FALSE(svr.is_running());
  4233. });
  4234. svr.wait_until_ready();
  4235. ResumingClient cli;
  4236. ASSERT_TRUE(cli.get());
  4237. ASSERT_TRUE(cli.get());
  4238. EXPECT_FALSE(cli.reused());
  4239. }
  4240. #endif
  4241. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4242. // wolfSSL shares its session cache between contexts, so a resumed session
  4243. // could carry a client certificate checked against another server's CA, or
  4244. // against a client CA since replaced.
  4245. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4247. ASSERT_TRUE(svr.is_valid());
  4248. // Trusts a CA that did not sign the client's certificate.
  4249. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4250. ASSERT_TRUE(other.is_valid());
  4251. for (auto s : {&svr, &other}) {
  4252. s->Get("/test", [](const Request &, Response &res) {
  4253. res.set_content("ok", "text/plain");
  4254. });
  4255. }
  4256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4257. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4258. auto se = detail::scope_exit([&] {
  4259. other.stop();
  4260. svr.stop();
  4261. t2.join();
  4262. t.join();
  4263. });
  4264. svr.wait_until_ready();
  4265. other.wait_until_ready();
  4266. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4267. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4268. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4269. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4270. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4271. ASSERT_EQ(WOLFSSL_SUCCESS,
  4272. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4273. WOLFSSL_FILETYPE_PEM));
  4274. WOLFSSL_SESSION *session = nullptr;
  4275. auto session_se = detail::scope_exit([&] {
  4276. if (session) { wolfSSL_SESSION_free(session); }
  4277. });
  4278. // A request over a new connection, resuming `session` when there is one and
  4279. // keeping the connection's own in its place. Tells whether it was answered.
  4280. auto get = [&](int port) {
  4281. auto error = Error::Success;
  4282. auto sock = detail::create_client_socket(
  4283. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4284. /*connection_timeout_sec=*/5, 0,
  4285. /*read_timeout_sec=*/5, 0,
  4286. /*write_timeout_sec=*/5, 0, std::string(), error);
  4287. if (sock == INVALID_SOCKET) { return false; }
  4288. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4289. auto ssl = wolfSSL_new(ctx);
  4290. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4291. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4292. if (session) { wolfSSL_set_session(ssl, session); }
  4293. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4294. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4295. "Connection: close\r\n\r\n";
  4296. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4297. std::string res;
  4298. char buf[256];
  4299. int n;
  4300. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4301. res.append(buf, static_cast<size_t>(n));
  4302. }
  4303. wolfSSL_shutdown(ssl);
  4304. if (session) { wolfSSL_SESSION_free(session); }
  4305. session = wolfSSL_get1_session(ssl);
  4306. return res.find("200 OK") != std::string::npos;
  4307. };
  4308. ASSERT_TRUE(get(PORT));
  4309. EXPECT_FALSE(get(PORT + 1));
  4310. ASSERT_TRUE(get(PORT));
  4311. ASSERT_TRUE(replace_client_ca(svr));
  4312. EXPECT_FALSE(get(PORT));
  4313. }
  4314. #endif
  4315. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4317. ASSERT_TRUE(svr.is_valid());
  4318. svr.Get("/test", [](const Request &, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4322. auto se = detail::scope_exit([&] {
  4323. svr.stop();
  4324. t.join();
  4325. ASSERT_FALSE(svr.is_running());
  4326. });
  4327. svr.wait_until_ready();
  4328. // A connection that sends no ClientHello keeps its handshake in progress,
  4329. // once the server has had a moment to start it.
  4330. auto error = Error::Success;
  4331. auto sock = detail::create_client_socket(
  4332. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4333. /*connection_timeout_sec=*/5, 0,
  4334. /*read_timeout_sec=*/5, 0,
  4335. /*write_timeout_sec=*/5, 0, std::string(), error);
  4336. ASSERT_NE(INVALID_SOCKET, sock);
  4337. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4338. std::string cert_pem, key_pem;
  4339. read_file(SERVER_CERT_FILE, cert_pem);
  4340. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4341. auto update = std::async(std::launch::async, [&]() {
  4342. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4343. });
  4344. EXPECT_EQ(std::future_status::timeout,
  4345. update.wait_for(std::chrono::milliseconds(200)));
  4346. detail::close_socket(sock);
  4347. EXPECT_TRUE(update.get());
  4348. SSLClient cli(HOST, PORT);
  4349. cli.enable_server_certificate_verification(false);
  4350. auto res = cli.Get("/test");
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. }
  4354. #endif
  4355. TEST(ErrorHandlerTest, ContentLength) {
  4356. Server svr;
  4357. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4358. res.status = StatusCode::OK_200;
  4359. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4360. "text/html"); // <= Content-Length still 13
  4361. });
  4362. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!\n", "text/plain");
  4364. res.status = 524;
  4365. });
  4366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4367. auto se = detail::scope_exit([&] {
  4368. svr.stop();
  4369. thread.join();
  4370. ASSERT_FALSE(svr.is_running());
  4371. });
  4372. svr.wait_until_ready();
  4373. {
  4374. Client cli(HOST, PORT);
  4375. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4379. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4380. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4381. }
  4382. }
  4383. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4384. TEST(ExceptionTest, WithoutExceptionHandler) {
  4385. Server svr;
  4386. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4387. throw std::runtime_error("exception...");
  4388. });
  4389. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4390. throw std::runtime_error("exception\r\n...");
  4391. });
  4392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4393. auto se = detail::scope_exit([&] {
  4394. svr.stop();
  4395. listen_thread.join();
  4396. ASSERT_FALSE(svr.is_running());
  4397. });
  4398. svr.wait_until_ready();
  4399. Client cli("localhost", PORT);
  4400. {
  4401. auto res = cli.Get("/exception");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4404. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4405. }
  4406. {
  4407. auto res = cli.Get("/unknown");
  4408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4409. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4410. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4411. }
  4412. }
  4413. TEST(ExceptionTest, WithExceptionHandler) {
  4414. Server svr;
  4415. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4416. std::exception_ptr ep) {
  4417. EXPECT_FALSE(ep == nullptr);
  4418. try {
  4419. std::rethrow_exception(ep);
  4420. } catch (std::exception &e) {
  4421. EXPECT_EQ("abc", std::string(e.what()));
  4422. } catch (...) {}
  4423. res.status = StatusCode::InternalServerError_500;
  4424. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4425. "text/html"); // <= Content-Length still 13 at this point
  4426. });
  4427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("Hello World!\n", "text/plain");
  4429. throw std::runtime_error("abc");
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. for (size_t i = 0; i < 10; i++) {
  4439. Client cli(HOST, PORT);
  4440. for (size_t j = 0; j < 100; j++) {
  4441. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4444. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4445. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4447. }
  4448. cli.set_keep_alive(true);
  4449. for (size_t j = 0; j < 100; j++) {
  4450. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4454. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4455. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4456. }
  4457. }
  4458. }
  4459. TEST(ExceptionTest, AndErrorHandler) {
  4460. Server svr;
  4461. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4462. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4463. });
  4464. svr.set_exception_handler(
  4465. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4466. EXPECT_FALSE(ep == nullptr);
  4467. try {
  4468. std::rethrow_exception(ep);
  4469. } catch (std::exception &e) {
  4470. res.set_content(e.what(), "text/html");
  4471. } catch (...) {}
  4472. res.status = StatusCode::InternalServerError_500;
  4473. });
  4474. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4475. throw std::runtime_error("EXCEPTION");
  4476. });
  4477. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4478. res.set_content("ERROR", "text/html");
  4479. res.status = StatusCode::InternalServerError_500;
  4480. });
  4481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4482. auto se = detail::scope_exit([&] {
  4483. svr.stop();
  4484. thread.join();
  4485. ASSERT_FALSE(svr.is_running());
  4486. });
  4487. svr.wait_until_ready();
  4488. Client cli(HOST, PORT);
  4489. {
  4490. auto res = cli.Get("/exception");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4493. EXPECT_EQ("EXCEPTION", res->body);
  4494. }
  4495. {
  4496. auto res = cli.Get("/error");
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4499. EXPECT_EQ("ERROR", res->body);
  4500. }
  4501. {
  4502. auto res = cli.Get("/invalid");
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4505. EXPECT_EQ("NOT_FOUND", res->body);
  4506. }
  4507. }
  4508. #endif
  4509. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4510. // process_request() wraps only routing() in a try/catch, so an exception from
  4511. // any other user callback used to unwind into the task queue - which does not
  4512. // catch - and terminate the process. Each test below runs the server on a
  4513. // single worker thread: a guard that catches the exception but still loses the
  4514. // thread would otherwise be hidden by a spare worker serving the follow-up
  4515. // request. Note that a regression here aborts the whole test binary rather
  4516. // than failing one test.
  4517. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4518. Server svr;
  4519. svr.new_task_queue = [] { return new ThreadPool(1); };
  4520. std::atomic<int> reported{0};
  4521. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4522. if (err == Error::UserCallbackException) { reported++; }
  4523. });
  4524. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4525. res.set_content_provider(
  4526. 1024, "text/plain",
  4527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4528. sink.write("hello", 5);
  4529. throw std::runtime_error("from the content provider");
  4530. });
  4531. });
  4532. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4533. res.set_content("ok", "text/plain");
  4534. });
  4535. auto port = svr.bind_to_any_port(HOST);
  4536. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4537. auto se = detail::scope_exit([&] {
  4538. svr.stop();
  4539. listen_thread.join();
  4540. ASSERT_FALSE(svr.is_running());
  4541. });
  4542. svr.wait_until_ready();
  4543. {
  4544. Client cli(HOST, port);
  4545. cli.set_read_timeout(5, 0);
  4546. EXPECT_FALSE(cli.Get("/throw"));
  4547. }
  4548. EXPECT_TRUE(svr.is_running());
  4549. EXPECT_EQ(1, reported.load());
  4550. // A request on a fresh connection is still served.
  4551. {
  4552. Client cli(HOST, port);
  4553. auto res = cli.Get("/ok");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("ok", res->body);
  4557. }
  4558. }
  4559. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4560. Server svr;
  4561. svr.new_task_queue = [] { return new ThreadPool(1); };
  4562. std::atomic<bool> should_throw{true};
  4563. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4564. res.set_content("hi", "text/plain");
  4565. });
  4566. svr.set_post_routing_handler(
  4567. [&](const Request & /*req*/, Response & /*res*/) {
  4568. if (should_throw) {
  4569. throw std::runtime_error("from the post-routing handler");
  4570. }
  4571. });
  4572. auto port = svr.bind_to_any_port(HOST);
  4573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4574. auto se = detail::scope_exit([&] {
  4575. svr.stop();
  4576. listen_thread.join();
  4577. ASSERT_FALSE(svr.is_running());
  4578. });
  4579. svr.wait_until_ready();
  4580. {
  4581. Client cli(HOST, port);
  4582. cli.set_read_timeout(5, 0);
  4583. EXPECT_FALSE(cli.Get("/hi"));
  4584. }
  4585. EXPECT_TRUE(svr.is_running());
  4586. should_throw = false;
  4587. {
  4588. Client cli(HOST, port);
  4589. auto res = cli.Get("/hi");
  4590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("hi", res->body);
  4593. }
  4594. }
  4595. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4596. // The guard reports the caught exception through the error logger, which is
  4597. // a user callback too. A logger that throws has to be contained as well, or
  4598. // the process would terminate from inside the catch.
  4599. Server svr;
  4600. svr.new_task_queue = [] { return new ThreadPool(1); };
  4601. std::atomic<int> reported{0};
  4602. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4603. if (err == Error::UserCallbackException) {
  4604. reported++;
  4605. throw std::runtime_error("from the error logger");
  4606. }
  4607. });
  4608. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4609. res.set_content_provider(
  4610. 1024, "text/plain",
  4611. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4612. sink.write("hello", 5);
  4613. throw std::runtime_error("from the content provider");
  4614. });
  4615. });
  4616. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4617. res.set_content("ok", "text/plain");
  4618. });
  4619. auto port = svr.bind_to_any_port(HOST);
  4620. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4621. auto se = detail::scope_exit([&] {
  4622. svr.stop();
  4623. listen_thread.join();
  4624. ASSERT_FALSE(svr.is_running());
  4625. });
  4626. svr.wait_until_ready();
  4627. {
  4628. Client cli(HOST, port);
  4629. cli.set_read_timeout(5, 0);
  4630. EXPECT_FALSE(cli.Get("/throw"));
  4631. }
  4632. EXPECT_TRUE(svr.is_running());
  4633. EXPECT_EQ(1, reported.load());
  4634. {
  4635. Client cli(HOST, port);
  4636. auto res = cli.Get("/ok");
  4637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("ok", res->body);
  4640. }
  4641. }
  4642. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4643. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4644. // so the exception unwinds through the ws::WebSocket object on its way to
  4645. // the guard. None of the HTTP cases above cross that.
  4646. Server svr;
  4647. svr.new_task_queue = [] { return new ThreadPool(1); };
  4648. std::atomic<int> reported{0};
  4649. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4650. if (err == Error::UserCallbackException) { reported++; }
  4651. });
  4652. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4653. throw std::runtime_error("from the WebSocket handler");
  4654. });
  4655. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4656. res.set_content("ok", "text/plain");
  4657. });
  4658. auto port = svr.bind_to_any_port(HOST);
  4659. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. listen_thread.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. {
  4667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4668. "/ws");
  4669. auto res = client.connect();
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. // The server dropped the connection instead of dying.
  4672. std::string msg;
  4673. EXPECT_FALSE(client.read(msg));
  4674. client.close();
  4675. }
  4676. EXPECT_TRUE(svr.is_running());
  4677. EXPECT_EQ(1, reported.load());
  4678. {
  4679. Client cli(HOST, port);
  4680. auto res = cli.Get("/ok");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::OK_200, res->status);
  4683. EXPECT_EQ("ok", res->body);
  4684. }
  4685. }
  4686. #ifdef CPPHTTPLIB_SSL_ENABLED
  4687. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4688. // SSLServer::process_and_close_socket() is a separate overload with its own
  4689. // guard, so it is exercised on its own.
  4690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4691. ASSERT_TRUE(svr.is_valid());
  4692. svr.new_task_queue = [] { return new ThreadPool(1); };
  4693. std::atomic<int> reported{0};
  4694. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4695. if (err == Error::UserCallbackException) { reported++; }
  4696. });
  4697. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4698. res.set_content_provider(
  4699. 1024, "text/plain",
  4700. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4701. sink.write("hello", 5);
  4702. throw std::runtime_error("from the content provider");
  4703. });
  4704. });
  4705. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. auto port = svr.bind_to_any_port(HOST);
  4709. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. listen_thread.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. {
  4717. SSLClient cli(HOST, port);
  4718. cli.enable_server_certificate_verification(false);
  4719. cli.set_read_timeout(5, 0);
  4720. EXPECT_FALSE(cli.Get("/throw"));
  4721. }
  4722. EXPECT_TRUE(svr.is_running());
  4723. EXPECT_EQ(1, reported.load());
  4724. {
  4725. SSLClient cli(HOST, port);
  4726. cli.enable_server_certificate_verification(false);
  4727. auto res = cli.Get("/ok");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("ok", res->body);
  4731. }
  4732. }
  4733. #endif
  4734. #endif
  4735. TEST(NoContentTest, ContentLength) {
  4736. Server svr;
  4737. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4738. res.status = StatusCode::NoContent_204;
  4739. });
  4740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4741. auto se = detail::scope_exit([&] {
  4742. svr.stop();
  4743. thread.join();
  4744. ASSERT_FALSE(svr.is_running());
  4745. });
  4746. svr.wait_until_ready();
  4747. {
  4748. Client cli(HOST, PORT);
  4749. auto res = cli.Get("/hi");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4752. // RFC 9110 8.6: none in a 204 response
  4753. EXPECT_FALSE(res->has_header("Content-Length"));
  4754. }
  4755. }
  4756. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4757. Server svr;
  4758. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4759. res.set_header("Content-Length", "5");
  4760. res.set_content("hello world", "text/plain");
  4761. });
  4762. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4763. // A body that reads as the last chunk, were it taken as chunked
  4764. res.set_header("Transfer-Encoding", "chunked");
  4765. res.set_content("0\r\n\r\n", "text/plain");
  4766. });
  4767. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4768. res.set_header("Content-Length", "2");
  4769. res.set_content_provider(5, "text/plain",
  4770. [](size_t offset, size_t length, DataSink &sink) {
  4771. sink.write(&"hello"[offset], length);
  4772. return true;
  4773. });
  4774. });
  4775. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4776. res.set_header("Content-Length", "1234");
  4777. });
  4778. thread t = thread([&] { svr.listen(HOST, PORT); });
  4779. auto se = detail::scope_exit([&] {
  4780. svr.stop();
  4781. t.join();
  4782. ASSERT_FALSE(svr.is_running());
  4783. });
  4784. svr.wait_until_ready();
  4785. Client cli(HOST, PORT);
  4786. cli.set_read_timeout(1, 0);
  4787. auto expect_body = [&](const Result &res, const std::string &body) {
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(body, res->body);
  4790. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4791. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4792. };
  4793. Headers identity{{"Accept-Encoding", ""}};
  4794. expect_body(cli.Get("/body", identity), "hello world");
  4795. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4796. expect_body(cli.Get("/body",
  4797. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4798. "he");
  4799. expect_body(cli.Get("/provider", identity), "hello");
  4800. expect_body(cli.Get("/empty", identity), "");
  4801. // A HEAD response may give the length of the body a GET would get.
  4802. auto res = cli.Head("/empty");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4805. }
  4806. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4807. Server svr;
  4808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4809. res.set_content("short", "text/plain");
  4810. });
  4811. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4812. res.body += " with a footer";
  4813. res.set_header("Transfer-Encoding", "chunked");
  4814. });
  4815. thread t = thread([&] { svr.listen(HOST, PORT); });
  4816. auto se = detail::scope_exit([&] {
  4817. svr.stop();
  4818. t.join();
  4819. ASSERT_FALSE(svr.is_running());
  4820. });
  4821. svr.wait_until_ready();
  4822. Client cli(HOST, PORT);
  4823. cli.set_read_timeout(1, 0);
  4824. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("short with a footer", res->body);
  4827. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4828. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4829. }
  4830. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4831. Server svr;
  4832. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4833. res.set_header("Content-Length", "3");
  4834. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4835. sink.write("abc", 3);
  4836. sink.done();
  4837. return true;
  4838. });
  4839. });
  4840. thread t = thread([&] { svr.listen(HOST, PORT); });
  4841. auto se = detail::scope_exit([&] {
  4842. svr.stop();
  4843. t.join();
  4844. ASSERT_FALSE(svr.is_running());
  4845. });
  4846. svr.wait_until_ready();
  4847. Client cli(HOST, PORT);
  4848. cli.set_keep_alive(true);
  4849. auto res = cli.Get("/");
  4850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4851. EXPECT_EQ("abc", res->body);
  4852. EXPECT_FALSE(res->has_header("Content-Length"));
  4853. EXPECT_EQ("close", res->get_header_value("Connection"));
  4854. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4855. // No body to delimit
  4856. auto head = cli.Head("/");
  4857. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4858. EXPECT_FALSE(head->has_header("Connection"));
  4859. }
  4860. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4861. #ifdef CPPHTTPLIB_SSL_ENABLED
  4862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4863. ASSERT_TRUE(svr.is_valid());
  4864. #else
  4865. Server svr;
  4866. #endif
  4867. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4868. if (req.path == "/routing_handler") {
  4869. res.set_header("PRE_ROUTING", "on");
  4870. res.set_content("Routing Handler", "text/plain");
  4871. return httplib::Server::HandlerResponse::Handled;
  4872. }
  4873. return httplib::Server::HandlerResponse::Unhandled;
  4874. });
  4875. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4876. res.set_content("Error", "text/html");
  4877. });
  4878. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4879. if (req.path == "/routing_handler") {
  4880. res.set_header("POST_ROUTING", "on");
  4881. }
  4882. });
  4883. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4884. res.set_content("Hello World!\n", "text/plain");
  4885. });
  4886. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4887. auto se = detail::scope_exit([&] {
  4888. svr.stop();
  4889. thread.join();
  4890. ASSERT_FALSE(svr.is_running());
  4891. });
  4892. svr.wait_until_ready();
  4893. {
  4894. #ifdef CPPHTTPLIB_SSL_ENABLED
  4895. SSLClient cli(HOST, PORT);
  4896. cli.enable_server_certificate_verification(false);
  4897. #else
  4898. Client cli(HOST, PORT);
  4899. #endif
  4900. auto res = cli.Get("/routing_handler");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. EXPECT_EQ(StatusCode::OK_200, res->status);
  4903. EXPECT_EQ("Routing Handler", res->body);
  4904. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4905. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4906. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4907. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4908. }
  4909. {
  4910. #ifdef CPPHTTPLIB_SSL_ENABLED
  4911. SSLClient cli(HOST, PORT);
  4912. cli.enable_server_certificate_verification(false);
  4913. #else
  4914. Client cli(HOST, PORT);
  4915. #endif
  4916. auto res = cli.Get("/hi");
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("Hello World!\n", res->body);
  4920. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4921. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4922. }
  4923. {
  4924. #ifdef CPPHTTPLIB_SSL_ENABLED
  4925. SSLClient cli(HOST, PORT);
  4926. cli.enable_server_certificate_verification(false);
  4927. #else
  4928. Client cli(HOST, PORT);
  4929. #endif
  4930. auto res = cli.Get("/aaa");
  4931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4933. EXPECT_EQ("Error", res->body);
  4934. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4935. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4936. }
  4937. }
  4938. TEST(RequestHandlerTest, PreRequestHandler) {
  4939. auto route_path = "/user/:user";
  4940. Server svr;
  4941. svr.Get("/hi", [](const Request &, Response &res) {
  4942. res.set_content("hi", "text/plain");
  4943. });
  4944. svr.Get(route_path, [](const Request &req, Response &res) {
  4945. res.set_content(req.path_params.at("user"), "text/plain");
  4946. });
  4947. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4948. if (req.matched_route == route_path) {
  4949. auto user = req.path_params.at("user");
  4950. if (user != "john") {
  4951. res.status = StatusCode::Forbidden_403;
  4952. res.set_content("error", "text/html");
  4953. return Server::HandlerResponse::Handled;
  4954. }
  4955. }
  4956. return Server::HandlerResponse::Unhandled;
  4957. });
  4958. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4959. auto se = detail::scope_exit([&] {
  4960. svr.stop();
  4961. thread.join();
  4962. ASSERT_FALSE(svr.is_running());
  4963. });
  4964. svr.wait_until_ready();
  4965. Client cli(HOST, PORT);
  4966. {
  4967. auto res = cli.Get("/hi");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("hi", res->body);
  4971. }
  4972. {
  4973. auto res = cli.Get("/user/john");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("john", res->body);
  4977. }
  4978. {
  4979. auto res = cli.Get("/user/invalid-user");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4982. EXPECT_EQ("error", res->body);
  4983. }
  4984. }
  4985. // The pre-request handler must run before the request body is read, so a
  4986. // rejected request never forces the server to buffer a (potentially large)
  4987. // body. Here the posted body is larger than the payload limit: if the body
  4988. // were read first the server would answer 413, but because the pre-request
  4989. // handler runs first it answers 403 and the body is never read.
  4990. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4991. Server svr;
  4992. svr.set_payload_max_length(8);
  4993. auto handler_ran = false;
  4994. svr.Post("/reject", [&](const Request &req, Response &res) {
  4995. handler_ran = true;
  4996. res.set_content(req.body, "text/plain");
  4997. });
  4998. svr.Post("/accept", [](const Request &req, Response &res) {
  4999. res.set_content(req.body, "text/plain");
  5000. });
  5001. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5002. if (req.matched_route == "/reject") {
  5003. res.status = StatusCode::Forbidden_403;
  5004. res.set_content("denied", "text/plain");
  5005. return Server::HandlerResponse::Handled;
  5006. }
  5007. return Server::HandlerResponse::Unhandled;
  5008. });
  5009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5010. auto se = detail::scope_exit([&] {
  5011. svr.stop();
  5012. thread.join();
  5013. ASSERT_FALSE(svr.is_running());
  5014. });
  5015. svr.wait_until_ready();
  5016. Client cli(HOST, PORT);
  5017. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5018. // rejects with 403 before the body is read, so 413 is never reached.
  5019. {
  5020. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5023. EXPECT_EQ("denied", res->body);
  5024. EXPECT_FALSE(handler_ran);
  5025. }
  5026. // An approved route still reads the body and enforces the payload limit.
  5027. {
  5028. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5030. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5031. }
  5032. }
  5033. TEST(UserDataTest, BasicOperations) {
  5034. httplib::UserData ud;
  5035. // Initially empty
  5036. EXPECT_FALSE(ud.has("key"));
  5037. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5038. // set and get
  5039. ud.set("key", 42);
  5040. EXPECT_TRUE(ud.has("key"));
  5041. auto *p = ud.get<int>("key");
  5042. ASSERT_NE(nullptr, p);
  5043. EXPECT_EQ(42, *p);
  5044. // Type mismatch → nullptr
  5045. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5046. // Overwrite with different type
  5047. ud.set("key", std::string("hello"));
  5048. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5049. auto *s = ud.get<std::string>("key");
  5050. ASSERT_NE(nullptr, s);
  5051. EXPECT_EQ("hello", *s);
  5052. // erase
  5053. ud.erase("key");
  5054. EXPECT_FALSE(ud.has("key"));
  5055. // clear
  5056. ud.set("a", 1);
  5057. ud.set("b", 2);
  5058. ud.clear();
  5059. EXPECT_FALSE(ud.has("a"));
  5060. EXPECT_FALSE(ud.has("b"));
  5061. }
  5062. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5063. struct AuthCtx {
  5064. std::string user_id;
  5065. };
  5066. Server svr;
  5067. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5068. res.user_data.set("auth", AuthCtx{"alice"});
  5069. return Server::HandlerResponse::Unhandled;
  5070. });
  5071. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5072. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5073. ASSERT_NE(nullptr, ctx);
  5074. res.set_content("Hello " + ctx->user_id, "text/plain");
  5075. });
  5076. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5077. auto se = detail::scope_exit([&] {
  5078. svr.stop();
  5079. thread.join();
  5080. ASSERT_FALSE(svr.is_running());
  5081. });
  5082. svr.wait_until_ready();
  5083. Client cli(HOST, PORT);
  5084. auto res = cli.Get("/me");
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ("Hello alice", res->body);
  5088. }
  5089. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5090. struct RoleCtx {
  5091. std::string role;
  5092. };
  5093. Server svr;
  5094. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5095. res.user_data.set("role", RoleCtx{"admin"});
  5096. return Server::HandlerResponse::Unhandled;
  5097. });
  5098. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5099. auto *ctx = res.user_data.get<RoleCtx>("role");
  5100. ASSERT_NE(nullptr, ctx);
  5101. res.set_content(ctx->role, "text/plain");
  5102. });
  5103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. thread.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. Client cli(HOST, PORT);
  5111. auto res = cli.Get("/role");
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::OK_200, res->status);
  5114. EXPECT_EQ("admin", res->body);
  5115. }
  5116. TEST(InvalidFormatTest, StatusCode) {
  5117. Server svr;
  5118. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5119. res.set_content("Hello World!\n", "text/plain");
  5120. res.status = 9999; // Status should be a three-digit code...
  5121. });
  5122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5123. auto se = detail::scope_exit([&] {
  5124. svr.stop();
  5125. thread.join();
  5126. ASSERT_FALSE(svr.is_running());
  5127. });
  5128. svr.wait_until_ready();
  5129. {
  5130. Client cli(HOST, PORT);
  5131. auto res = cli.Get("/hi");
  5132. ASSERT_FALSE(res);
  5133. }
  5134. }
  5135. TEST(URLFragmentTest, WithFragment) {
  5136. Server svr;
  5137. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5138. EXPECT_TRUE(req.target == "/hi");
  5139. });
  5140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5141. auto se = detail::scope_exit([&] {
  5142. svr.stop();
  5143. thread.join();
  5144. ASSERT_FALSE(svr.is_running());
  5145. });
  5146. svr.wait_until_ready();
  5147. {
  5148. Client cli(HOST, PORT);
  5149. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5150. EXPECT_TRUE(res);
  5151. EXPECT_EQ(StatusCode::OK_200, res->status);
  5152. res = cli.Get("/hi%23key1=val1=key2=val2");
  5153. EXPECT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5158. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5159. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5160. Server svr;
  5161. std::vector<std::string> targets;
  5162. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5163. targets.push_back(req.target);
  5164. });
  5165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5166. auto se = detail::scope_exit([&] {
  5167. svr.stop();
  5168. thread.join();
  5169. ASSERT_FALSE(svr.is_running());
  5170. });
  5171. svr.wait_until_ready();
  5172. Client cli(HOST, PORT);
  5173. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5175. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5176. // A '?' after the '#' belongs to the fragment, not to the query.
  5177. Request req;
  5178. req.method = "GET";
  5179. req.path = "/hi#f?x=1";
  5180. req.params.emplace("a", "1");
  5181. Response res;
  5182. auto error = Error::Success;
  5183. EXPECT_TRUE(cli.send(req, res, error));
  5184. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5185. "/hi?a=1"}),
  5186. targets);
  5187. }
  5188. TEST(HeaderWriter, SetHeaderWriter) {
  5189. Server svr;
  5190. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5191. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5192. return detail::write_headers(strm, hdrs);
  5193. });
  5194. svr.Get("/hi", [](const Request &req, Response &res) {
  5195. auto it = req.headers.find("CustomClientHeader");
  5196. EXPECT_TRUE(it != req.headers.end());
  5197. EXPECT_EQ(it->second, "CustomClientValue");
  5198. res.set_content("Hello World!\n", "text/plain");
  5199. });
  5200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5201. auto se = detail::scope_exit([&] {
  5202. svr.stop();
  5203. thread.join();
  5204. ASSERT_FALSE(svr.is_running());
  5205. });
  5206. svr.wait_until_ready();
  5207. {
  5208. Client cli(HOST, PORT);
  5209. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5210. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5211. return detail::write_headers(strm, hdrs);
  5212. });
  5213. auto res = cli.Get("/hi");
  5214. EXPECT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. auto it = res->headers.find("CustomServerHeader");
  5217. EXPECT_TRUE(it != res->headers.end());
  5218. EXPECT_EQ(it->second, "CustomServerValue");
  5219. }
  5220. }
  5221. class ServerTest : public ::testing::Test {
  5222. protected:
  5223. ServerTest()
  5224. : cli_(HOST, PORT)
  5225. #ifdef CPPHTTPLIB_SSL_ENABLED
  5226. ,
  5227. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5228. #endif
  5229. {
  5230. #ifdef CPPHTTPLIB_SSL_ENABLED
  5231. cli_.enable_server_certificate_verification(false);
  5232. #endif
  5233. // Allow LARGE_DATA (100MB) responses
  5234. cli_.set_payload_max_length(200 * 1024 * 1024);
  5235. }
  5236. virtual void SetUp() {
  5237. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5238. svr_.set_payload_max_length(200 * 1024 * 1024);
  5239. svr_.set_mount_point("/", "./www");
  5240. svr_.set_mount_point("/mount", "./www2");
  5241. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5242. svr_.Get("/hi",
  5243. [&](const Request & /*req*/, Response &res) {
  5244. res.set_content("Hello World!", "text/plain");
  5245. })
  5246. .Get("/file_content",
  5247. [&](const Request & /*req*/, Response &res) {
  5248. res.set_file_content("./www/dir/test.html");
  5249. })
  5250. .Get("/file_content_with_content_type",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_file_content("./www/file", "text/plain");
  5253. })
  5254. .Get("/invalid_file_content",
  5255. [&](const Request & /*req*/, Response &res) {
  5256. res.set_file_content("./www/dir/invalid_file_path");
  5257. })
  5258. .Get("/http_response_splitting",
  5259. [&](const Request & /*req*/, Response &res) {
  5260. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5261. EXPECT_EQ(0U, res.headers.size());
  5262. EXPECT_FALSE(res.has_header("a"));
  5263. res.set_header("a", "1\nSet-Cookie: a=1");
  5264. EXPECT_EQ(0U, res.headers.size());
  5265. EXPECT_FALSE(res.has_header("a"));
  5266. res.set_header("a", "1\rSet-Cookie: a=1");
  5267. EXPECT_EQ(0U, res.headers.size());
  5268. EXPECT_FALSE(res.has_header("a"));
  5269. res.set_header("a\r\nb", "0");
  5270. EXPECT_EQ(0U, res.headers.size());
  5271. EXPECT_FALSE(res.has_header("a"));
  5272. res.set_header("a\rb", "0");
  5273. EXPECT_EQ(0U, res.headers.size());
  5274. EXPECT_FALSE(res.has_header("a"));
  5275. res.set_header("a\nb", "0");
  5276. EXPECT_EQ(0U, res.headers.size());
  5277. EXPECT_FALSE(res.has_header("a"));
  5278. res.set_redirect("1\r\nSet-Cookie: a=1");
  5279. EXPECT_EQ(0U, res.headers.size());
  5280. EXPECT_FALSE(res.has_header("Location"));
  5281. })
  5282. .Get("/slow",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. std::this_thread::sleep_for(std::chrono::seconds(4));
  5285. res.set_content("slow", "text/plain");
  5286. })
  5287. #if 0
  5288. .Post("/slowpost",
  5289. [&](const Request & /*req*/, Response &res) {
  5290. std::this_thread::sleep_for(std::chrono::seconds(2));
  5291. res.set_content("slow", "text/plain");
  5292. })
  5293. #endif
  5294. .Get("/remote_addr",
  5295. [&](const Request &req, Response &res) {
  5296. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5297. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5301. #endif
  5302. res.set_content(req.remote_addr, "text/plain");
  5303. })
  5304. .Get("/local_addr",
  5305. [&](const Request &req, Response &res) {
  5306. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5307. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5308. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5311. #endif
  5312. auto local_addr = req.local_addr;
  5313. auto local_port = std::to_string(req.local_port);
  5314. res.set_content(local_addr.append(":").append(local_port),
  5315. "text/plain");
  5316. })
  5317. .Get("/endwith%",
  5318. [&](const Request & /*req*/, Response &res) {
  5319. res.set_content("Hello World!", "text/plain");
  5320. })
  5321. .Get("/a\\+\\+b",
  5322. [&](const Request &req, Response &res) {
  5323. ASSERT_TRUE(req.has_param("a +b"));
  5324. auto val = req.get_param_value("a +b");
  5325. res.set_content(val, "text/plain");
  5326. })
  5327. .Get("/", [&](const Request & /*req*/,
  5328. Response &res) { res.set_redirect("/hi"); })
  5329. .Post("/1",
  5330. [](const Request & /*req*/, Response &res) {
  5331. res.set_redirect("/2", StatusCode::SeeOther_303);
  5332. })
  5333. .Get("/2",
  5334. [](const Request & /*req*/, Response &res) {
  5335. res.set_content("redirected.", "text/plain");
  5336. res.status = StatusCode::OK_200;
  5337. })
  5338. .Post("/person",
  5339. [&](const Request &req, Response &res) {
  5340. if (req.has_param("name") && req.has_param("note")) {
  5341. persons_[req.get_param_value("name")] =
  5342. req.get_param_value("note");
  5343. } else {
  5344. res.status = StatusCode::BadRequest_400;
  5345. }
  5346. })
  5347. .Put("/person",
  5348. [&](const Request &req, Response &res) {
  5349. if (req.has_param("name") && req.has_param("note")) {
  5350. persons_[req.get_param_value("name")] =
  5351. req.get_param_value("note");
  5352. } else {
  5353. res.status = StatusCode::BadRequest_400;
  5354. }
  5355. })
  5356. .Get("/person/(.*)",
  5357. [&](const Request &req, Response &res) {
  5358. string name = req.matches[1];
  5359. if (persons_.find(name) != persons_.end()) {
  5360. auto note = persons_[name];
  5361. res.set_content(note, "text/plain");
  5362. } else {
  5363. res.status = StatusCode::NotFound_404;
  5364. }
  5365. })
  5366. .Delete("/person",
  5367. [&](const Request &req, Response &res) {
  5368. if (req.has_param("name")) {
  5369. string name = req.get_param_value("name");
  5370. if (persons_.find(name) != persons_.end()) {
  5371. persons_.erase(name);
  5372. res.set_content("DELETED", "text/plain");
  5373. } else {
  5374. res.status = StatusCode::NotFound_404;
  5375. }
  5376. } else {
  5377. res.status = StatusCode::BadRequest_400;
  5378. }
  5379. })
  5380. .Post("/x-www-form-urlencoded-json",
  5381. [&](const Request &req, Response &res) {
  5382. auto json = req.get_param_value("json");
  5383. ASSERT_EQ(JSON_DATA, json);
  5384. res.set_content(json, "appliation/json");
  5385. res.status = StatusCode::OK_200;
  5386. })
  5387. .Get("/streamed-chunked",
  5388. [&](const Request & /*req*/, Response &res) {
  5389. res.set_chunked_content_provider(
  5390. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5391. sink.os << "123";
  5392. sink.os << "456";
  5393. sink.os << "789";
  5394. sink.done();
  5395. return true;
  5396. });
  5397. })
  5398. .Get("/streamed-chunked-with-prohibited-trailer",
  5399. [&](const Request & /*req*/, Response &res) {
  5400. auto i = new int(0);
  5401. // Declare both a prohibited trailer (Content-Length) and an
  5402. // allowed one
  5403. res.set_header("Trailer", "Content-Length, X-Allowed");
  5404. res.set_chunked_content_provider(
  5405. "text/plain",
  5406. [i](size_t /*offset*/, DataSink &sink) {
  5407. switch (*i) {
  5408. case 0: sink.os << "123"; break;
  5409. case 1: sink.os << "456"; break;
  5410. case 2: sink.os << "789"; break;
  5411. case 3: {
  5412. sink.done_with_trailer(
  5413. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5414. } break;
  5415. }
  5416. (*i)++;
  5417. return true;
  5418. },
  5419. [i](bool success) {
  5420. EXPECT_TRUE(success);
  5421. delete i;
  5422. });
  5423. })
  5424. .Get("/streamed-chunked2",
  5425. [&](const Request & /*req*/, Response &res) {
  5426. auto i = new int(0);
  5427. res.set_chunked_content_provider(
  5428. "text/plain",
  5429. [i](size_t /*offset*/, DataSink &sink) {
  5430. switch (*i) {
  5431. case 0: sink.os << "123"; break;
  5432. case 1: sink.os << "456"; break;
  5433. case 2: sink.os << "789"; break;
  5434. case 3: sink.done(); break;
  5435. }
  5436. (*i)++;
  5437. return true;
  5438. },
  5439. [i](bool success) {
  5440. EXPECT_TRUE(success);
  5441. delete i;
  5442. });
  5443. })
  5444. .Get("/streamed-chunked-with-trailer",
  5445. [&](const Request & /*req*/, Response &res) {
  5446. auto i = new int(0);
  5447. res.set_header("Trailer", "Dummy1, Dummy2");
  5448. res.set_chunked_content_provider(
  5449. "text/plain",
  5450. [i](size_t /*offset*/, DataSink &sink) {
  5451. switch (*i) {
  5452. case 0: sink.os << "123"; break;
  5453. case 1: sink.os << "456"; break;
  5454. case 2: sink.os << "789"; break;
  5455. case 3: {
  5456. sink.done_with_trailer(
  5457. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5458. } break;
  5459. }
  5460. (*i)++;
  5461. return true;
  5462. },
  5463. [i](bool success) {
  5464. EXPECT_TRUE(success);
  5465. delete i;
  5466. });
  5467. })
  5468. .Get("/streamed",
  5469. [&](const Request & /*req*/, Response &res) {
  5470. res.set_content_provider(
  5471. 6, "text/plain",
  5472. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5473. sink.os << (offset < 3 ? "a" : "b");
  5474. return true;
  5475. });
  5476. })
  5477. .Get("/streamed-without-length",
  5478. [&](const Request & /*req*/, Response &res) {
  5479. auto data = new std::string("abcdefg");
  5480. res.set_content_provider(
  5481. "text/plain",
  5482. [data](size_t offset, DataSink &sink) {
  5483. if (offset < data->size()) {
  5484. sink.os << data->substr(offset);
  5485. }
  5486. sink.done();
  5487. return true;
  5488. },
  5489. [data](bool success) {
  5490. EXPECT_TRUE(success);
  5491. delete data;
  5492. });
  5493. })
  5494. .Get("/streamed-with-range",
  5495. [&](const Request &req, Response &res) {
  5496. auto data = new std::string("abcdefg");
  5497. // An explicit status keeps the server from picking the 206 it
  5498. // would otherwise choose for a ranged request, so the response
  5499. // is not a partial representation.
  5500. auto status = req.get_param_value("status");
  5501. if (status == "200") {
  5502. res.status = StatusCode::OK_200;
  5503. } else if (status == "403") {
  5504. res.status = StatusCode::Forbidden_403;
  5505. }
  5506. res.set_content_provider(
  5507. data->size(), "text/plain",
  5508. [data](size_t offset, size_t length, DataSink &sink) {
  5509. size_t DATA_CHUNK_SIZE = 4;
  5510. const auto &d = *data;
  5511. auto out_len =
  5512. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5513. auto ret =
  5514. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5515. EXPECT_TRUE(ret);
  5516. return true;
  5517. },
  5518. [data, &req](bool success) {
  5519. EXPECT_EQ(success, !req.has_param("error"));
  5520. delete data;
  5521. });
  5522. })
  5523. .Get("/streamed-cancel",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_content_provider(
  5526. size_t(-1), "text/plain",
  5527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5528. sink.os << "data_chunk";
  5529. return true;
  5530. });
  5531. })
  5532. .Get("/regex-with-delimiter",
  5533. [&](const Request &req, Response & /*res*/) {
  5534. ASSERT_TRUE(req.has_param("key"));
  5535. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5536. })
  5537. .Get("/with-range",
  5538. [&](const Request & /*req*/, Response &res) {
  5539. res.set_content("abcdefg", "text/plain");
  5540. })
  5541. .Get("/test-start-time",
  5542. [&](const Request &req, Response & /*res*/) {
  5543. EXPECT_NE(req.start_time_,
  5544. std::chrono::steady_clock::time_point::min());
  5545. })
  5546. .Get("/with-range-customized-response",
  5547. [&](const Request & /*req*/, Response &res) {
  5548. res.status = StatusCode::BadRequest_400;
  5549. res.set_content(JSON_DATA, "application/json");
  5550. })
  5551. .Post("/chunked",
  5552. [&](const Request &req, Response & /*res*/) {
  5553. EXPECT_EQ(req.body, "dechunked post body");
  5554. })
  5555. .Post("/large-chunked",
  5556. [&](const Request &req, Response & /*res*/) {
  5557. std::string expected(6 * 30 * 1024u, 'a');
  5558. EXPECT_EQ(req.body, expected);
  5559. })
  5560. .Post("/multipart",
  5561. [&](const Request &req, Response & /*res*/) {
  5562. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5563. req.form.get_field_count("text2") +
  5564. req.form.get_field_count("file3") +
  5565. req.form.get_field_count("file4"));
  5566. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5567. req.form.get_file_count("file2"));
  5568. ASSERT_TRUE(!req.form.has_file("???"));
  5569. ASSERT_TRUE(!req.form.has_field("???"));
  5570. ASSERT_TRUE(req.body.empty());
  5571. {
  5572. const auto &text = req.form.get_field("text1");
  5573. EXPECT_EQ("text default", text);
  5574. }
  5575. {
  5576. const auto &text = req.form.get_field("text2");
  5577. EXPECT_EQ("aωb", text);
  5578. }
  5579. {
  5580. const auto &file = req.form.get_file("file1");
  5581. EXPECT_EQ("hello.txt", file.filename);
  5582. EXPECT_EQ("text/plain", file.content_type);
  5583. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5584. }
  5585. {
  5586. const auto &file = req.form.get_file("file2");
  5587. EXPECT_EQ("world.json", file.filename);
  5588. EXPECT_EQ("application/json", file.content_type);
  5589. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5590. }
  5591. {
  5592. const auto &text = req.form.get_field("file3");
  5593. EXPECT_EQ(0u, text.size());
  5594. }
  5595. {
  5596. const auto &text = req.form.get_field("file4");
  5597. EXPECT_EQ(0u, text.size());
  5598. }
  5599. })
  5600. .Post("/multipart/multi_file_values",
  5601. [&](const Request &req, Response & /*res*/) {
  5602. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5603. req.form.get_field_count("multi_text1"));
  5604. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5605. ASSERT_TRUE(!req.form.has_file("???"));
  5606. ASSERT_TRUE(!req.form.has_field("???"));
  5607. ASSERT_TRUE(req.body.empty());
  5608. {
  5609. const auto &text = req.form.get_field("text");
  5610. EXPECT_EQ("default text", text);
  5611. }
  5612. {
  5613. const auto &text1_values = req.form.get_fields("multi_text1");
  5614. EXPECT_EQ(2u, text1_values.size());
  5615. EXPECT_EQ("aaaaa", text1_values[0]);
  5616. EXPECT_EQ("bbbbb", text1_values[1]);
  5617. }
  5618. {
  5619. const auto &file1_values = req.form.get_files("multi_file1");
  5620. EXPECT_EQ(2u, file1_values.size());
  5621. auto file1 = file1_values[0];
  5622. EXPECT_EQ(file1.filename, "hello.txt");
  5623. EXPECT_EQ(file1.content_type, "text/plain");
  5624. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5625. auto file2 = file1_values[1];
  5626. EXPECT_EQ(file2.filename, "world.json");
  5627. EXPECT_EQ(file2.content_type, "application/json");
  5628. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5629. }
  5630. })
  5631. .Post("/empty",
  5632. [&](const Request &req, Response &res) {
  5633. EXPECT_EQ(req.body, "");
  5634. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5636. res.set_content("empty", "text/plain");
  5637. })
  5638. .Post("/empty-no-content-type",
  5639. [&](const Request &req, Response &res) {
  5640. EXPECT_EQ(req.body, "");
  5641. EXPECT_FALSE(req.has_header("Content-Type"));
  5642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5643. res.set_content("empty-no-content-type", "text/plain");
  5644. })
  5645. .Post("/path-only",
  5646. [&](const Request &req, Response &res) {
  5647. EXPECT_EQ(req.body, "");
  5648. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5649. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5650. res.set_content("path-only", "text/plain");
  5651. })
  5652. .Post("/path-headers-only",
  5653. [&](const Request &req, Response &res) {
  5654. EXPECT_EQ(req.body, "");
  5655. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5656. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5657. EXPECT_EQ("world", req.get_header_value("hello"));
  5658. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5659. res.set_content("path-headers-only", "text/plain");
  5660. })
  5661. .Post("/post-large",
  5662. [&](const Request &req, Response &res) {
  5663. EXPECT_EQ(req.body, LARGE_DATA);
  5664. res.set_content(req.body, "text/plain");
  5665. })
  5666. .Post("/post-loopback",
  5667. [&](const Request &, Response &res,
  5668. ContentReader const &content_reader) {
  5669. std::string body;
  5670. content_reader([&](const char *data, size_t data_length) {
  5671. body.append(data, data_length);
  5672. return true;
  5673. });
  5674. res.set_content(body, "text/plain");
  5675. })
  5676. .Put("/put-loopback",
  5677. [&](const Request &, Response &res,
  5678. ContentReader const &content_reader) {
  5679. std::string body;
  5680. content_reader([&](const char *data, size_t data_length) {
  5681. body.append(data, data_length);
  5682. return true;
  5683. });
  5684. res.set_content(body, "text/plain");
  5685. })
  5686. .Patch("/patch-loopback",
  5687. [&](const Request &, Response &res,
  5688. ContentReader const &content_reader) {
  5689. std::string body;
  5690. content_reader([&](const char *data, size_t data_length) {
  5691. body.append(data, data_length);
  5692. return true;
  5693. });
  5694. res.set_content(body, "text/plain");
  5695. })
  5696. .Put("/empty-no-content-type",
  5697. [&](const Request &req, Response &res) {
  5698. EXPECT_EQ(req.body, "");
  5699. EXPECT_FALSE(req.has_header("Content-Type"));
  5700. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5701. res.set_content("empty-no-content-type", "text/plain");
  5702. })
  5703. .Put("/put",
  5704. [&](const Request &req, Response &res) {
  5705. EXPECT_EQ(req.body, "PUT");
  5706. res.set_content(req.body, "text/plain");
  5707. })
  5708. .Put("/put-large",
  5709. [&](const Request &req, Response &res) {
  5710. EXPECT_EQ(req.body, LARGE_DATA);
  5711. res.set_content(req.body, "text/plain");
  5712. })
  5713. .Patch("/patch",
  5714. [&](const Request &req, Response &res) {
  5715. EXPECT_EQ(req.body, "PATCH");
  5716. res.set_content(req.body, "text/plain");
  5717. })
  5718. .Delete("/delete",
  5719. [&](const Request & /*req*/, Response &res) {
  5720. res.set_content("DELETE", "text/plain");
  5721. })
  5722. .Delete("/delete-body",
  5723. [&](const Request &req, Response &res) {
  5724. EXPECT_EQ(req.body, "content");
  5725. res.set_content(req.body, "text/plain");
  5726. })
  5727. .Options(R"(\*)",
  5728. [&](const Request & /*req*/, Response &res) {
  5729. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5730. })
  5731. .CustomRoute("PROPFIND", "/dav/:id",
  5732. [&](const Request &req, Response &res) {
  5733. res.set_header("x-body-size",
  5734. std::to_string(req.body.size()));
  5735. res.set_header("x-matched-route", req.matched_route);
  5736. res.set_header("x-dav-id", req.path_params.at("id"));
  5737. res.status = StatusCode::MultiStatus_207;
  5738. res.set_content(req.body, "application/xml");
  5739. })
  5740. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5741. [&](const Request &req, Response &res) {
  5742. res.set_header("x-dav-match", req.matches[1]);
  5743. res.status = StatusCode::MultiStatus_207;
  5744. })
  5745. .CustomRoute("MKCOL", "/dav-mkcol",
  5746. [&](const Request &req, Response &res) {
  5747. EXPECT_TRUE(req.body.empty());
  5748. res.status = StatusCode::Created_201;
  5749. })
  5750. .CustomRoute(
  5751. "REPORT", "/dav-report",
  5752. [&](const Request & /*req*/, Response &res,
  5753. const ContentReader &content_reader) {
  5754. std::string body;
  5755. content_reader([&](const char *data, size_t data_length) {
  5756. body.append(data, data_length);
  5757. return true;
  5758. });
  5759. res.set_header("x-body-size", std::to_string(body.size()));
  5760. res.status = StatusCode::MultiStatus_207;
  5761. res.set_content(body, "application/xml");
  5762. })
  5763. .Get("/request-target",
  5764. [&](const Request &req, Response & /*res*/) {
  5765. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5766. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5767. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5768. })
  5769. .Get("/long-query-value",
  5770. [&](const Request &req, Response & /*res*/) {
  5771. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5772. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5773. })
  5774. .Get("/too-long-query-value",
  5775. [&](const Request &req, Response & /*res*/) {
  5776. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5777. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5778. })
  5779. .Get("/array-param",
  5780. [&](const Request &req, Response & /*res*/) {
  5781. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5782. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5783. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5784. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5785. })
  5786. .Get("/array-param-values",
  5787. [&](const Request &req, Response & /*res*/) {
  5788. auto values = req.get_param_values("array");
  5789. EXPECT_EQ(3u, values.size());
  5790. EXPECT_EQ("value1", values[0]);
  5791. EXPECT_EQ("value2", values[1]);
  5792. EXPECT_EQ("value3", values[2]);
  5793. auto empty = req.get_param_values("nonexistent");
  5794. EXPECT_TRUE(empty.empty());
  5795. })
  5796. .Post("/validate-no-multiple-headers",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5799. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5800. })
  5801. .Post("/content_receiver",
  5802. [&](const Request &req, Response &res,
  5803. const ContentReader &content_reader) {
  5804. if (req.is_multipart_form_data()) {
  5805. std::vector<FormData> items;
  5806. content_reader(
  5807. [&](const FormData &file) {
  5808. items.push_back(file);
  5809. return true;
  5810. },
  5811. [&](const char *data, size_t data_length) {
  5812. items.back().content.append(data, data_length);
  5813. return true;
  5814. });
  5815. EXPECT_EQ(5u, items.size());
  5816. {
  5817. const auto &file = get_file_value(items, "text1");
  5818. EXPECT_TRUE(file.filename.empty());
  5819. EXPECT_EQ("text default", file.content);
  5820. }
  5821. {
  5822. const auto &file = get_file_value(items, "text2");
  5823. EXPECT_TRUE(file.filename.empty());
  5824. EXPECT_EQ("aωb", file.content);
  5825. }
  5826. {
  5827. const auto &file = get_file_value(items, "file1");
  5828. EXPECT_EQ("hello.txt", file.filename);
  5829. EXPECT_EQ("text/plain", file.content_type);
  5830. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5831. }
  5832. {
  5833. const auto &file = get_file_value(items, "file2");
  5834. EXPECT_EQ("world.json", file.filename);
  5835. EXPECT_EQ("application/json", file.content_type);
  5836. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5837. }
  5838. {
  5839. const auto &file = get_file_value(items, "file3");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("application/octet-stream", file.content_type);
  5842. EXPECT_EQ(0u, file.content.size());
  5843. }
  5844. } else {
  5845. std::string body;
  5846. content_reader([&](const char *data, size_t data_length) {
  5847. EXPECT_EQ(7U, data_length);
  5848. body.append(data, data_length);
  5849. return true;
  5850. });
  5851. EXPECT_EQ(body, "content");
  5852. res.set_content(body, "text/plain");
  5853. }
  5854. })
  5855. .Put("/content_receiver",
  5856. [&](const Request & /*req*/, Response &res,
  5857. const ContentReader &content_reader) {
  5858. std::string body;
  5859. content_reader([&](const char *data, size_t data_length) {
  5860. body.append(data, data_length);
  5861. return true;
  5862. });
  5863. EXPECT_EQ(body, "content");
  5864. res.set_content(body, "text/plain");
  5865. })
  5866. .Patch("/content_receiver",
  5867. [&](const Request & /*req*/, Response &res,
  5868. const ContentReader &content_reader) {
  5869. std::string body;
  5870. content_reader([&](const char *data, size_t data_length) {
  5871. body.append(data, data_length);
  5872. return true;
  5873. });
  5874. EXPECT_EQ(body, "content");
  5875. res.set_content(body, "text/plain");
  5876. })
  5877. .Post("/query-string-and-body",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. ASSERT_TRUE(req.has_param("key"));
  5880. EXPECT_EQ(req.get_param_value("key"), "value");
  5881. EXPECT_EQ(req.body, "content");
  5882. })
  5883. .Get("/last-request",
  5884. [&](const Request &req, Response & /*res*/) {
  5885. EXPECT_EQ("close", req.get_header_value("Connection"));
  5886. })
  5887. .Get(R"(/redirect/(\d+))",
  5888. [&](const Request &req, Response &res) {
  5889. auto num = std::stoi(req.matches[1]) + 1;
  5890. std::string url = "/redirect/" + std::to_string(num);
  5891. res.set_redirect(url);
  5892. })
  5893. .Post("/binary",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_EQ(4U, req.body.size());
  5896. EXPECT_EQ("application/octet-stream",
  5897. req.get_header_value("Content-Type"));
  5898. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5899. res.set_content(req.body, "application/octet-stream");
  5900. })
  5901. .Put("/binary",
  5902. [&](const Request &req, Response &res) {
  5903. EXPECT_EQ(4U, req.body.size());
  5904. EXPECT_EQ("application/octet-stream",
  5905. req.get_header_value("Content-Type"));
  5906. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5907. res.set_content(req.body, "application/octet-stream");
  5908. })
  5909. .Patch("/binary",
  5910. [&](const Request &req, Response &res) {
  5911. EXPECT_EQ(4U, req.body.size());
  5912. EXPECT_EQ("application/octet-stream",
  5913. req.get_header_value("Content-Type"));
  5914. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5915. res.set_content(req.body, "application/octet-stream");
  5916. })
  5917. .Delete("/binary",
  5918. [&](const Request &req, Response &res) {
  5919. EXPECT_EQ(4U, req.body.size());
  5920. EXPECT_EQ("application/octet-stream",
  5921. req.get_header_value("Content-Type"));
  5922. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5923. res.set_content(req.body, "application/octet-stream");
  5924. })
  5925. .Get("/issue1772",
  5926. [&](const Request & /*req*/, Response &res) {
  5927. res.status = 401;
  5928. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5929. })
  5930. .Delete("/issue609",
  5931. [](const httplib::Request &, httplib::Response &res,
  5932. const httplib::ContentReader &) {
  5933. res.set_content("ok", "text/plain");
  5934. })
  5935. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5936. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5937. .Get("/compress",
  5938. [&](const Request & /*req*/, Response &res) {
  5939. res.set_content(
  5940. "12345678901234567890123456789012345678901234567890123456789"
  5941. "01234567890123456789012345678901234567890",
  5942. "text/plain");
  5943. })
  5944. .Get("/compress-with-charset",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content(
  5947. "12345678901234567890123456789012345678901234567890123456789"
  5948. "01234567890123456789012345678901234567890",
  5949. "application/json; charset=utf-8");
  5950. })
  5951. .Get("/nocompress",
  5952. [&](const Request & /*req*/, Response &res) {
  5953. res.set_content(
  5954. "12345678901234567890123456789012345678901234567890123456789"
  5955. "01234567890123456789012345678901234567890",
  5956. "application/octet-stream");
  5957. })
  5958. .Post("/compress-multipart",
  5959. [&](const Request &req, Response & /*res*/) {
  5960. EXPECT_EQ(2u, req.form.fields.size());
  5961. ASSERT_TRUE(!req.form.has_field("???"));
  5962. {
  5963. const auto &text = req.form.get_field("key1");
  5964. EXPECT_EQ("test", text);
  5965. }
  5966. {
  5967. const auto &text = req.form.get_field("key2");
  5968. EXPECT_EQ("--abcdefg123", text);
  5969. }
  5970. })
  5971. #endif
  5972. ;
  5973. persons_["john"] = "programmer";
  5974. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5975. svr_.wait_until_ready();
  5976. }
  5977. virtual void TearDown() {
  5978. svr_.stop();
  5979. if (!request_threads_.empty()) {
  5980. std::this_thread::sleep_for(std::chrono::seconds(1));
  5981. for (auto &t : request_threads_) {
  5982. t.join();
  5983. }
  5984. }
  5985. t_.join();
  5986. }
  5987. map<string, string> persons_;
  5988. #ifdef CPPHTTPLIB_SSL_ENABLED
  5989. SSLClient cli_;
  5990. SSLServer svr_;
  5991. #else
  5992. Client cli_;
  5993. Server svr_;
  5994. #endif
  5995. thread t_;
  5996. std::vector<thread> request_threads_;
  5997. };
  5998. TEST_F(ServerTest, GetMethod200) {
  5999. auto res = cli_.Get("/hi");
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ("HTTP/1.1", res->version);
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. EXPECT_EQ("OK", res->reason);
  6004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6005. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6006. EXPECT_EQ("Hello World!", res->body);
  6007. }
  6008. TEST_F(ServerTest, GetEmptyFile) {
  6009. auto res = cli_.Get("/empty_file");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6014. EXPECT_EQ("", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetFileContent) {
  6017. auto res = cli_.Get("/file_content");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6022. EXPECT_EQ("test.html", res->body);
  6023. }
  6024. TEST_F(ServerTest, GetFileContentWithRange) {
  6025. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6030. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6031. EXPECT_EQ("est", res->body);
  6032. }
  6033. TEST_F(ServerTest, GetFileContentWithContentType) {
  6034. auto res = cli_.Get("/file_content_with_content_type");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6038. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6039. EXPECT_EQ("file\n", res->body);
  6040. }
  6041. TEST_F(ServerTest, GetInvalidFileContent) {
  6042. auto res = cli_.Get("/invalid_file_content");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6045. }
  6046. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6047. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ("HTTP/1.1", res->version);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6052. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetMethod302) {
  6056. auto res = cli_.Get("/");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::Found_302, res->status);
  6059. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6060. }
  6061. TEST_F(ServerTest, GetMethod302Redirect) {
  6062. cli_.set_follow_location(true);
  6063. auto res = cli_.Get("/");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("Hello World!", res->body);
  6067. EXPECT_EQ("/hi", res->location);
  6068. }
  6069. TEST_F(ServerTest, GetMethod404) {
  6070. auto res = cli_.Get("/invalid");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, HeadMethod200) {
  6075. auto res = cli_.Head("/hi");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6079. EXPECT_TRUE(res->body.empty());
  6080. }
  6081. TEST_F(ServerTest, HeadMethod200Static) {
  6082. auto res = cli_.Head("/mount/dir/index.html");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6086. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6087. EXPECT_TRUE(res->body.empty());
  6088. }
  6089. TEST_F(ServerTest, HeadMethod404) {
  6090. auto res = cli_.Head("/invalid");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6093. EXPECT_TRUE(res->body.empty());
  6094. }
  6095. TEST_F(ServerTest, GetMethodPersonJohn) {
  6096. auto res = cli_.Get("/person/john");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::OK_200, res->status);
  6099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6100. EXPECT_EQ("programmer", res->body);
  6101. }
  6102. TEST_F(ServerTest, PostMethod1) {
  6103. auto res = cli_.Get("/person/john1");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6106. res = cli_.Post("/person", "name=john1&note=coder",
  6107. "application/x-www-form-urlencoded");
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. ASSERT_EQ(StatusCode::OK_200, res->status);
  6110. res = cli_.Get("/person/john1");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. ASSERT_EQ(StatusCode::OK_200, res->status);
  6113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6114. ASSERT_EQ("coder", res->body);
  6115. }
  6116. TEST_F(ServerTest, PostMethod2) {
  6117. auto res = cli_.Get("/person/john2");
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6120. Params params;
  6121. params.emplace("name", "john2");
  6122. params.emplace("note", "coder");
  6123. res = cli_.Post("/person", params);
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. ASSERT_EQ(StatusCode::OK_200, res->status);
  6126. res = cli_.Get("/person/john2");
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. ASSERT_EQ(StatusCode::OK_200, res->status);
  6129. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6130. ASSERT_EQ("coder", res->body);
  6131. }
  6132. TEST_F(ServerTest, PutMethod3) {
  6133. auto res = cli_.Get("/person/john3");
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6136. Params params;
  6137. params.emplace("name", "john3");
  6138. params.emplace("note", "coder");
  6139. res = cli_.Put("/person", params);
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::OK_200, res->status);
  6142. res = cli_.Get("/person/john3");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. ASSERT_EQ(StatusCode::OK_200, res->status);
  6145. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6146. ASSERT_EQ("coder", res->body);
  6147. }
  6148. TEST_F(ServerTest, DeleteMethod1) {
  6149. auto res = cli_.Get("/person/john4");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6152. Params params;
  6153. params.emplace("name", "john4");
  6154. params.emplace("note", "coder");
  6155. res = cli_.Post("/person", params);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::OK_200, res->status);
  6158. res = cli_.Get("/person/john4");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. ASSERT_EQ(StatusCode::OK_200, res->status);
  6161. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6162. ASSERT_EQ("coder", res->body);
  6163. Params delete_params;
  6164. delete_params.emplace("name", "john4");
  6165. res = cli_.Delete("/person", delete_params);
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. ASSERT_EQ(StatusCode::OK_200, res->status);
  6168. ASSERT_EQ("DELETED", res->body);
  6169. res = cli_.Get("/person/john4");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6172. }
  6173. TEST_F(ServerTest, DeleteMethod2) {
  6174. auto res = cli_.Get("/person/john5");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6177. Params params;
  6178. params.emplace("name", "john5");
  6179. params.emplace("note", "developer");
  6180. res = cli_.Post("/person", params);
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli_.Get("/person/john5");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. ASSERT_EQ("developer", res->body);
  6188. Params delete_params;
  6189. delete_params.emplace("name", "john5");
  6190. Headers headers;
  6191. headers.emplace("Custom-Header", "test-value");
  6192. res = cli_.Delete("/person", headers, delete_params);
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ("DELETED", res->body);
  6196. res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. }
  6200. TEST_F(ServerTest, DeleteMethod3) {
  6201. auto res = cli_.Get("/person/john6");
  6202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6203. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6204. Params params;
  6205. params.emplace("name", "john6");
  6206. params.emplace("note", "tester");
  6207. res = cli_.Post("/person", params);
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::OK_200, res->status);
  6210. res = cli_.Get("/person/john6");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. ASSERT_EQ(StatusCode::OK_200, res->status);
  6213. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6214. ASSERT_EQ("tester", res->body);
  6215. Params delete_params;
  6216. delete_params.emplace("name", "john6");
  6217. Headers headers;
  6218. headers.emplace("Custom-Header", "test-value");
  6219. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ("DELETED", res->body);
  6223. res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. }
  6227. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6228. Params params;
  6229. params.emplace("json", JSON_DATA);
  6230. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ(JSON_DATA, res->body);
  6234. }
  6235. TEST_F(ServerTest, PostEmptyContent) {
  6236. auto res = cli_.Post("/empty", "", "text/plain");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ("empty", res->body);
  6240. }
  6241. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6242. auto res = cli_.Post("/empty-no-content-type");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("empty-no-content-type", res->body);
  6246. }
  6247. TEST_F(ServerTest, PostPathOnly) {
  6248. auto res = cli_.Post("/path-only");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ("path-only", res->body);
  6252. }
  6253. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6254. auto res = cli_.Post("/path-headers-only",
  6255. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. ASSERT_EQ("path-headers-only", res->body);
  6259. }
  6260. TEST_F(ServerTest, PostLarge) {
  6261. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. ASSERT_EQ(StatusCode::OK_200, res->status);
  6264. EXPECT_EQ(LARGE_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6267. auto res = cli_.Put("/empty-no-content-type");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. ASSERT_EQ(StatusCode::OK_200, res->status);
  6270. ASSERT_EQ("empty-no-content-type", res->body);
  6271. }
  6272. TEST_F(ServerTest, GetMethodDir) {
  6273. auto res = cli_.Get("/dir/");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::OK_200, res->status);
  6276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6277. auto body = R"(<html>
  6278. <head>
  6279. </head>
  6280. <body>
  6281. <a href="/dir/test.html">Test</a>
  6282. <a href="/hi">hi</a>
  6283. </body>
  6284. </html>
  6285. )";
  6286. EXPECT_EQ(body, res->body);
  6287. }
  6288. TEST_F(ServerTest, GetMethodDirTest) {
  6289. auto res = cli_.Get("/dir/test.html");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6293. EXPECT_EQ("test.html", res->body);
  6294. }
  6295. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6296. auto res = cli_.Get("/dir/../dir/test.html");
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6299. }
  6300. TEST_F(ServerTest, GetMethodInvalidPath) {
  6301. auto res = cli_.Get("/dir/../test.html");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. }
  6305. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6306. auto res = cli_.Get("/../www/dir/test.html");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6309. }
  6310. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6311. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6314. }
  6315. TEST_F(ServerTest, GetMethodDirMountTest) {
  6316. auto res = cli_.Get("/mount/dir/test.html");
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6320. EXPECT_EQ("test.html", res->body);
  6321. }
  6322. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6323. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6328. auto res = cli_.Get("/mount/dir/../test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6333. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6338. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6341. }
  6342. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6343. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6346. }
  6347. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6348. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6351. }
  6352. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6353. auto res = cli_.Get("/mount/dir");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6356. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6357. }
  6358. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6359. auto res = cli_.Get("//dir");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6362. EXPECT_FALSE(res->has_header("Location"));
  6363. }
  6364. TEST_F(ServerTest, PostMethod303) {
  6365. auto res = cli_.Post("/1", "body", "text/plain");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6368. EXPECT_EQ("/2", res->get_header_value("Location"));
  6369. }
  6370. TEST_F(ServerTest, PostMethod303Redirect) {
  6371. cli_.set_follow_location(true);
  6372. auto res = cli_.Post("/1", "body", "text/plain");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. EXPECT_EQ("redirected.", res->body);
  6376. EXPECT_EQ("/2", res->location);
  6377. }
  6378. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6379. auto res = cli_.Get("/dir/test.abcde");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::OK_200, res->status);
  6382. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6383. EXPECT_EQ("abcde", res->body);
  6384. }
  6385. TEST_F(ServerTest, StaticFileRange) {
  6386. auto res =
  6387. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6390. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6391. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6392. EXPECT_EQ(true, res->has_header("Content-Range"));
  6393. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6394. EXPECT_EQ(std::string("cd"), res->body);
  6395. }
  6396. TEST_F(ServerTest, StaticFileRanges) {
  6397. auto res = cli_.Get("/dir/test.abcde",
  6398. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6401. EXPECT_TRUE(
  6402. res->get_header_value("Content-Type")
  6403. .find(
  6404. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6405. 0);
  6406. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6407. }
  6408. TEST_F(ServerTest, StaticFileRangeHead) {
  6409. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6412. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6413. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6416. }
  6417. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6418. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6422. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ(true, res->has_header("Content-Range"));
  6424. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6425. res->get_header_value("Content-Range"));
  6426. EXPECT_EQ("LAST\n", res->body);
  6427. }
  6428. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6429. auto res =
  6430. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6434. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6435. EXPECT_EQ(true, res->has_header("Content-Range"));
  6436. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6437. }
  6438. TEST_F(ServerTest, StaticFileBigFile) {
  6439. auto res = cli_.Get("/dir/1MB.txt");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6443. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6444. }
  6445. TEST_F(ServerTest, InvalidBaseDirMount) {
  6446. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6447. }
  6448. TEST_F(ServerTest, Binary) {
  6449. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6450. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6451. "application/octet-stream");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::OK_200, res->status);
  6454. ASSERT_EQ(4U, res->body.size());
  6455. res = cli_.Put("/binary", binary.data(), binary.size(),
  6456. "application/octet-stream");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. ASSERT_EQ(StatusCode::OK_200, res->status);
  6459. ASSERT_EQ(4U, res->body.size());
  6460. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6461. "application/octet-stream");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. ASSERT_EQ(StatusCode::OK_200, res->status);
  6464. ASSERT_EQ(4U, res->body.size());
  6465. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6466. "application/octet-stream");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. ASSERT_EQ(StatusCode::OK_200, res->status);
  6469. ASSERT_EQ(4U, res->body.size());
  6470. }
  6471. TEST_F(ServerTest, BinaryString) {
  6472. auto binary = std::string("\x00\x01\x02\x03", 4);
  6473. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Put("/binary", binary, "application/octet-stream");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. ASSERT_EQ(StatusCode::OK_200, res->status);
  6480. ASSERT_EQ(4U, res->body.size());
  6481. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. ASSERT_EQ(StatusCode::OK_200, res->status);
  6484. ASSERT_EQ(4U, res->body.size());
  6485. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ(4U, res->body.size());
  6489. }
  6490. TEST_F(ServerTest, EmptyRequest) {
  6491. auto res = cli_.Get("");
  6492. ASSERT_TRUE(!res);
  6493. EXPECT_EQ(Error::Connection, res.error());
  6494. }
  6495. TEST_F(ServerTest, LongRequest) {
  6496. std::string request;
  6497. for (size_t i = 0; i < 545; i++) {
  6498. request += "/TooLongRequest";
  6499. }
  6500. request += "OK";
  6501. auto res = cli_.Get(request.c_str());
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6504. }
  6505. TEST_F(ServerTest, TooLongRequest) {
  6506. std::string request;
  6507. for (size_t i = 0; i < 546; i++) {
  6508. request += "/TooLongRequest";
  6509. }
  6510. request += "_NG";
  6511. auto start = std::chrono::high_resolution_clock::now();
  6512. cli_.set_keep_alive(true);
  6513. auto res = cli_.Get(request.c_str());
  6514. auto end = std::chrono::high_resolution_clock::now();
  6515. auto elapsed =
  6516. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6517. .count();
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6520. EXPECT_LE(elapsed, 1000);
  6521. EXPECT_EQ("close", res->get_header_value("Connection"));
  6522. EXPECT_FALSE(cli_.is_socket_open());
  6523. }
  6524. TEST_F(ServerTest, AlmostTooLongRequest) {
  6525. // test for #2046 - URI length check shouldn't include other content on req
  6526. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6527. // leading /, space, HTTP/1.1)
  6528. std::string request =
  6529. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6530. auto res = cli_.Get(request.c_str());
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6533. }
  6534. TEST_F(ServerTest, LongHeader) {
  6535. Request req;
  6536. req.method = "GET";
  6537. req.path = "/hi";
  6538. std::string host_and_port;
  6539. host_and_port += HOST;
  6540. host_and_port += ":";
  6541. host_and_port += std::to_string(PORT);
  6542. req.headers.emplace("Host", host_and_port.c_str());
  6543. req.headers.emplace("Accept", "*/*");
  6544. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6545. req.headers.emplace(
  6546. "Header-Name",
  6547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@");
  6576. auto res = std::make_shared<Response>();
  6577. auto error = Error::Success;
  6578. auto ret = cli_.send(req, *res, error);
  6579. ASSERT_TRUE(ret);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. }
  6582. TEST_F(ServerTest, LongQueryValue) {
  6583. auto start = std::chrono::high_resolution_clock::now();
  6584. cli_.set_keep_alive(true);
  6585. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6586. auto end = std::chrono::high_resolution_clock::now();
  6587. auto elapsed =
  6588. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6589. .count();
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6592. EXPECT_LE(elapsed, 1000);
  6593. EXPECT_EQ("close", res->get_header_value("Connection"));
  6594. EXPECT_FALSE(cli_.is_socket_open());
  6595. }
  6596. TEST_F(ServerTest, TooLongQueryValue) {
  6597. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6598. ASSERT_FALSE(res);
  6599. EXPECT_EQ(Error::Read, res.error());
  6600. }
  6601. TEST_F(ServerTest, TooLongHeader) {
  6602. Request req;
  6603. req.method = "GET";
  6604. req.path = "/hi";
  6605. std::string host_and_port;
  6606. host_and_port += HOST;
  6607. host_and_port += ":";
  6608. host_and_port += std::to_string(PORT);
  6609. req.headers.emplace("Host", host_and_port.c_str());
  6610. req.headers.emplace("Accept", "*/*");
  6611. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6612. req.headers.emplace(
  6613. "Header-Name",
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@");
  6643. auto res = std::make_shared<Response>();
  6644. auto error = Error::Success;
  6645. auto ret = cli_.send(req, *res, error);
  6646. ASSERT_TRUE(ret);
  6647. EXPECT_EQ(StatusCode::OK_200, res->status);
  6648. }
  6649. TEST_F(ServerTest, HeaderCountAtLimit) {
  6650. // Test with headers just under the 100 limit
  6651. httplib::Headers headers;
  6652. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6653. // This should keep us just under the 100 header limit
  6654. for (int i = 0; i < 95; i++) {
  6655. std::string name = "X-Test-Header-" + std::to_string(i);
  6656. std::string value = "value" + std::to_string(i);
  6657. headers.emplace(name, value);
  6658. }
  6659. // This should work fine as we're under the limit
  6660. auto res = cli_.Get("/hi", headers);
  6661. EXPECT_TRUE(res);
  6662. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6663. }
  6664. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6665. // Test with many headers to exceed the 100 limit
  6666. httplib::Headers headers;
  6667. // Add 150 headers to definitely exceed the 100 limit
  6668. for (int i = 0; i < 150; i++) {
  6669. std::string name = "X-Test-Header-" + std::to_string(i);
  6670. std::string value = "value" + std::to_string(i);
  6671. headers.emplace(name, value);
  6672. }
  6673. // This should fail due to exceeding header count limit
  6674. cli_.set_keep_alive(true);
  6675. auto res = cli_.Get("/hi", headers);
  6676. // The server should respond with 400 Bad Request
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6679. EXPECT_EQ("close", res->get_header_value("Connection"));
  6680. EXPECT_FALSE(cli_.is_socket_open());
  6681. }
  6682. TEST_F(ServerTest, PercentEncoding) {
  6683. auto res = cli_.Get("/e%6edwith%");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, PercentEncodingUnicode) {
  6688. auto res = cli_.Get("/e%u006edwith%");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. }
  6692. TEST_F(ServerTest, InvalidPercentEncoding) {
  6693. auto res = cli_.Get("/%endwith%");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6696. }
  6697. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6698. auto res = cli_.Get("/%uendwith%");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6701. }
  6702. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6703. auto res = cli_.Get("/hello?aaa=bbb%");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6706. }
  6707. TEST_F(ServerTest, PlusSignEncoding) {
  6708. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ("a +b", res->body);
  6712. }
  6713. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6714. // This test simulates a potential DoS attack using many headers
  6715. // to verify our security fix prevents memory exhaustion
  6716. httplib::Headers attack_headers;
  6717. // Attempt to add many headers like an attacker would (200 headers to far
  6718. // exceed limit)
  6719. for (int i = 0; i < 200; i++) {
  6720. std::string name = "X-Attack-Header-" + std::to_string(i);
  6721. std::string value = "attack_payload_" + std::to_string(i);
  6722. attack_headers.emplace(name, value);
  6723. }
  6724. // Try to POST with excessive headers
  6725. cli_.set_keep_alive(true);
  6726. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6727. // Should either fail or return 400 Bad Request due to security limit
  6728. if (res) {
  6729. // If we get a response, it should be 400 Bad Request
  6730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6731. EXPECT_EQ("close", res->get_header_value("Connection"));
  6732. }
  6733. EXPECT_FALSE(cli_.is_socket_open());
  6734. }
  6735. TEST_F(ServerTest, MultipartFormData) {
  6736. UploadFormDataItems items = {
  6737. {"text1", "text default", "", ""},
  6738. {"text2", "aωb", "", ""},
  6739. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6740. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6741. {"file3", "", "", "application/octet-stream"},
  6742. {"file4", "", "", " application/json tmp-string "}};
  6743. auto res = cli_.Post("/multipart", items);
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. }
  6747. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6748. UploadFormDataItems items = {
  6749. {"text", "default text", "", ""},
  6750. {"multi_text1", "aaaaa", "", ""},
  6751. {"multi_text1", "bbbbb", "", ""},
  6752. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6753. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6754. "application/json"},
  6755. };
  6756. auto res = cli_.Post("/multipart/multi_file_values", items);
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. }
  6760. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6761. auto res = cli_.Get("/hi");
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_EQ(StatusCode::OK_200, res->status);
  6764. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6765. EXPECT_EQ("Hello World!", res->body);
  6766. }
  6767. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6768. Request req;
  6769. req.method = "POST";
  6770. req.path = "/chunked";
  6771. std::string host_and_port;
  6772. host_and_port += HOST;
  6773. host_and_port += ":";
  6774. host_and_port += std::to_string(PORT);
  6775. req.headers.emplace("Host", host_and_port.c_str());
  6776. req.headers.emplace("Accept", "*/*");
  6777. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6778. req.headers.emplace("Content-Type", "text/plain");
  6779. req.headers.emplace("Content-Length", "0");
  6780. req.headers.emplace(
  6781. "Transfer-Encoding",
  6782. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6783. // Client does not chunk, so make a chunked body manually.
  6784. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6785. auto res = std::make_shared<Response>();
  6786. auto error = Error::Success;
  6787. auto ret = cli_.send(req, *res, error);
  6788. ASSERT_TRUE(ret);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. }
  6791. template <typename ClientT>
  6792. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6793. int expected_status) {
  6794. Request req;
  6795. req.method = "POST";
  6796. req.path = "/chunked";
  6797. std::string host_and_port;
  6798. host_and_port += HOST;
  6799. host_and_port += ":";
  6800. host_and_port += std::to_string(PORT);
  6801. req.headers.emplace("Host", host_and_port.c_str());
  6802. req.headers.emplace("Content-Length", "0");
  6803. req.headers.emplace("Transfer-Encoding", "chunked");
  6804. req.body = body;
  6805. auto res = std::make_shared<Response>();
  6806. auto error = Error::Success;
  6807. ASSERT_TRUE(cli.send(req, *res, error));
  6808. EXPECT_EQ(expected_status, res->status);
  6809. }
  6810. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6811. // rather than treat them as valid lengths.
  6812. template <typename ClientT>
  6813. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6814. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6815. }
  6816. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6817. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6818. }
  6819. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6820. expect_chunked_body_rejected(
  6821. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6822. }
  6823. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6824. // chunk-size line carries no CR, LF or other control character ahead of its
  6825. // terminator. Such a line must be refused rather than read as extension text.
  6826. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6827. expect_chunked_body_rejected(
  6828. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6829. }
  6830. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6831. expect_chunked_body_rejected(
  6832. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6833. }
  6834. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6835. expect_chunked_body_rejected(
  6836. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6837. }
  6838. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6839. // The literal stays split: a hex escape consumes every hex digit that
  6840. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6841. expect_chunked_body_rejected(
  6842. cli_, "4;a\x01"
  6843. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. // The bytes around chunk data are no payload, so they cannot ride on the
  6846. // payload limit
  6847. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6848. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, 'x');
  6849. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, '0');
  6850. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, ' ');
  6851. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6852. SCOPED_TRACE(size_line.substr(0, 2));
  6853. std::string body;
  6854. for (auto c : std::string("dechunked post body")) {
  6855. body += size_line + "\r\n" + c + "\r\n";
  6856. }
  6857. body += "0\r\n\r\n";
  6858. expect_chunked_body_rejected(cli_, body.c_str());
  6859. }
  6860. }
  6861. TEST_F(ServerTest, AcceptsChunkExtension) {
  6862. expect_chunked_body_status(cli_,
  6863. "4;name=value\r\ndech\r\n"
  6864. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6865. "0;last\r\n\r\n",
  6866. StatusCode::OK_200);
  6867. }
  6868. TEST_F(ServerTest, GetStreamed2) {
  6869. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6872. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6873. EXPECT_EQ(true, res->has_header("Content-Range"));
  6874. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6875. EXPECT_EQ(std::string("ab"), res->body);
  6876. }
  6877. TEST_F(ServerTest, GetStreamed) {
  6878. auto res = cli_.Get("/streamed");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6882. EXPECT_EQ(std::string("aaabbb"), res->body);
  6883. }
  6884. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6885. auto res = cli_.Get("/streamed-without-length",
  6886. Headers{make_range_header({{0, -1}})});
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. EXPECT_EQ(false, res->has_header("Content-Length"));
  6890. EXPECT_EQ(false, res->has_header("Content-Range"));
  6891. EXPECT_EQ(std::string("abcdefg"), res->body);
  6892. }
  6893. TEST_F(ServerTest, GetStreamedWithRange1) {
  6894. auto res =
  6895. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6898. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6899. EXPECT_EQ(true, res->has_header("Content-Range"));
  6900. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6901. EXPECT_EQ(std::string("def"), res->body);
  6902. }
  6903. TEST_F(ServerTest, GetStreamedWithRange2) {
  6904. auto res =
  6905. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6908. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6909. EXPECT_EQ(true, res->has_header("Content-Range"));
  6910. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6911. EXPECT_EQ(std::string("bcdefg"), res->body);
  6912. }
  6913. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6914. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6917. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6918. EXPECT_EQ(true, res->has_header("Content-Range"));
  6919. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6920. EXPECT_EQ(std::string("efg"), res->body);
  6921. }
  6922. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6923. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6924. // the entire representation.
  6925. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6926. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6929. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6930. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6931. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6932. }
  6933. }
  6934. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6935. auto res =
  6936. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6939. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6940. EXPECT_EQ(false, res->has_header("Content-Range"));
  6941. EXPECT_EQ(0U, res->body.size());
  6942. }
  6943. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6944. // Only a 206 is served as a partial representation. Under any other status
  6945. // `apply_ranges()` reported the full content length, so the body must match
  6946. // that header, and the content provider must never be asked for an offset
  6947. // outside the representation.
  6948. auto check = [&](int status, const char *range) {
  6949. auto path =
  6950. std::string("/streamed-with-range?status=") + std::to_string(status);
  6951. auto ctx = path + " Range: " + range;
  6952. auto res = cli_.Get(path, Headers{{"Range", range}});
  6953. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6954. EXPECT_EQ(status, res->status) << ctx;
  6955. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6957. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6958. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6959. };
  6960. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6961. check(403, "bytes=3-5");
  6962. // The offset is far past the representation.
  6963. check(403, "bytes=100000-100200");
  6964. // `first_pos` is still -1 here, and the bounds asserts in
  6965. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6966. check(403, "bytes=-3");
  6967. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6968. // multipart branch would have written one that is empty.
  6969. check(403, "bytes=1-2, 4-5");
  6970. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6971. // covers the whole representation.
  6972. check(200, "bytes=3-5");
  6973. check(200, "bytes=1-2, 4-5");
  6974. }
  6975. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6976. auto res =
  6977. cli_.Get("/streamed-with-range",
  6978. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6979. "92233720368547758079223372036854775807"}});
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6982. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6983. EXPECT_EQ(false, res->has_header("Content-Range"));
  6984. EXPECT_EQ(0U, res->body.size());
  6985. }
  6986. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6987. auto res = cli_.Get(
  6988. "/with-range",
  6989. Headers{{"Range",
  6990. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6991. {"Accept-Encoding", ""}});
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6994. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6995. EXPECT_EQ(true, res->has_header("Content-Range"));
  6996. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6997. EXPECT_EQ(std::string("abcdefg"), res->body);
  6998. }
  6999. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7000. auto res = cli_.Get("/with-range", Headers{
  7001. {"Range", "bytes=0-"},
  7002. {"Accept-Encoding", ""},
  7003. });
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7006. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7007. EXPECT_EQ(true, res->has_header("Content-Range"));
  7008. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7009. EXPECT_EQ(std::string("abcdefg"), res->body);
  7010. }
  7011. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7012. auto res = cli_.Get("/streamed-with-range",
  7013. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7016. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7017. EXPECT_EQ(false, res->has_header("Content-Range"));
  7018. EXPECT_EQ(267U, res->body.size());
  7019. // Check that both range contents are present
  7020. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7021. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7022. // Check that Content-Range headers are present for both ranges
  7023. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7024. std::string::npos);
  7025. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7026. std::string::npos);
  7027. }
  7028. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7029. Ranges ranges;
  7030. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7031. ranges.emplace_back(0, -1);
  7032. }
  7033. auto res = cli_.Get("/streamed-with-range?error",
  7034. Headers{{make_range_header(ranges)}});
  7035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7036. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7037. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7038. EXPECT_EQ(false, res->has_header("Content-Range"));
  7039. EXPECT_EQ(0U, res->body.size());
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7042. auto res = cli_.Get("/streamed-with-range",
  7043. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ(5U, res->body.size());
  7047. // Check that overlapping ranges are coalesced into a single range
  7048. EXPECT_EQ("bcdef", res->body);
  7049. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7050. // Should be single range, not multipart
  7051. EXPECT_TRUE(res->has_header("Content-Range"));
  7052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7053. }
  7054. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7055. auto res = cli_.Get("/streamed-with-range",
  7056. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7059. EXPECT_EQ(268U, res->body.size());
  7060. // Check that both range contents are present
  7061. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7062. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7063. // Check that Content-Range headers are present for both ranges
  7064. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7065. std::string::npos);
  7066. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7067. std::string::npos);
  7068. }
  7069. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7070. auto res = cli_.Get("/streamed-with-range",
  7071. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7074. EXPECT_EQ(269U, res->body.size());
  7075. // Check that both duplicate range contents are present
  7076. size_t first_abc = res->body.find("abc\r\n");
  7077. EXPECT_TRUE(first_abc != std::string::npos);
  7078. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7079. EXPECT_TRUE(second_abc != std::string::npos);
  7080. // Check that Content-Range headers are present for both ranges
  7081. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7082. EXPECT_TRUE(first_range != std::string::npos);
  7083. size_t second_range =
  7084. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7085. EXPECT_TRUE(second_range != std::string::npos);
  7086. }
  7087. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7088. auto res =
  7089. cli_.Get("/streamed-with-range?error",
  7090. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7092. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7093. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7094. EXPECT_EQ(false, res->has_header("Content-Range"));
  7095. EXPECT_EQ(0U, res->body.size());
  7096. }
  7097. TEST_F(ServerTest, GetStreamedEndless) {
  7098. uint64_t offset = 0;
  7099. auto res = cli_.Get("/streamed-cancel",
  7100. [&](const char * /*data*/, uint64_t data_length) {
  7101. if (offset < 100) {
  7102. offset += data_length;
  7103. return true;
  7104. }
  7105. return false;
  7106. });
  7107. ASSERT_TRUE(!res);
  7108. EXPECT_EQ(Error::Canceled, res.error());
  7109. }
  7110. TEST_F(ServerTest, ClientStop) {
  7111. std::atomic_size_t count{4};
  7112. std::vector<std::thread> threads;
  7113. for (auto i = count.load(); i != 0; --i) {
  7114. threads.emplace_back([&]() {
  7115. auto res = cli_.Get("/streamed-cancel",
  7116. [&](const char *, uint64_t) { return true; });
  7117. --count;
  7118. ASSERT_TRUE(!res);
  7119. EXPECT_TRUE(res.error() == Error::Canceled ||
  7120. res.error() == Error::Read || res.error() == Error::Write);
  7121. });
  7122. }
  7123. std::this_thread::sleep_for(std::chrono::seconds(2));
  7124. while (count != 0) {
  7125. cli_.stop();
  7126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7127. }
  7128. for (auto &t : threads) {
  7129. t.join();
  7130. }
  7131. }
  7132. TEST_F(ServerTest, GetWithRange1) {
  7133. auto res = cli_.Get("/with-range", Headers{
  7134. make_range_header({{3, 5}}),
  7135. {"Accept-Encoding", ""},
  7136. });
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7139. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7140. EXPECT_EQ(true, res->has_header("Content-Range"));
  7141. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7142. EXPECT_EQ(std::string("def"), res->body);
  7143. }
  7144. TEST_F(ServerTest, GetWithRange2) {
  7145. auto res = cli_.Get("/with-range", Headers{
  7146. make_range_header({{1, -1}}),
  7147. {"Accept-Encoding", ""},
  7148. });
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("bcdefg"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetWithRange3) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. make_range_header({{0, 0}}),
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("a"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetWithRange4) {
  7169. auto res = cli_.Get("/with-range", Headers{
  7170. make_range_header({{-1, 2}}),
  7171. {"Accept-Encoding", ""},
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7175. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7176. EXPECT_EQ(true, res->has_header("Content-Range"));
  7177. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7178. EXPECT_EQ(std::string("fg"), res->body);
  7179. }
  7180. TEST_F(ServerTest, GetWithRange5) {
  7181. auto res = cli_.Get("/with-range", Headers{
  7182. make_range_header({{0, 5}}),
  7183. {"Accept-Encoding", ""},
  7184. });
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("abcdef"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7193. auto res =
  7194. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7197. }
  7198. TEST_F(ServerTest, GetWithRangeMultipart) {
  7199. auto res =
  7200. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7204. EXPECT_EQ(false, res->has_header("Content-Range"));
  7205. EXPECT_EQ(267U, res->body.size());
  7206. }
  7207. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7208. auto res = cli_.Get("/with-range",
  7209. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7211. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7212. }
  7213. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7214. auto res = cli_.Get("/with-range-customized-response",
  7215. Headers{{make_range_header({{1, 2}})}});
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7218. EXPECT_EQ(true, res->has_header("Content-Length"));
  7219. EXPECT_EQ(false, res->has_header("Content-Range"));
  7220. EXPECT_EQ(JSON_DATA, res->body);
  7221. }
  7222. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7223. auto res = cli_.Get("/with-range-customized-response",
  7224. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7227. EXPECT_EQ(true, res->has_header("Content-Length"));
  7228. EXPECT_EQ(false, res->has_header("Content-Range"));
  7229. EXPECT_EQ(JSON_DATA, res->body);
  7230. }
  7231. TEST_F(ServerTest, Issue1772) {
  7232. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7235. }
  7236. TEST_F(ServerTest, Issue609) {
  7237. auto res = cli_.Delete("/issue609");
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. EXPECT_EQ(std::string("ok"), res->body);
  7241. }
  7242. TEST_F(ServerTest, GetStreamedChunked) {
  7243. auto res = cli_.Get("/streamed-chunked");
  7244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7245. EXPECT_EQ(StatusCode::OK_200, res->status);
  7246. EXPECT_EQ(std::string("123456789"), res->body);
  7247. }
  7248. TEST_F(ServerTest, GetStreamedChunked2) {
  7249. auto res = cli_.Get("/streamed-chunked2");
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. EXPECT_EQ(StatusCode::OK_200, res->status);
  7252. EXPECT_EQ(std::string("123456789"), res->body);
  7253. }
  7254. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7255. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ(std::string("123456789"), res->body);
  7259. EXPECT_TRUE(res->has_header("Trailer"));
  7260. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7261. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7262. // Trailers are now stored separately from headers (security fix)
  7263. EXPECT_EQ(2U, res->trailers.size());
  7264. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7265. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7266. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7267. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7268. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7269. // Verify trailers are NOT in headers (security verification)
  7270. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7271. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7272. }
  7273. TEST_F(ServerTest, LargeChunkedPost) {
  7274. Request req;
  7275. req.method = "POST";
  7276. req.path = "/large-chunked";
  7277. std::string host_and_port;
  7278. host_and_port += HOST;
  7279. host_and_port += ":";
  7280. host_and_port += std::to_string(PORT);
  7281. req.headers.emplace("Host", host_and_port.c_str());
  7282. req.headers.emplace("Accept", "*/*");
  7283. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7284. req.headers.emplace("Content-Type", "text/plain");
  7285. req.headers.emplace("Content-Length", "0");
  7286. req.headers.emplace("Transfer-Encoding", "chunked");
  7287. std::string long_string(30 * 1024u, 'a');
  7288. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7289. // Attempt to make a large enough post to exceed OS buffers, to test that
  7290. // the server handles short reads if the full chunk data isn't available.
  7291. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7292. auto res = std::make_shared<Response>();
  7293. auto error = Error::Success;
  7294. auto ret = cli_.send(req, *res, error);
  7295. ASSERT_TRUE(ret);
  7296. EXPECT_EQ(StatusCode::OK_200, res->status);
  7297. }
  7298. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7299. auto res = cli_.Get("/remote_addr");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7303. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7304. }
  7305. TEST_F(ServerTest, GetMethodLocalAddr) {
  7306. auto res = cli_.Get("/local_addr");
  7307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7308. EXPECT_EQ(StatusCode::OK_200, res->status);
  7309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7310. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7311. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7312. }
  7313. TEST_F(ServerTest, HTTPResponseSplitting) {
  7314. auto res = cli_.Get("/http_response_splitting");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::OK_200, res->status);
  7317. }
  7318. TEST_F(ServerTest, SlowRequest) {
  7319. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7320. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7321. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7322. }
  7323. #if 0
  7324. TEST_F(ServerTest, SlowPost) {
  7325. char buffer[64 * 1024];
  7326. memset(buffer, 0x42, sizeof(buffer));
  7327. auto res = cli_.Post(
  7328. "/slowpost", 64 * 1024 * 1024,
  7329. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7330. auto ret = sink.write(buffer, sizeof(buffer));
  7331. EXPECT_TRUE(ret);
  7332. return true;
  7333. },
  7334. "text/plain");
  7335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7336. EXPECT_EQ(StatusCode::OK_200, res->status);
  7337. }
  7338. TEST_F(ServerTest, SlowPostFail) {
  7339. char buffer[64 * 1024];
  7340. memset(buffer, 0x42, sizeof(buffer));
  7341. cli_.set_write_timeout(std::chrono::seconds(0));
  7342. auto res = cli_.Post(
  7343. "/slowpost", 64 * 1024 * 1024,
  7344. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7345. sink.write(buffer, sizeof(buffer));
  7346. return true;
  7347. },
  7348. "text/plain");
  7349. ASSERT_TRUE(!res);
  7350. EXPECT_EQ(Error::Write, res.error());
  7351. }
  7352. #endif
  7353. TEST_F(ServerTest, Put) {
  7354. auto res = cli_.Put("/put", "PUT", "text/plain");
  7355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. EXPECT_EQ("PUT", res->body);
  7358. }
  7359. TEST_F(ServerTest, PutWithContentProvider) {
  7360. auto res = cli_.Put(
  7361. "/put", 3,
  7362. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7363. sink.os << "PUT";
  7364. return true;
  7365. },
  7366. "text/plain");
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. EXPECT_EQ("PUT", res->body);
  7370. }
  7371. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7372. auto res = cli_.Post(
  7373. "/post", 42,
  7374. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7375. return false;
  7376. },
  7377. "text/plain");
  7378. ASSERT_TRUE(!res);
  7379. EXPECT_EQ(Error::Canceled, res.error());
  7380. }
  7381. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7382. auto res = cli_.Put(
  7383. "/put",
  7384. [](size_t /*offset*/, DataSink &sink) {
  7385. sink.os << "PUT";
  7386. sink.done();
  7387. return true;
  7388. },
  7389. "text/plain");
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::OK_200, res->status);
  7392. EXPECT_EQ("PUT", res->body);
  7393. }
  7394. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7395. auto res = cli_.Post(
  7396. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7397. "text/plain");
  7398. ASSERT_TRUE(!res);
  7399. EXPECT_EQ(Error::Canceled, res.error());
  7400. }
  7401. TEST_F(ServerTest, PostLoopBack) {
  7402. std::string body;
  7403. auto res = cli_.Post(
  7404. "/post-loopback", 9,
  7405. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7406. EXPECT_EQ(9u, length);
  7407. sink.write("123", 3);
  7408. sink.write("456", 3);
  7409. sink.write("789", 3);
  7410. return true;
  7411. },
  7412. "text/plain",
  7413. [&body](const char *data, size_t data_length) {
  7414. body.append(data, data_length);
  7415. return true;
  7416. });
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. EXPECT_EQ("123456789", body);
  7420. }
  7421. TEST_F(ServerTest, PutLoopBack) {
  7422. std::string body;
  7423. auto res = cli_.Put(
  7424. "/put-loopback", 9,
  7425. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7426. EXPECT_EQ(9u, length);
  7427. sink.write("123", 3);
  7428. sink.write("456", 3);
  7429. sink.write("789", 3);
  7430. return true;
  7431. },
  7432. "text/plain",
  7433. [&body](const char *data, size_t data_length) {
  7434. body.append(data, data_length);
  7435. return true;
  7436. });
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. EXPECT_EQ("123456789", body);
  7440. }
  7441. TEST_F(ServerTest, PatchLoopBack) {
  7442. std::string body;
  7443. auto res = cli_.Patch(
  7444. "/patch-loopback", 9,
  7445. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7446. EXPECT_EQ(9u, length);
  7447. sink.write("123", 3);
  7448. sink.write("456", 3);
  7449. sink.write("789", 3);
  7450. return true;
  7451. },
  7452. "text/plain",
  7453. [&body](const char *data, size_t data_length) {
  7454. body.append(data, data_length);
  7455. return true;
  7456. });
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("123456789", body);
  7460. }
  7461. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7462. std::string body;
  7463. auto res = cli_.Post(
  7464. "/post-loopback",
  7465. [](size_t /*offset*/, DataSink &sink) {
  7466. sink.write("123", 3);
  7467. sink.write("456", 3);
  7468. sink.write("789", 3);
  7469. sink.done();
  7470. return true;
  7471. },
  7472. "text/plain",
  7473. [&body](const char *data, size_t data_length) {
  7474. body.append(data, data_length);
  7475. return true;
  7476. });
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. EXPECT_EQ("123456789", body);
  7480. }
  7481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7482. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7483. cli_.set_compress(true);
  7484. auto res = cli_.Put(
  7485. "/put", 3,
  7486. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7487. sink.os << "PUT";
  7488. return true;
  7489. },
  7490. "text/plain");
  7491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. EXPECT_EQ("PUT", res->body);
  7494. }
  7495. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7496. cli_.set_compress(true);
  7497. auto res = cli_.Post(
  7498. "/post", 42,
  7499. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7500. return false;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(!res);
  7504. EXPECT_EQ(Error::Canceled, res.error());
  7505. }
  7506. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7507. cli_.set_compress(true);
  7508. auto res = cli_.Put(
  7509. "/put",
  7510. [](size_t /*offset*/, DataSink &sink) {
  7511. sink.os << "PUT";
  7512. sink.done();
  7513. return true;
  7514. },
  7515. "text/plain");
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. EXPECT_EQ("PUT", res->body);
  7519. }
  7520. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7521. cli_.set_compress(true);
  7522. auto res = cli_.Post(
  7523. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7524. "text/plain");
  7525. ASSERT_TRUE(!res);
  7526. EXPECT_EQ(Error::Canceled, res.error());
  7527. }
  7528. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7529. cli_.set_compress(true);
  7530. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ(LARGE_DATA, res->body);
  7534. }
  7535. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7536. #ifdef CPPHTTPLIB_SSL_ENABLED
  7537. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7538. Client cli(s.c_str());
  7539. cli.enable_server_certificate_verification(false);
  7540. #else
  7541. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7542. Client cli(s.c_str());
  7543. #endif
  7544. cli.set_compress(true);
  7545. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(StatusCode::OK_200, res->status);
  7548. EXPECT_EQ(LARGE_DATA, res->body);
  7549. // The compressed size should be less than a 10th of the original. May vary
  7550. // depending on the zlib library.
  7551. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7552. static_cast<uint64_t>(10 * 1024 * 1024));
  7553. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7554. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7555. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7556. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7557. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7558. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7559. #endif
  7560. }
  7561. TEST_F(ServerTest, PutContentWithDeflate) {
  7562. cli_.set_compress(false);
  7563. Headers headers;
  7564. headers.emplace("Content-Encoding", "deflate");
  7565. // PUT in deflate format:
  7566. auto res = cli_.Put("/put", headers,
  7567. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ("PUT", res->body);
  7571. }
  7572. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7573. Headers headers;
  7574. headers.emplace("Accept-Encoding", "gzip, deflate");
  7575. auto res = cli_.Get("/streamed-chunked", headers);
  7576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7577. EXPECT_EQ(StatusCode::OK_200, res->status);
  7578. EXPECT_EQ(std::string("123456789"), res->body);
  7579. }
  7580. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7581. Headers headers;
  7582. headers.emplace("Accept-Encoding", "gzip, deflate");
  7583. auto res = cli_.Get("/streamed-chunked2", headers);
  7584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7585. EXPECT_EQ(StatusCode::OK_200, res->status);
  7586. EXPECT_EQ(std::string("123456789"), res->body);
  7587. }
  7588. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7589. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7591. EXPECT_EQ(StatusCode::OK_200, res->status);
  7592. }
  7593. TEST(GzipDecompressor, ChunkedDecompression) {
  7594. std::string data;
  7595. for (size_t i = 0; i < 32 * 1024; ++i) {
  7596. data.push_back(static_cast<char>('a' + i % 26));
  7597. }
  7598. std::string compressed_data;
  7599. {
  7600. httplib::detail::gzip_compressor compressor;
  7601. bool result = compressor.compress(
  7602. data.data(), data.size(),
  7603. /*last=*/true,
  7604. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7605. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7606. compressed_data_size);
  7607. return true;
  7608. });
  7609. ASSERT_TRUE(result);
  7610. }
  7611. std::string decompressed_data;
  7612. {
  7613. httplib::detail::gzip_decompressor decompressor;
  7614. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7615. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7616. size_t chunk_size = 130;
  7617. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7618. chunk_begin += chunk_size) {
  7619. size_t current_chunk_size =
  7620. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7621. bool result = decompressor.decompress(
  7622. compressed_data.data() + chunk_begin, current_chunk_size,
  7623. [&](const char *decompressed_data_chunk,
  7624. size_t decompressed_data_chunk_size) {
  7625. decompressed_data.insert(decompressed_data.size(),
  7626. decompressed_data_chunk,
  7627. decompressed_data_chunk_size);
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(result);
  7631. }
  7632. }
  7633. ASSERT_EQ(data, decompressed_data);
  7634. }
  7635. TEST(GzipDecompressor, DeflateDecompression) {
  7636. std::string original_text = "Raw deflate without gzip";
  7637. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7638. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7639. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7640. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7641. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7642. std::string decompressed_data;
  7643. {
  7644. httplib::detail::gzip_decompressor decompressor;
  7645. bool result = decompressor.decompress(
  7646. compressed_data.data(), compressed_data.size(),
  7647. [&](const char *decompressed_data_chunk,
  7648. size_t decompressed_data_chunk_size) {
  7649. decompressed_data.insert(decompressed_data.size(),
  7650. decompressed_data_chunk,
  7651. decompressed_data_chunk_size);
  7652. return true;
  7653. });
  7654. ASSERT_TRUE(result);
  7655. }
  7656. ASSERT_EQ(original_text, decompressed_data);
  7657. }
  7658. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7659. std::string original_text = "Raw deflate without gzip";
  7660. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7661. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7662. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7663. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7664. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7665. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7666. std::string decompressed_data;
  7667. {
  7668. httplib::detail::gzip_decompressor decompressor;
  7669. bool result = decompressor.decompress(
  7670. compressed_data.data(), compressed_data.size(),
  7671. [&](const char *decompressed_data_chunk,
  7672. size_t decompressed_data_chunk_size) {
  7673. decompressed_data.insert(decompressed_data.size(),
  7674. decompressed_data_chunk,
  7675. decompressed_data_chunk_size);
  7676. return true;
  7677. });
  7678. ASSERT_TRUE(result);
  7679. }
  7680. ASSERT_EQ(original_text, decompressed_data);
  7681. }
  7682. #endif
  7683. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7684. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7685. Headers headers;
  7686. headers.emplace("Accept-Encoding", "br");
  7687. auto res = cli_.Get("/streamed-chunked", headers);
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ(std::string("123456789"), res->body);
  7691. }
  7692. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7693. Headers headers;
  7694. headers.emplace("Accept-Encoding", "br");
  7695. auto res = cli_.Get("/streamed-chunked2", headers);
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ(std::string("123456789"), res->body);
  7699. }
  7700. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7701. cli_.set_compress(true);
  7702. auto res = cli_.Put(
  7703. "/put", 3,
  7704. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7705. sink.os << "PUT";
  7706. return true;
  7707. },
  7708. "text/plain");
  7709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7710. EXPECT_EQ(StatusCode::OK_200, res->status);
  7711. EXPECT_EQ("PUT", res->body);
  7712. }
  7713. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7714. cli_.set_compress(true);
  7715. auto res = cli_.Put(
  7716. "/put",
  7717. [](size_t /*offset*/, DataSink &sink) {
  7718. sink.os << "PUT";
  7719. sink.done();
  7720. return true;
  7721. },
  7722. "text/plain");
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ("PUT", res->body);
  7726. }
  7727. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7728. cli_.set_compress(true);
  7729. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. EXPECT_EQ(LARGE_DATA, res->body);
  7733. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7734. }
  7735. #endif
  7736. TEST_F(ServerTest, Patch) {
  7737. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7739. EXPECT_EQ(StatusCode::OK_200, res->status);
  7740. EXPECT_EQ("PATCH", res->body);
  7741. }
  7742. TEST_F(ServerTest, Delete) {
  7743. auto res = cli_.Delete("/delete");
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(StatusCode::OK_200, res->status);
  7746. EXPECT_EQ("DELETE", res->body);
  7747. }
  7748. TEST_F(ServerTest, DeleteContentReceiver) {
  7749. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. EXPECT_EQ("content", res->body);
  7753. }
  7754. TEST_F(ServerTest, Options) {
  7755. auto res = cli_.Options("*");
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7759. EXPECT_TRUE(res->body.empty());
  7760. }
  7761. TEST_F(ServerTest, URL) {
  7762. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. }
  7766. TEST_F(ServerTest, ArrayParam) {
  7767. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. }
  7771. TEST_F(ServerTest, ArrayParamValues) {
  7772. auto res =
  7773. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. }
  7777. TEST_F(ServerTest, NoMultipleHeaders) {
  7778. Headers headers = {{"Content-Length", "5"}};
  7779. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7780. "text/plain");
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. }
  7784. TEST_F(ServerTest, PostContentReceiver) {
  7785. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. ASSERT_EQ(StatusCode::OK_200, res->status);
  7788. ASSERT_EQ("content", res->body);
  7789. }
  7790. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7791. UploadFormDataItems items = {
  7792. {"text1", "text default", "", ""},
  7793. {"text2", "aωb", "", ""},
  7794. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7795. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7796. {"file3", "", "", "application/octet-stream"},
  7797. };
  7798. auto res = cli_.Post("/content_receiver", items);
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::OK_200, res->status);
  7801. }
  7802. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7803. UploadFormDataItems items = {
  7804. {"text1", "text default", "", ""},
  7805. {"text2", "aωb", "", ""},
  7806. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7807. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7808. {"file3", "", "", "application/octet-stream"},
  7809. };
  7810. auto boundary = std::string("+++++");
  7811. std::string body;
  7812. for (const auto &item : items) {
  7813. body += "--" + boundary + "\r\n";
  7814. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7815. if (!item.filename.empty()) {
  7816. body += "; filename=\"" + item.filename + "\"";
  7817. }
  7818. body += "\r\n";
  7819. if (!item.content_type.empty()) {
  7820. body += "Content-Type: " + item.content_type + "\r\n";
  7821. }
  7822. body += "\r\n";
  7823. body += item.content + "\r\n";
  7824. }
  7825. body += "--" + boundary + "--\r\n";
  7826. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7827. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7829. EXPECT_EQ(StatusCode::OK_200, res->status);
  7830. }
  7831. TEST(MultipartFormDataTest, FieldEscaping) {
  7832. Server svr;
  7833. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7834. const ContentReader &content_reader) {
  7835. ASSERT_TRUE(req.is_multipart_form_data());
  7836. std::vector<FormData> received;
  7837. content_reader(
  7838. [&](const FormData &file) {
  7839. received.push_back(file);
  7840. return true;
  7841. },
  7842. [&](const char *data, size_t data_length) {
  7843. received.back().content.append(data, data_length);
  7844. return true;
  7845. });
  7846. // '"', CR and LF in names and filenames are escaped following the
  7847. // WHATWG HTML standard, so each part still parses as a single part
  7848. // with no injected headers. Content types get CR/LF escaped too,
  7849. // while '"' (legal there, e.g. quoted charset) is preserved.
  7850. ASSERT_EQ(4U, received.size());
  7851. EXPECT_EQ("na%22me", received[0].name);
  7852. EXPECT_EQ("quoted name", received[0].content);
  7853. EXPECT_EQ("file", received[1].name);
  7854. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7855. received[1].filename);
  7856. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7857. EXPECT_EQ("injected", received[1].content);
  7858. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7859. EXPECT_EQ("my%22file.txt", received[2].filename);
  7860. EXPECT_EQ("cr lf name", received[2].content);
  7861. EXPECT_EQ("typed", received[3].name);
  7862. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7863. received[3].content_type);
  7864. EXPECT_EQ("typed content", received[3].content);
  7865. });
  7866. auto port = svr.bind_to_any_port("localhost");
  7867. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7868. auto se = detail::scope_exit([&] {
  7869. svr.stop();
  7870. t.join();
  7871. ASSERT_FALSE(svr.is_running());
  7872. });
  7873. svr.wait_until_ready();
  7874. Client cli("localhost", port);
  7875. UploadFormDataItems items = {
  7876. {"na\"me", "quoted name", "", ""},
  7877. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7878. "application/octet-stream"},
  7879. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7880. {"typed", "typed content", "",
  7881. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7882. };
  7883. auto res = cli.Post("/post", items);
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. }
  7887. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7888. const UploadFormDataItems items = {
  7889. {"name1", "Content 1", "", ""},
  7890. {"name2", "Content 2", "file2.txt", "text/plain"},
  7891. };
  7892. Server svr;
  7893. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7894. const ContentReader &content_reader) {
  7895. ASSERT_TRUE(req.is_multipart_form_data());
  7896. std::vector<FormData> received;
  7897. content_reader(
  7898. [&](const FormData &file) {
  7899. received.push_back(file);
  7900. return true;
  7901. },
  7902. [&](const char *data, size_t data_length) {
  7903. received.back().content.append(data, data_length);
  7904. return true;
  7905. });
  7906. ASSERT_EQ(2U, received.size());
  7907. EXPECT_EQ("name1", received[0].name);
  7908. EXPECT_EQ("Content 1", received[0].content);
  7909. EXPECT_EQ("name2", received[1].name);
  7910. EXPECT_EQ("Content 2", received[1].content);
  7911. EXPECT_EQ("file2.txt", received[1].filename);
  7912. EXPECT_EQ("text/plain", received[1].content_type);
  7913. });
  7914. auto port = svr.bind_to_any_port("localhost");
  7915. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7916. auto se = detail::scope_exit([&] {
  7917. svr.stop();
  7918. t.join();
  7919. ASSERT_FALSE(svr.is_running());
  7920. });
  7921. svr.wait_until_ready();
  7922. Client cli("localhost", port);
  7923. // Whole-body serialization with a generated boundary
  7924. {
  7925. MultipartFormDataWriter writer;
  7926. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7927. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7928. writer.content_type());
  7929. auto body = writer.serialize(items);
  7930. EXPECT_EQ(body.size(), writer.content_length(items));
  7931. auto res = cli.Post("/post", body, writer.content_type());
  7932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. // Per-part framing with a custom boundary via a content provider
  7936. {
  7937. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7938. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7939. MultipartFormDataWriter writer("custom-boundary_123");
  7940. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7941. std::string body;
  7942. for (const auto &item : items) {
  7943. body += writer.item_begin(item);
  7944. body += item.content;
  7945. body += MultipartFormDataWriter::item_end();
  7946. }
  7947. body += writer.finish();
  7948. EXPECT_EQ(body.size(), writer.content_length(items));
  7949. auto res = cli.Post(
  7950. "/post", body.size(),
  7951. [&](size_t offset, size_t length, DataSink &sink) {
  7952. sink.write(body.data() + offset, length);
  7953. return true;
  7954. },
  7955. writer.content_type());
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. }
  7960. TEST_F(ServerTest, PostContentReceiverGzip) {
  7961. cli_.set_compress(true);
  7962. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. ASSERT_EQ(StatusCode::OK_200, res->status);
  7965. ASSERT_EQ("content", res->body);
  7966. }
  7967. TEST_F(ServerTest, PutContentReceiver) {
  7968. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7970. ASSERT_EQ(StatusCode::OK_200, res->status);
  7971. ASSERT_EQ("content", res->body);
  7972. }
  7973. TEST_F(ServerTest, PatchContentReceiver) {
  7974. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. ASSERT_EQ(StatusCode::OK_200, res->status);
  7977. ASSERT_EQ("content", res->body);
  7978. }
  7979. template <typename ClientType>
  7980. void TestWithHeadersAndContentReceiver(
  7981. ClientType &cli,
  7982. std::function<Result(ClientType &, const std::string &, const Headers &,
  7983. const std::string &, const std::string &,
  7984. ContentReceiver, DownloadProgress)>
  7985. request_func) {
  7986. Headers headers;
  7987. headers.emplace("X-Custom-Header", "test-value");
  7988. std::string received_body;
  7989. auto res = request_func(
  7990. cli, "/content_receiver", headers, "content", "application/json",
  7991. [&](const char *data, size_t data_length) {
  7992. received_body.append(data, data_length);
  7993. return true;
  7994. },
  7995. nullptr);
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ("content", received_body);
  7999. }
  8000. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. using ClientT = SSLClient;
  8003. #else
  8004. using ClientT = Client;
  8005. #endif
  8006. TestWithHeadersAndContentReceiver<ClientT>(
  8007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8008. const std::string &body, const std::string &content_type,
  8009. ContentReceiver receiver, DownloadProgress progress) {
  8010. return cli.Post(path, headers, body, content_type, receiver, progress);
  8011. });
  8012. }
  8013. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiver<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver, DownloadProgress progress) {
  8023. return cli.Put(path, headers, body, content_type, receiver, progress);
  8024. });
  8025. }
  8026. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8027. #ifdef CPPHTTPLIB_SSL_ENABLED
  8028. using ClientT = SSLClient;
  8029. #else
  8030. using ClientT = Client;
  8031. #endif
  8032. TestWithHeadersAndContentReceiver<ClientT>(
  8033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8034. const std::string &body, const std::string &content_type,
  8035. ContentReceiver receiver, DownloadProgress progress) {
  8036. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8037. });
  8038. }
  8039. template <typename ClientType>
  8040. void TestWithHeadersAndContentReceiverWithProgress(
  8041. ClientType &cli,
  8042. std::function<Result(ClientType &, const std::string &, const Headers &,
  8043. const std::string &, const std::string &,
  8044. ContentReceiver, DownloadProgress)>
  8045. request_func) {
  8046. Headers headers;
  8047. headers.emplace("X-Test-Header", "progress-test");
  8048. std::string received_body;
  8049. auto progress_called = false;
  8050. auto res = request_func(
  8051. cli, "/content_receiver", headers, "content", "text/plain",
  8052. [&](const char *data, size_t data_length) {
  8053. received_body.append(data, data_length);
  8054. return true;
  8055. },
  8056. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8057. progress_called = true;
  8058. return true;
  8059. });
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("content", received_body);
  8063. EXPECT_TRUE(progress_called);
  8064. }
  8065. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Post(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Put(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8092. #ifdef CPPHTTPLIB_SSL_ENABLED
  8093. using ClientT = SSLClient;
  8094. #else
  8095. using ClientT = Client;
  8096. #endif
  8097. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8098. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8099. const std::string &body, const std::string &content_type,
  8100. ContentReceiver receiver, DownloadProgress progress) {
  8101. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8102. });
  8103. }
  8104. template <typename ClientType>
  8105. void TestWithHeadersAndContentReceiverError(
  8106. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8107. const Headers &, const std::string &,
  8108. const std::string &, ContentReceiver)>
  8109. request_func) {
  8110. Headers headers;
  8111. headers.emplace("X-Error-Test", "true");
  8112. std::string received_body;
  8113. auto receiver_failed = false;
  8114. auto res =
  8115. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8116. [&](const char *data, size_t data_length) {
  8117. received_body.append(data, data_length);
  8118. receiver_failed = true;
  8119. return false;
  8120. });
  8121. ASSERT_FALSE(res);
  8122. EXPECT_TRUE(receiver_failed);
  8123. }
  8124. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverError<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver) {
  8134. return cli.Post(path, headers, body, content_type, receiver);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverError<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver) {
  8147. return cli.Put(path, headers, body, content_type, receiver);
  8148. });
  8149. }
  8150. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8151. #ifdef CPPHTTPLIB_SSL_ENABLED
  8152. using ClientT = SSLClient;
  8153. #else
  8154. using ClientT = Client;
  8155. #endif
  8156. TestWithHeadersAndContentReceiverError<ClientT>(
  8157. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8158. const std::string &body, const std::string &content_type,
  8159. ContentReceiver receiver) {
  8160. return cli.Patch(path, headers, body, content_type, receiver);
  8161. });
  8162. }
  8163. TEST_F(ServerTest, PostQueryStringAndBody) {
  8164. auto res =
  8165. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. ASSERT_EQ(StatusCode::OK_200, res->status);
  8168. }
  8169. TEST_F(ServerTest, HTTP2Magic) {
  8170. Request req;
  8171. req.method = "PRI";
  8172. req.path = "*";
  8173. req.body = "SM";
  8174. auto res = std::make_shared<Response>();
  8175. auto error = Error::Success;
  8176. auto ret = cli_.send(req, *res, error);
  8177. ASSERT_TRUE(ret);
  8178. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8179. }
  8180. TEST_F(ServerTest, KeepAlive) {
  8181. auto res = cli_.Get("/hi");
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8185. EXPECT_EQ("Hello World!", res->body);
  8186. res = cli_.Get("/hi");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8190. EXPECT_EQ("Hello World!", res->body);
  8191. res = cli_.Get("/hi");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8195. EXPECT_EQ("Hello World!", res->body);
  8196. res = cli_.Get("/not-exist");
  8197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8199. res = cli_.Post("/empty", "", "text/plain");
  8200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8201. EXPECT_EQ(StatusCode::OK_200, res->status);
  8202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8203. EXPECT_EQ("empty", res->body);
  8204. EXPECT_EQ("close", res->get_header_value("Connection"));
  8205. res = cli_.Post(
  8206. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8207. "text/plain");
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8211. EXPECT_EQ("empty", res->body);
  8212. cli_.set_keep_alive(false);
  8213. res = cli_.Get("/last-request");
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::OK_200, res->status);
  8216. EXPECT_EQ("close", res->get_header_value("Connection"));
  8217. }
  8218. TEST_F(ServerTest, TooManyRedirect) {
  8219. cli_.set_follow_location(true);
  8220. auto res = cli_.Get("/redirect/0");
  8221. ASSERT_TRUE(!res);
  8222. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8223. }
  8224. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8225. Request req;
  8226. req.method = "FOOBAR";
  8227. req.path = "/hi";
  8228. cli_.set_keep_alive(true);
  8229. auto res = cli_.send(req);
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8232. EXPECT_EQ("close", res->get_header_value("Connection"));
  8233. EXPECT_FALSE(cli_.is_socket_open());
  8234. }
  8235. TEST_F(ServerTest, CustomRouteReadsBody) {
  8236. const std::string xml =
  8237. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8238. Request req;
  8239. req.method = "PROPFIND";
  8240. req.path = "/dav/dir";
  8241. req.set_header("Depth", "1");
  8242. req.body = xml;
  8243. auto res = cli_.send(req);
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8246. EXPECT_EQ(xml, res->body);
  8247. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8248. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8249. }
  8250. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8251. Request req;
  8252. req.method = "PROPFIND";
  8253. req.path = "/dav/42";
  8254. auto res = cli_.send(req);
  8255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8256. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8257. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8258. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8259. }
  8260. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8261. Request req;
  8262. req.method = "PROPFIND";
  8263. req.path = "/dav-re/123";
  8264. auto res = cli_.send(req);
  8265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8266. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8267. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8268. }
  8269. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8270. Request req;
  8271. req.method = "MKCOL";
  8272. req.path = "/dav-mkcol";
  8273. auto res = cli_.send(req);
  8274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8275. EXPECT_EQ(StatusCode::Created_201, res->status);
  8276. }
  8277. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8278. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8279. Request req;
  8280. req.method = "REPORT";
  8281. req.path = "/dav-report";
  8282. req.body = xml;
  8283. auto res = cli_.send(req);
  8284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8285. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8286. EXPECT_EQ(xml, res->body);
  8287. }
  8288. // A content reader route must fire even when the request carries no body,
  8289. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8290. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8291. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8292. Request req;
  8293. req.method = "REPORT";
  8294. req.path = "/dav-report";
  8295. auto res = cli_.send(req);
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8298. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8299. }
  8300. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8301. Request req;
  8302. req.method = "PROPFIND";
  8303. req.path = "/not-dav";
  8304. auto res = cli_.send(req);
  8305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8307. }
  8308. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8309. Request req;
  8310. req.method = "UNLOCK";
  8311. req.path = "/dav/dir";
  8312. cli_.set_keep_alive(true);
  8313. auto res = cli_.send(req);
  8314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8315. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8316. EXPECT_EQ("close", res->get_header_value("Connection"));
  8317. EXPECT_FALSE(cli_.is_socket_open());
  8318. }
  8319. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8320. // The mount point serves this path, but only for GET and HEAD.
  8321. auto get_res = cli_.Get("/dir/index.html");
  8322. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8323. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8324. Request req;
  8325. req.method = "PROPFIND";
  8326. req.path = "/dir/index.html";
  8327. auto res = cli_.send(req);
  8328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8330. }
  8331. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8332. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8333. cli_.set_keep_alive(true);
  8334. for (auto i = 0; i < 2; i++) {
  8335. Request req;
  8336. req.method = "PROPFIND";
  8337. req.path = "/dav/dir";
  8338. req.body = xml;
  8339. auto res = cli_.send(req);
  8340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8341. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8342. EXPECT_EQ(xml, res->body);
  8343. EXPECT_TRUE(cli_.is_socket_open());
  8344. }
  8345. // A built-in method must still be served on the same connection.
  8346. cli_.set_keep_alive(false);
  8347. auto res = cli_.Get("/hi");
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::OK_200, res->status);
  8350. EXPECT_EQ("close", res->get_header_value("Connection"));
  8351. }
  8352. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8353. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8354. Request req;
  8355. req.method = "PROPFIND";
  8356. req.path = "/dav/dir";
  8357. req.set_header("Expect", "100-continue");
  8358. req.body = xml;
  8359. auto res = cli_.send(req);
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8362. EXPECT_EQ(xml, res->body);
  8363. }
  8364. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8365. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8366. TEST_F(ServerTest, Gzip) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "gzip, deflate");
  8369. auto res = cli_.Get("/compress", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8373. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "gzip, deflate");
  8382. auto res = cli_.Get("/compress-with-charset", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8385. EXPECT_EQ("application/json; charset=utf-8",
  8386. res->get_header_value("Content-Type"));
  8387. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8388. "7890123456789012345678901234567890",
  8389. res->body);
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8393. Headers headers;
  8394. headers.emplace("Accept-Encoding", "");
  8395. auto res = cli_.Get("/compress", headers);
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8399. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8401. "7890123456789012345678901234567890",
  8402. res->body);
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. }
  8405. TEST_F(ServerTest, GzipWithContentReceiver) {
  8406. Headers headers;
  8407. headers.emplace("Accept-Encoding", "gzip, deflate");
  8408. std::string body;
  8409. auto res =
  8410. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8411. EXPECT_EQ(100U, data_length);
  8412. body.append(data, data_length);
  8413. return true;
  8414. });
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8418. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8419. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8420. "7890123456789012345678901234567890",
  8421. body);
  8422. EXPECT_EQ(StatusCode::OK_200, res->status);
  8423. }
  8424. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8425. Headers headers;
  8426. headers.emplace("Accept-Encoding", "gzip, deflate");
  8427. cli_.set_decompress(false);
  8428. auto res = cli_.Get("/compress", headers);
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8431. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8432. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8433. EXPECT_EQ(33U, res->body.size());
  8434. EXPECT_EQ(StatusCode::OK_200, res->status);
  8435. }
  8436. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8437. Headers headers;
  8438. headers.emplace("Accept-Encoding", "");
  8439. std::string body;
  8440. auto res =
  8441. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8442. EXPECT_EQ(100U, data_length);
  8443. body.append(data, data_length);
  8444. return true;
  8445. });
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8449. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8451. "7890123456789012345678901234567890",
  8452. body);
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST_F(ServerTest, NoGzip) {
  8456. Headers headers;
  8457. headers.emplace("Accept-Encoding", "gzip, deflate");
  8458. auto res = cli_.Get("/nocompress", headers);
  8459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8464. "7890123456789012345678901234567890",
  8465. res->body);
  8466. EXPECT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8469. Headers headers;
  8470. headers.emplace("Accept-Encoding", "gzip, deflate");
  8471. std::string body;
  8472. auto res = cli_.Get("/nocompress", headers,
  8473. [&](const char *data, size_t data_length) {
  8474. EXPECT_EQ(100U, data_length);
  8475. body.append(data, data_length);
  8476. return true;
  8477. });
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8480. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8481. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8482. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8483. "7890123456789012345678901234567890",
  8484. body);
  8485. EXPECT_EQ(StatusCode::OK_200, res->status);
  8486. }
  8487. TEST_F(ServerTest, MultipartFormDataGzip) {
  8488. UploadFormDataItems items = {
  8489. {"key1", "test", "", ""},
  8490. {"key2", "--abcdefg123", "", ""},
  8491. };
  8492. cli_.set_compress(true);
  8493. auto res = cli_.Post("/compress-multipart", items);
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. #endif
  8498. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8499. // Static file compression is opt-in, so these run their own server rather than
  8500. // flipping it on for the shared ServerTest fixture, which would silently
  8501. // rewrite what every other static file test is asserting.
  8502. class StaticFileCompressionTest : public ::testing::Test {
  8503. protected:
  8504. void TearDown() override {
  8505. if (t_.joinable()) {
  8506. svr_.stop();
  8507. t_.join();
  8508. }
  8509. }
  8510. int start(const std::function<void(Server &)> &configure = nullptr) {
  8511. // Serves the same tree as a directory of build-time compressed assets
  8512. // would be served: the mount point names the coding the files are already
  8513. // stored in. Registered before "/" so it is the one that matches.
  8514. svr_.set_mount_point("/pre-encoded", "./www",
  8515. {{"Content-Encoding", "gzip"}});
  8516. svr_.set_mount_point("/", "./www");
  8517. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8518. res.set_file_content("./www/dir/index.html", "text/html");
  8519. });
  8520. svr_.Get("/pre-encoded-file-content",
  8521. [](const Request & /*req*/, Response &res) {
  8522. res.set_header("Content-Encoding", "gzip");
  8523. res.set_file_content("./www/dir/index.html", "text/html");
  8524. });
  8525. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8526. res.set_content_provider(
  8527. 6, "text/plain",
  8528. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8529. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8530. return true;
  8531. });
  8532. });
  8533. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8534. res.set_content_provider(
  8535. 1000, "text/plain",
  8536. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8537. if (offset < 100) {
  8538. std::string data(100, 'A');
  8539. sink.write(data.data(), data.size());
  8540. return true;
  8541. }
  8542. std::this_thread::sleep_for(std::chrono::seconds(2));
  8543. std::string data(900, 'B');
  8544. sink.write(data.data(), data.size());
  8545. return true;
  8546. });
  8547. });
  8548. if (configure) { configure(svr_); }
  8549. auto port = svr_.bind_to_any_port(HOST);
  8550. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8551. svr_.wait_until_ready();
  8552. return port;
  8553. }
  8554. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8555. // Every file under ./www except 1MB.txt is smaller than the default
  8556. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8557. // it out of the way.
  8558. static void enable_without_floor(Server &svr) {
  8559. svr.set_static_file_compression(true);
  8560. svr.set_static_file_compression_min_length(0);
  8561. }
  8562. Server svr_;
  8563. std::thread t_;
  8564. };
  8565. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8566. auto port = start();
  8567. Client cli(HOST, port);
  8568. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8570. EXPECT_EQ(StatusCode::OK_200, res->status);
  8571. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8572. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8573. EXPECT_EQ(1048576U, res->body.size());
  8574. }
  8575. TEST_F(StaticFileCompressionTest, MountPoint) {
  8576. auto port = start(enable);
  8577. Client cli(HOST, port);
  8578. cli.set_decompress(false);
  8579. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ(StatusCode::OK_200, res->status);
  8582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8583. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8584. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8585. // The response stays self-delimiting: a length, not a chunked body.
  8586. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8587. EXPECT_EQ(std::to_string(res->body.size()),
  8588. res->get_header_value("Content-Length"));
  8589. EXPECT_LT(res->body.size(), 1048576U);
  8590. EXPECT_FALSE(res->body.empty());
  8591. }
  8592. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8593. auto port = start(enable);
  8594. Client cli(HOST, port);
  8595. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8597. EXPECT_EQ(StatusCode::OK_200, res->status);
  8598. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8599. EXPECT_EQ(1048576U, res->body.size());
  8600. }
  8601. TEST_F(StaticFileCompressionTest, FileContent) {
  8602. auto port = start(enable_without_floor);
  8603. Client cli(HOST, port);
  8604. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8606. EXPECT_EQ(StatusCode::OK_200, res->status);
  8607. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8608. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8609. EXPECT_EQ(104U, res->body.size());
  8610. }
  8611. // A handler that serves an already-encoded file names the coding itself. The
  8612. // file-backed path decided its coding from Accept-Encoding and the content
  8613. // type alone, so it compressed the stored bytes a second time and appended a
  8614. // second Content-Encoding field line.
  8615. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8616. auto port = start(enable_without_floor);
  8617. Client cli(HOST, port);
  8618. cli.set_decompress(false);
  8619. auto res = cli.Get("/pre-encoded-file-content",
  8620. Headers{{"Accept-Encoding", "gzip"}});
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(StatusCode::OK_200, res->status);
  8623. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8624. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8625. // Vary belongs to a coding the server chose, and it chose none here.
  8626. EXPECT_FALSE(res->has_header("Vary"));
  8627. // The file travels exactly as it is stored on disk.
  8628. EXPECT_EQ(104U, res->body.size());
  8629. }
  8630. // The 1MB file clears the default floor, so this one runs the configuration a
  8631. // deployment would actually have.
  8632. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8633. auto port = start(enable);
  8634. Client cli(HOST, port);
  8635. cli.set_decompress(false);
  8636. auto res =
  8637. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8641. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8642. EXPECT_FALSE(res->has_header("Vary"));
  8643. EXPECT_EQ(1048576U, res->body.size());
  8644. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8645. }
  8646. TEST_F(StaticFileCompressionTest, Head) {
  8647. auto port = start(enable);
  8648. Client cli(HOST, port);
  8649. cli.set_decompress(false);
  8650. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8651. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8652. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8656. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8657. // HEAD still reports the size a GET would return.
  8658. EXPECT_EQ(get->get_header_value("Content-Length"),
  8659. res->get_header_value("Content-Length"));
  8660. EXPECT_TRUE(res->body.empty());
  8661. }
  8662. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8663. auto port = start(enable);
  8664. Client cli(HOST, port);
  8665. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8666. {"Accept-Encoding", "gzip"}});
  8667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8668. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8669. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8670. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8671. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8672. EXPECT_EQ("cd", res->body);
  8673. }
  8674. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8675. auto port = start(enable);
  8676. Client cli(HOST, port);
  8677. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8679. EXPECT_EQ(StatusCode::OK_200, res->status);
  8680. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8681. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8682. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8683. }
  8684. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8685. auto port = start(enable);
  8686. Client cli(HOST, port);
  8687. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8689. EXPECT_EQ(StatusCode::OK_200, res->status);
  8690. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8691. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8692. EXPECT_TRUE(res->body.empty());
  8693. }
  8694. TEST_F(StaticFileCompressionTest, MinLength) {
  8695. auto port = start(enable);
  8696. Client cli(HOST, port);
  8697. // 104 bytes, well under the default floor. Compressing it would add the
  8698. // gzip header and trailer to a body that already fits in one packet.
  8699. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_EQ(StatusCode::OK_200, res->status);
  8702. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8703. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8704. }
  8705. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8706. auto port = start([](Server &svr) {
  8707. svr.set_static_file_compression(true);
  8708. svr.set_static_file_compression_min_length(1);
  8709. });
  8710. Client cli(HOST, port);
  8711. cli.set_decompress(false);
  8712. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8714. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8715. // A 9-byte file comes back larger than it went in, because gzip's header and
  8716. // trailer outweigh anything deflate can save. That is the end of the range
  8717. // the floor exists to keep out.
  8718. EXPECT_GT(res->body.size(), 9U);
  8719. }
  8720. TEST_F(StaticFileCompressionTest, MaxLength) {
  8721. auto port = start([](Server &svr) {
  8722. svr.set_static_file_compression(true);
  8723. svr.set_static_file_compression_min_length(0);
  8724. svr.set_static_file_compression_max_length(1024);
  8725. });
  8726. Client cli(HOST, port);
  8727. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8728. // defines `small` as a macro on Windows.
  8729. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8731. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8732. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8733. // Under it: compressed.
  8734. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8735. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8736. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8737. }
  8738. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8739. auto port = start(enable_without_floor);
  8740. Client cli(HOST, port);
  8741. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8742. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8743. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8744. auto identity_etag = identity->get_header_value("ETag");
  8745. ASSERT_FALSE(identity_etag.empty());
  8746. auto gzipped =
  8747. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8748. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8749. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8750. auto gzip_etag = gzipped->get_header_value("ETag");
  8751. ASSERT_FALSE(gzip_etag.empty());
  8752. // Two representations, two validators.
  8753. EXPECT_NE(identity_etag, gzip_etag);
  8754. // Each one revalidates against the request that would produce it...
  8755. auto fresh =
  8756. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8757. {"If-None-Match", gzip_etag}});
  8758. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8759. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8760. auto fresh_identity =
  8761. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8762. {"If-None-Match", identity_etag}});
  8763. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8764. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8765. // ...and not against the other representation.
  8766. auto crossed =
  8767. cli.Get("/dir/index.html",
  8768. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8769. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8770. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8771. }
  8772. // The opt-in covers responses the server reads off disk itself. A caller's own
  8773. // known-length provider keeps its Content-Length and, more importantly, keeps
  8774. // delivering incrementally: routing it through a compressor would hold every
  8775. // write back until zlib's window filled.
  8776. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8777. auto port = start(enable);
  8778. Client cli(HOST, port);
  8779. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8781. EXPECT_EQ(StatusCode::OK_200, res->status);
  8782. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8783. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8784. EXPECT_EQ("aaabbb", res->body);
  8785. }
  8786. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8787. auto port = start(enable);
  8788. Client cli(HOST, port);
  8789. cli.set_read_timeout(1, 0);
  8790. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8791. Headers{{"Accept-Encoding", "gzip"}});
  8792. ASSERT_TRUE(handle.is_valid());
  8793. // The provider writes 100 bytes and then stalls for longer than the read
  8794. // timeout. Those first bytes have to arrive anyway: run the response through
  8795. // a compressor and zlib holds them until its window fills, so the read would
  8796. // come back empty instead.
  8797. char buf[256];
  8798. auto n = handle.read(buf, sizeof(buf));
  8799. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8800. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8801. }
  8802. #endif
  8803. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8804. TEST_F(ServerTest, Brotli) {
  8805. Headers headers;
  8806. headers.emplace("Accept-Encoding", "br");
  8807. auto res = cli_.Get("/compress", headers);
  8808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8809. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8811. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8812. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8813. "7890123456789012345678901234567890",
  8814. res->body);
  8815. EXPECT_EQ(StatusCode::OK_200, res->status);
  8816. }
  8817. #endif
  8818. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8819. TEST_F(ServerTest, Zstd) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "zstd");
  8822. auto res = cli_.Get("/compress", headers);
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8828. "7890123456789012345678901234567890",
  8829. res->body);
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "");
  8835. auto res = cli_.Get("/compress", headers);
  8836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8837. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8839. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8840. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8841. "7890123456789012345678901234567890",
  8842. res->body);
  8843. EXPECT_EQ(StatusCode::OK_200, res->status);
  8844. }
  8845. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8846. Headers headers;
  8847. headers.emplace("Accept-Encoding", "zstd");
  8848. std::string body;
  8849. auto res =
  8850. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8851. EXPECT_EQ(100U, data_length);
  8852. body.append(data, data_length);
  8853. return true;
  8854. });
  8855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8856. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8858. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8859. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8860. "7890123456789012345678901234567890",
  8861. body);
  8862. EXPECT_EQ(StatusCode::OK_200, res->status);
  8863. }
  8864. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8865. Headers headers;
  8866. headers.emplace("Accept-Encoding", "zstd");
  8867. cli_.set_decompress(false);
  8868. auto res = cli_.Get("/compress", headers);
  8869. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8870. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8871. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8872. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8874. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8876. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8877. EXPECT_EQ(StatusCode::OK_200, res->status);
  8878. ASSERT_EQ(26U, res->body.size());
  8879. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8880. 0);
  8881. }
  8882. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8883. Headers headers;
  8884. headers.emplace("Accept-Encoding", "");
  8885. std::string body;
  8886. auto res =
  8887. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8888. EXPECT_EQ(100U, data_length);
  8889. body.append(data, data_length);
  8890. return true;
  8891. });
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8894. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8897. "7890123456789012345678901234567890",
  8898. body);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, NoZstd) {
  8902. Headers headers;
  8903. headers.emplace("Accept-Encoding", "zstd");
  8904. auto res = cli_.Get("/nocompress", headers);
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8907. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8908. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8909. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8910. "7890123456789012345678901234567890",
  8911. res->body);
  8912. EXPECT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8915. Headers headers;
  8916. headers.emplace("Accept-Encoding", "zstd");
  8917. std::string body;
  8918. auto res = cli_.Get("/nocompress", headers,
  8919. [&](const char *data, size_t data_length) {
  8920. EXPECT_EQ(100U, data_length);
  8921. body.append(data, data_length);
  8922. return true;
  8923. });
  8924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8925. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8926. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8929. "7890123456789012345678901234567890",
  8930. body);
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. }
  8933. // TODO: How to enable zstd ??
  8934. TEST_F(ServerTest, MultipartFormDataZstd) {
  8935. UploadFormDataItems items = {
  8936. {"key1", "test", "", ""},
  8937. {"key2", "--abcdefg123", "", ""},
  8938. };
  8939. Headers headers;
  8940. headers.emplace("Accept-Encoding", "zstd");
  8941. cli_.set_compress(true);
  8942. auto res = cli_.Post("/compress-multipart", headers, items);
  8943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8944. EXPECT_EQ(StatusCode::OK_200, res->status);
  8945. }
  8946. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8947. Headers headers;
  8948. headers.emplace("Accept-Encoding", "zstd");
  8949. cli_.set_compress(true);
  8950. auto res = cli_.Put(
  8951. "/put", headers, 3,
  8952. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8953. sink.os << "PUT";
  8954. return true;
  8955. },
  8956. "text/plain");
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("PUT", res->body);
  8960. }
  8961. // Pre-compression logging tests
  8962. TEST_F(ServerTest, PreCompressionLogging) {
  8963. // Test data for compression (matches the actual /compress endpoint content)
  8964. const std::string test_content =
  8965. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8966. "3456789012345678901234567890";
  8967. // Variables to capture logging data
  8968. std::string pre_compression_body;
  8969. std::string pre_compression_content_type;
  8970. std::string pre_compression_content_encoding;
  8971. std::string post_compression_body;
  8972. std::string post_compression_content_type;
  8973. std::string post_compression_content_encoding;
  8974. // Set up pre-compression logger
  8975. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8976. const Response &res) {
  8977. pre_compression_body = res.body;
  8978. pre_compression_content_type = res.get_header_value("Content-Type");
  8979. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8980. });
  8981. // Set up post-compression logger
  8982. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8983. post_compression_body = res.body;
  8984. post_compression_content_type = res.get_header_value("Content-Type");
  8985. post_compression_content_encoding =
  8986. res.get_header_value("Content-Encoding");
  8987. });
  8988. // Test with gzip compression
  8989. Headers headers;
  8990. headers.emplace("Accept-Encoding", "gzip");
  8991. auto res = cli_.Get("/compress", headers);
  8992. // Verify response was compressed
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8996. // Verify pre-compression logger captured uncompressed content
  8997. EXPECT_EQ(test_content, pre_compression_body);
  8998. EXPECT_EQ("text/plain", pre_compression_content_type);
  8999. EXPECT_TRUE(pre_compression_content_encoding
  9000. .empty()); // No encoding header before compression
  9001. // Verify post-compression logger captured compressed content
  9002. EXPECT_NE(test_content,
  9003. post_compression_body); // Should be different after compression
  9004. EXPECT_EQ("text/plain", post_compression_content_type);
  9005. EXPECT_EQ("gzip", post_compression_content_encoding);
  9006. // Verify compressed content is smaller
  9007. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9008. }
  9009. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9010. const std::string test_content =
  9011. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9012. "3456789012345678901234567890";
  9013. std::string pre_compression_body;
  9014. std::string post_compression_body;
  9015. svr_.set_pre_compression_logger(
  9016. [&](const Request & /*req*/, const Response &res) {
  9017. pre_compression_body = res.body;
  9018. });
  9019. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9020. post_compression_body = res.body;
  9021. });
  9022. Headers headers;
  9023. headers.emplace("Accept-Encoding", "br");
  9024. auto res = cli_.Get("/compress", headers);
  9025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9026. EXPECT_EQ(StatusCode::OK_200, res->status);
  9027. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9028. // Verify pre-compression content is uncompressed
  9029. EXPECT_EQ(test_content, pre_compression_body);
  9030. // Verify post-compression content is compressed
  9031. EXPECT_NE(test_content, post_compression_body);
  9032. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9033. }
  9034. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9035. const std::string test_content =
  9036. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9037. "3456789012345678901234567890";
  9038. std::string pre_compression_body;
  9039. std::string post_compression_body;
  9040. svr_.set_pre_compression_logger(
  9041. [&](const Request & /*req*/, const Response &res) {
  9042. pre_compression_body = res.body;
  9043. });
  9044. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9045. post_compression_body = res.body;
  9046. });
  9047. // Request without compression (use /nocompress endpoint)
  9048. Headers headers;
  9049. auto res = cli_.Get("/nocompress", headers);
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::OK_200, res->status);
  9052. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9053. // Pre-compression logger should not be called when no compression is applied
  9054. EXPECT_TRUE(
  9055. pre_compression_body.empty()); // Pre-compression logger not called
  9056. EXPECT_EQ(
  9057. test_content,
  9058. post_compression_body); // Post-compression logger captures final content
  9059. }
  9060. TEST_F(ServerTest, LoggerSeesContentLength) {
  9061. size_t logged_content_length = 0;
  9062. std::string logged_content_length_header;
  9063. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9064. logged_content_length = res.content_length_;
  9065. logged_content_length_header = res.get_header_value("Content-Length");
  9066. });
  9067. auto res = cli_.Get("/nocompress");
  9068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. EXPECT_EQ(res->body.size(), logged_content_length);
  9071. EXPECT_EQ(std::to_string(logged_content_length),
  9072. logged_content_length_header);
  9073. }
  9074. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9075. const std::string test_content =
  9076. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9077. "3456789012345678901234567890";
  9078. std::string pre_compression_body;
  9079. bool pre_logger_called = false;
  9080. // Set only pre-compression logger
  9081. svr_.set_pre_compression_logger(
  9082. [&](const Request & /*req*/, const Response &res) {
  9083. pre_compression_body = res.body;
  9084. pre_logger_called = true;
  9085. });
  9086. Headers headers;
  9087. headers.emplace("Accept-Encoding", "gzip");
  9088. auto res = cli_.Get("/compress", headers);
  9089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9090. EXPECT_EQ(StatusCode::OK_200, res->status);
  9091. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9092. // Verify pre-compression logger was called
  9093. EXPECT_TRUE(pre_logger_called);
  9094. EXPECT_EQ(test_content, pre_compression_body);
  9095. }
  9096. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9097. {
  9098. // Test with Expect: 100-continue header - success case
  9099. // Server returns 100 Continue, client sends body, server returns 200 OK
  9100. Request req;
  9101. req.method = "POST";
  9102. req.path = "/post-large";
  9103. req.set_header("Expect", "100-continue");
  9104. req.body = LARGE_DATA;
  9105. Response res;
  9106. auto error = Error::Success;
  9107. cli_.set_keep_alive(true);
  9108. auto ret = cli_.send(req, res, error);
  9109. EXPECT_TRUE(ret);
  9110. EXPECT_EQ(StatusCode::OK_200, res.status);
  9111. EXPECT_EQ(LARGE_DATA, res.body);
  9112. }
  9113. {
  9114. // Test with Expect: 100-continue header - error case
  9115. // Client should not send the body when server returns an error
  9116. Request req;
  9117. req.method = "POST";
  9118. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9119. req.set_header("Expect", "100-continue");
  9120. req.body = LARGE_DATA;
  9121. Response res;
  9122. auto error = Error::Success;
  9123. auto start = std::chrono::high_resolution_clock::now();
  9124. cli_.set_keep_alive(true);
  9125. auto ret = cli_.send(req, res, error);
  9126. auto end = std::chrono::high_resolution_clock::now();
  9127. auto elapsed =
  9128. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9129. .count();
  9130. // With Expect: 100-continue, request completes successfully but with error
  9131. EXPECT_TRUE(ret);
  9132. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9133. EXPECT_EQ("close", res.get_header_value("Connection"));
  9134. EXPECT_FALSE(cli_.is_socket_open());
  9135. EXPECT_LE(elapsed, 2000);
  9136. }
  9137. {
  9138. // Send an extra GET request to ensure error recovery without hanging
  9139. Request req;
  9140. req.method = "GET";
  9141. req.path = "/hi";
  9142. auto start = std::chrono::high_resolution_clock::now();
  9143. auto res = cli_.send(req);
  9144. auto end = std::chrono::high_resolution_clock::now();
  9145. auto elapsed =
  9146. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9147. .count();
  9148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9149. EXPECT_EQ(StatusCode::OK_200, res->status);
  9150. EXPECT_EQ("Hello World!", res->body);
  9151. EXPECT_LE(elapsed, 500);
  9152. }
  9153. }
  9154. TEST(ZstdDecompressor, ChunkedDecompression) {
  9155. std::string data;
  9156. for (size_t i = 0; i < 32 * 1024; ++i) {
  9157. data.push_back(static_cast<char>('a' + i % 26));
  9158. }
  9159. std::string compressed_data;
  9160. {
  9161. httplib::detail::zstd_compressor compressor;
  9162. bool result = compressor.compress(
  9163. data.data(), data.size(),
  9164. /*last=*/true,
  9165. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9166. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9167. compressed_data_size);
  9168. return true;
  9169. });
  9170. ASSERT_TRUE(result);
  9171. }
  9172. std::string decompressed_data;
  9173. {
  9174. httplib::detail::zstd_decompressor decompressor;
  9175. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9176. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9177. size_t chunk_size = 130;
  9178. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9179. chunk_begin += chunk_size) {
  9180. size_t current_chunk_size =
  9181. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9182. bool result = decompressor.decompress(
  9183. compressed_data.data() + chunk_begin, current_chunk_size,
  9184. [&](const char *decompressed_data_chunk,
  9185. size_t decompressed_data_chunk_size) {
  9186. decompressed_data.insert(decompressed_data.size(),
  9187. decompressed_data_chunk,
  9188. decompressed_data_chunk_size);
  9189. return true;
  9190. });
  9191. ASSERT_TRUE(result);
  9192. }
  9193. }
  9194. ASSERT_EQ(data, decompressed_data);
  9195. }
  9196. TEST(ZstdDecompressor, Decompress) {
  9197. std::string original_text = "Compressed with ZSTD";
  9198. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9199. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9200. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9201. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9202. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9203. std::string decompressed_data;
  9204. {
  9205. httplib::detail::zstd_decompressor decompressor;
  9206. bool result = decompressor.decompress(
  9207. compressed_data.data(), compressed_data.size(),
  9208. [&](const char *decompressed_data_chunk,
  9209. size_t decompressed_data_chunk_size) {
  9210. decompressed_data.insert(decompressed_data.size(),
  9211. decompressed_data_chunk,
  9212. decompressed_data_chunk_size);
  9213. return true;
  9214. });
  9215. ASSERT_TRUE(result);
  9216. }
  9217. ASSERT_EQ(original_text, decompressed_data);
  9218. }
  9219. #endif
  9220. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9221. // separate chunks so that the server sees each part in its own read(). Used to
  9222. // place a read boundary at a specific offset of a request body.
  9223. static bool send_request_in_parts(time_t read_timeout_sec,
  9224. const std::vector<std::string> &parts,
  9225. std::string *resp = nullptr,
  9226. int port = PORT) {
  9227. auto error = Error::Success;
  9228. auto client_sock = detail::create_client_socket(
  9229. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9230. /*connection_timeout_sec=*/5, 0,
  9231. /*read_timeout_sec=*/5, 0,
  9232. /*write_timeout_sec=*/5, 0, std::string(), error);
  9233. if (client_sock == INVALID_SOCKET) { return false; }
  9234. auto ret = detail::process_client_socket(
  9235. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9236. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9237. for (size_t i = 0; i < parts.size(); i++) {
  9238. const auto &part = parts[i];
  9239. if (part.size() !=
  9240. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9241. return false;
  9242. }
  9243. if (i + 1 < parts.size()) {
  9244. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9245. }
  9246. }
  9247. char buf[512];
  9248. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9249. while (line_reader.getline()) {
  9250. if (resp) { *resp += line_reader.ptr(); }
  9251. }
  9252. return true;
  9253. });
  9254. detail::close_socket(client_sock);
  9255. return ret;
  9256. }
  9257. // Sends a raw request to a server listening at HOST:PORT.
  9258. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9259. std::string *resp = nullptr, int port = PORT) {
  9260. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9261. }
  9262. #ifdef CPPHTTPLIB_SSL_ENABLED
  9263. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9265. ASSERT_TRUE(svr.is_valid());
  9266. svr.set_read_timeout(1, 0);
  9267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9268. auto se = detail::scope_exit([&] {
  9269. svr.stop();
  9270. t.join();
  9271. ASSERT_FALSE(svr.is_running());
  9272. });
  9273. svr.wait_until_ready();
  9274. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9275. // keeps each wait well within the read timeout. The server gives up a
  9276. // second in, so the bytes sent after that fail.
  9277. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9278. parts.resize(26, std::string(1, '\0'));
  9279. EXPECT_FALSE(send_request_in_parts(5, parts));
  9280. }
  9281. #endif
  9282. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9283. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9284. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9285. const std::vector<std::string> &parts,
  9286. std::string *resp = nullptr,
  9287. int port = PORT) {
  9288. auto error = Error::Success;
  9289. auto sock = detail::create_client_socket(
  9290. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9291. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9292. /*write_timeout_sec=*/5, 0, std::string(), error);
  9293. if (sock == INVALID_SOCKET) { return false; }
  9294. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9295. auto ctx = SSL_CTX_new(TLS_client_method());
  9296. auto ssl = SSL_new(ctx);
  9297. auto ssl_se = detail::scope_exit([&] {
  9298. SSL_free(ssl);
  9299. SSL_CTX_free(ctx);
  9300. });
  9301. SSL_set_fd(ssl, static_cast<int>(sock));
  9302. if (SSL_connect(ssl) != 1) { return false; }
  9303. for (size_t i = 0; i < parts.size(); i++) {
  9304. const auto &part = parts[i];
  9305. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9306. static_cast<int>(part.size())) {
  9307. return false;
  9308. }
  9309. if (i + 1 < parts.size()) {
  9310. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9311. }
  9312. }
  9313. char buf[512];
  9314. int n;
  9315. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9316. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9317. }
  9318. return true;
  9319. }
  9320. #endif
  9321. // The request line, then a header value a byte at a time.
  9322. static std::vector<std::string> slow_request_head_parts() {
  9323. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9324. parts.resize(26, "a");
  9325. parts.emplace_back("\r\n\r\n");
  9326. return parts;
  9327. }
  9328. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9329. // within the one-second read timeout. The server gives up a second in, before
  9330. // the head is complete.
  9331. static void
  9332. expect_slow_request_head_dropped(Server &svr,
  9333. const std::function<std::string()> &send) {
  9334. std::atomic<bool> handled(false);
  9335. svr.Get("/", [&](const Request &, Response &res) {
  9336. handled = true;
  9337. res.set_content("ok", "text/plain");
  9338. });
  9339. svr.set_read_timeout(1, 0);
  9340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9341. auto se = detail::scope_exit([&] {
  9342. svr.stop();
  9343. t.join();
  9344. ASSERT_FALSE(svr.is_running());
  9345. });
  9346. svr.wait_until_ready();
  9347. auto resp = send();
  9348. EXPECT_FALSE(handled);
  9349. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9350. }
  9351. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9352. Server svr;
  9353. expect_slow_request_head_dropped(svr, [] {
  9354. std::string resp;
  9355. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9356. return resp;
  9357. });
  9358. }
  9359. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9360. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9362. ASSERT_TRUE(svr.is_valid());
  9363. expect_slow_request_head_dropped(svr, [] {
  9364. std::string resp;
  9365. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9366. return resp;
  9367. });
  9368. }
  9369. #endif
  9370. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9371. Server svr;
  9372. std::string header_value;
  9373. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9374. header_value = req.get_header_value("foo");
  9375. res.set_content("ok", "text/plain");
  9376. });
  9377. thread t = thread([&] { svr.listen(HOST, PORT); });
  9378. auto se = detail::scope_exit([&] {
  9379. svr.stop();
  9380. t.join();
  9381. ASSERT_FALSE(svr.is_running());
  9382. });
  9383. svr.wait_until_ready();
  9384. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9385. // like characters are not treated the same - use vertical tab and escape.
  9386. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9387. "foo: \t \v bar \x1B\t \r\n"
  9388. "Connection: close\r\n"
  9389. "\r\n";
  9390. std::string res;
  9391. ASSERT_TRUE(send_request(5, req, &res));
  9392. EXPECT_EQ(header_value, "");
  9393. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9394. }
  9395. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9396. Server svr;
  9397. std::string received;
  9398. svr.Get("/order", [&](const Request &req, Response &res) {
  9399. received = entries_to_string(req.headers);
  9400. res.set_content("ok", "text/plain");
  9401. });
  9402. auto port = svr.bind_to_any_port(HOST);
  9403. thread t = thread([&] { svr.listen_after_bind(); });
  9404. auto se = detail::scope_exit([&] {
  9405. svr.stop();
  9406. t.join();
  9407. ASSERT_FALSE(svr.is_running());
  9408. });
  9409. svr.wait_until_ready();
  9410. const std::string req = "GET /order HTTP/1.1\r\n"
  9411. "Host: localhost\r\n"
  9412. "X-First: 1\r\n"
  9413. "X-Dup: a\r\n"
  9414. "X-Second: 2\r\n"
  9415. "X-Dup: b\r\n"
  9416. "Connection: close\r\n"
  9417. "\r\n";
  9418. std::string res;
  9419. ASSERT_TRUE(send_request(5, req, &res, port));
  9420. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9421. EXPECT_EQ(
  9422. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9423. received);
  9424. }
  9425. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9426. Server svr;
  9427. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9428. res.set_header("Set-Cookie", "first=1");
  9429. res.set_header("X-Between", "y");
  9430. res.set_header("Set-Cookie", "second=2");
  9431. res.set_content("ok", "text/plain");
  9432. });
  9433. auto port = svr.bind_to_any_port(HOST);
  9434. thread t = thread([&] { svr.listen_after_bind(); });
  9435. auto se = detail::scope_exit([&] {
  9436. svr.stop();
  9437. t.join();
  9438. ASSERT_FALSE(svr.is_running());
  9439. });
  9440. svr.wait_until_ready();
  9441. Client cli(HOST, port);
  9442. auto res = cli.Get("/cookies");
  9443. ASSERT_TRUE(res);
  9444. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9445. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9446. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9447. }
  9448. // A stream may send a byte at a time with a small extension on each chunk,
  9449. // however long it runs
  9450. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9451. Server svr;
  9452. svr.Post("/count", [](const Request &req, Response &res) {
  9453. res.set_content(std::to_string(req.body.size()), "text/plain");
  9454. });
  9455. auto port = svr.bind_to_any_port(HOST);
  9456. ASSERT_LT(0, port);
  9457. thread t = thread([&] { svr.listen_after_bind(); });
  9458. auto se = detail::scope_exit([&] {
  9459. svr.stop();
  9460. t.join();
  9461. ASSERT_FALSE(svr.is_running());
  9462. });
  9463. svr.wait_until_ready();
  9464. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9465. "\r\nTransfer-Encoding: chunked\r\n"
  9466. "Connection: close\r\n\r\n";
  9467. for (auto i = 0; i < 4096; i++) {
  9468. req += "1;a=b\r\nx\r\n";
  9469. }
  9470. req += "0\r\n\r\n";
  9471. std::string res;
  9472. ASSERT_TRUE(send_request(5, req, &res, port));
  9473. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9474. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9475. }
  9476. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9477. Server svr;
  9478. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9479. auto i = new int(0);
  9480. res.set_header("Trailer", "X-Safe, X-Reflected");
  9481. res.set_chunked_content_provider(
  9482. "text/plain",
  9483. [i](size_t /*offset*/, DataSink &sink) {
  9484. if (*i == 0) {
  9485. sink.os << "body";
  9486. } else {
  9487. Headers trailer;
  9488. // A valid trailer that must survive.
  9489. trailer.emplace("X-Safe", "safe");
  9490. // Attacker-controlled value carrying CR/LF (response splitting).
  9491. trailer.emplace("X-Reflected",
  9492. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9493. // Attacker-controlled name carrying CR/LF.
  9494. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9495. sink.done_with_trailer(trailer);
  9496. }
  9497. (*i)++;
  9498. return true;
  9499. },
  9500. [i](bool /*success*/) { delete i; });
  9501. });
  9502. thread t = thread([&] { svr.listen(HOST, PORT); });
  9503. auto se = detail::scope_exit([&] {
  9504. svr.stop();
  9505. t.join();
  9506. ASSERT_FALSE(svr.is_running());
  9507. });
  9508. svr.wait_until_ready();
  9509. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9510. "Host: " + HOST +
  9511. "\r\n"
  9512. "Connection: close\r\n"
  9513. "\r\n";
  9514. std::string res;
  9515. ASSERT_TRUE(send_request(5, req, &res));
  9516. // The injected fields must not appear anywhere in the raw response.
  9517. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9518. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9519. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9520. // Invalid trailers are dropped entirely, matching set_header().
  9521. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9522. // The valid trailer still passes through.
  9523. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9524. }
  9525. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9526. // A custom header writer gets only the fields the default one writes
  9527. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9528. std::string s;
  9529. for (const auto &h : hdrs) {
  9530. s += h.first + ": " + h.second + "\r\n";
  9531. }
  9532. s += "\r\n";
  9533. return strm.write(s.data(), s.size());
  9534. };
  9535. for (auto custom_writer : {false, true}) {
  9536. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9537. Server svr;
  9538. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9539. svr.set_post_routing_handler([](const Request &, Response &res) {
  9540. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9541. });
  9542. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9543. // res.headers is a public field an application can populate directly,
  9544. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9545. // A valid header that must survive.
  9546. res.headers.emplace("X-Safe", "safe");
  9547. // Attacker-controlled value carrying CR/LF (response splitting).
  9548. res.headers.emplace("X-Reflected",
  9549. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9550. // Attacker-controlled name carrying CR/LF.
  9551. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9552. res.set_content("body", "text/plain");
  9553. });
  9554. thread t = thread([&] { svr.listen(HOST, PORT); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9562. "Host: " + HOST +
  9563. "\r\n"
  9564. "Connection: close\r\n"
  9565. "\r\n";
  9566. std::string res;
  9567. ASSERT_TRUE(send_request(5, req, &res));
  9568. // The injected fields must not appear anywhere in the raw response.
  9569. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9570. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9571. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9572. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9573. // Invalid headers are dropped entirely, matching set_header().
  9574. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9575. // The valid header still passes through.
  9576. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9577. }
  9578. }
  9579. // Forward declaration: in split builds split.py strips `inline` and moves the
  9580. // definition into httplib.cc, so detail::write_request_line is not visible from
  9581. // the public httplib.h. Re-declaring it here lets the tests link against the
  9582. // symbol in both header-only and split builds.
  9583. namespace httplib {
  9584. namespace detail {
  9585. ssize_t write_request_line(Stream &strm, const std::string &method,
  9586. const std::string &path);
  9587. } // namespace detail
  9588. } // namespace httplib
  9589. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9590. // A well-formed target is written verbatim.
  9591. {
  9592. detail::BufferStream strm;
  9593. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9594. EXPECT_GT(n, 0);
  9595. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9596. }
  9597. // A target carrying CR/LF, SP or other control octets must be rejected
  9598. // before anything reaches the wire, otherwise it splits the request line and
  9599. // injects a header or a whole request.
  9600. const std::string evil_targets[] = {
  9601. "/a\r\nInjected: pwned",
  9602. "/a\rInjected",
  9603. "/a\nInjected",
  9604. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9605. "/a b",
  9606. "/a\tb",
  9607. "/a\x7f",
  9608. };
  9609. for (const auto &evil : evil_targets) {
  9610. detail::BufferStream strm;
  9611. auto n = detail::write_request_line(strm, "GET", evil);
  9612. EXPECT_LT(n, 0);
  9613. EXPECT_TRUE(strm.get_buffer().empty());
  9614. }
  9615. }
  9616. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9617. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9618. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9619. // target reaches write_request. The client must fail cleanly with
  9620. // Error::Write instead of putting a request-line-less, header-injecting
  9621. // request on the wire.
  9622. Server svr;
  9623. svr.Get("/a", [](const Request &, Response &res) {
  9624. res.set_content("ok", "text/plain");
  9625. });
  9626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9627. auto se = detail::scope_exit([&] {
  9628. svr.stop();
  9629. thread.join();
  9630. ASSERT_FALSE(svr.is_running());
  9631. });
  9632. svr.wait_until_ready();
  9633. {
  9634. Client cli(HOST, PORT);
  9635. cli.set_path_encode(false);
  9636. // The request is rejected before anything is written, so the connection
  9637. // stays silent and the subsequent response read would otherwise block for
  9638. // the full default read timeout. Shorten it -- the assertion is on the
  9639. // error, not the timeout.
  9640. cli.set_read_timeout(1, 0);
  9641. auto res = cli.Get("/a\r\nInjected: pwned");
  9642. EXPECT_FALSE(res);
  9643. EXPECT_EQ(Error::Write, res.error());
  9644. }
  9645. }
  9646. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9647. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9648. // including extension methods.
  9649. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9650. for (const auto &method : good_methods) {
  9651. detail::BufferStream strm;
  9652. auto n = detail::write_request_line(strm, method, "/");
  9653. EXPECT_GT(n, 0);
  9654. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9655. }
  9656. // A method carrying CR/LF would split the request line and smuggle a whole
  9657. // request ahead of the real one. A space or an empty method corrupts the
  9658. // request line. All must be rejected before anything reaches the wire.
  9659. const std::string evil_methods[] = {
  9660. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9661. "GET\r\nInjected: pwned",
  9662. "GET\r",
  9663. "GET\n",
  9664. "GE T",
  9665. "",
  9666. };
  9667. for (const auto &evil : evil_methods) {
  9668. detail::BufferStream strm;
  9669. auto n = detail::write_request_line(strm, evil, "/");
  9670. EXPECT_LT(n, 0);
  9671. EXPECT_TRUE(strm.get_buffer().empty());
  9672. }
  9673. }
  9674. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9675. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9676. // through Client::send must fail with Error::Write and no request, neither
  9677. // the smuggled one nor the real one, may reach the server.
  9678. Server svr;
  9679. std::atomic<int> request_count(0);
  9680. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9681. request_count++;
  9682. res.status = StatusCode::OK_200;
  9683. return Server::HandlerResponse::Handled;
  9684. });
  9685. auto port = svr.bind_to_any_port(HOST);
  9686. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9687. auto se = detail::scope_exit([&] {
  9688. svr.stop();
  9689. thread.join();
  9690. ASSERT_FALSE(svr.is_running());
  9691. });
  9692. svr.wait_until_ready();
  9693. {
  9694. Client cli(HOST, port);
  9695. const std::string evil_methods[] = {
  9696. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9697. "GE T",
  9698. "",
  9699. };
  9700. for (const auto &evil : evil_methods) {
  9701. Request req;
  9702. req.method = evil;
  9703. req.path = "/";
  9704. auto res = cli.send(req);
  9705. EXPECT_FALSE(res);
  9706. EXPECT_EQ(Error::Write, res.error());
  9707. }
  9708. auto handle =
  9709. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9710. EXPECT_FALSE(handle.is_valid());
  9711. EXPECT_EQ(Error::Write, handle.error);
  9712. // A valid request on the same client still goes through.
  9713. auto res = cli.Get("/");
  9714. ASSERT_TRUE(res);
  9715. EXPECT_EQ(StatusCode::OK_200, res->status);
  9716. }
  9717. EXPECT_EQ(1, request_count.load());
  9718. }
  9719. // Sends a raw request and verifies that there isn't a crash or exception.
  9720. static void test_raw_request(const std::string &req,
  9721. std::string *out = nullptr) {
  9722. Server svr;
  9723. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9724. res.set_content("ok", "text/plain");
  9725. });
  9726. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9727. res.set_content("ok", "text/plain");
  9728. });
  9729. svr.Get("/header_field_value_check",
  9730. [&](const Request & /*req*/, Response &res) {
  9731. res.set_content("ok", "text/plain");
  9732. });
  9733. svr.CustomRoute("PROPFIND", "/dav",
  9734. [&](const Request & /*req*/, Response &res) {
  9735. res.status = StatusCode::MultiStatus_207;
  9736. });
  9737. // Server read timeout must be longer than the client read timeout for the
  9738. // bug to reproduce, probably to force the server to process a request
  9739. // without a trailing blank line.
  9740. const time_t client_read_timeout_sec = 1;
  9741. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9742. bool listen_thread_ok = false;
  9743. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9744. auto se = detail::scope_exit([&] {
  9745. svr.stop();
  9746. t.join();
  9747. ASSERT_FALSE(svr.is_running());
  9748. EXPECT_TRUE(listen_thread_ok);
  9749. });
  9750. svr.wait_until_ready();
  9751. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9752. }
  9753. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9754. // A certain header line causes an exception if the header property is parsed
  9755. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9756. test_raw_request(
  9757. "GET /hi HTTP/1.1\r\n"
  9758. " : "
  9759. " "
  9760. " ");
  9761. }
  9762. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9763. // A certain header line causes an exception if the header property *name* is
  9764. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9765. // greedy matcher and requires backtracking when there are a lot of ":"
  9766. // characters.
  9767. // This occurs with libc++ but not libstdc++.
  9768. test_raw_request(
  9769. "GET /hi HTTP/1.1\r\n"
  9770. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9771. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9772. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9773. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9774. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9775. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9776. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9777. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9778. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9779. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9780. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9781. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9782. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9783. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9784. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9785. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9786. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9787. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9788. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9789. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9790. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9791. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9792. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9793. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9794. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9795. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9796. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9797. "&&&%%%");
  9798. }
  9799. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9800. // Make sure this doesn't crash the server.
  9801. // In a previous version of the header line regex, the "\r" rendered the line
  9802. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9803. // a new position where the leading white space ended and the field value
  9804. // began.
  9805. // The crash occurs with libc++ but not libstdc++.
  9806. test_raw_request("GET /hi HTTP/1.1\r\n"
  9807. "a:" +
  9808. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9809. "\r\n"
  9810. "\r\n");
  9811. }
  9812. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9813. const char *rejected[] = {
  9814. // RFC 9112 §3: one SP between the parts, and nothing else
  9815. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9816. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9817. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9818. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9819. // A request-target has no fragment
  9820. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9821. // An HTTP/1.1 request needs a Host
  9822. "GET /hi HTTP/1.1\r\n\r\n",
  9823. };
  9824. for (auto request : rejected) {
  9825. std::string out;
  9826. test_raw_request(request, &out);
  9827. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9828. }
  9829. std::string out;
  9830. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9831. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9832. }
  9833. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9834. // RFC 9112 §6.1
  9835. const char *requests[] = {
  9836. "PUT /put_hi HTTP/1.1\r\n"
  9837. "Host: localhost\r\n"
  9838. "Content-Length: 0\r\n"
  9839. "Transfer-Encoding: chunked\r\n"
  9840. "\r\n"
  9841. "0\r\n\r\n",
  9842. "PUT /put_hi HTTP/1.0\r\n"
  9843. "Connection: keep-alive\r\n"
  9844. "Transfer-Encoding: chunked\r\n"
  9845. "\r\n"
  9846. "0\r\n\r\n",
  9847. };
  9848. for (auto request : requests) {
  9849. std::string out;
  9850. test_raw_request(request, &out);
  9851. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9852. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9853. }
  9854. }
  9855. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9856. std::string out;
  9857. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9858. "Content-Type: text/plain\r\n"
  9859. "Transfer-Encoding: chunked\r\n"
  9860. "\r\n"
  9861. "nothex\r\n",
  9862. &out);
  9863. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9864. }
  9865. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9866. std::string out;
  9867. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9868. "Content-Type: text/plain\r\n"
  9869. "Transfer-Encoding: chunked\r\n"
  9870. "\r\n"
  9871. "3\r\n"
  9872. "xyz\r\n"
  9873. "NaN\r\n",
  9874. &out);
  9875. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9876. }
  9877. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9878. std::string out;
  9879. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9880. "Content-Type: text/plain\r\n"
  9881. "Transfer-Encoding: chunked\r\n"
  9882. "\r\n"
  9883. // Length is too large for 64 bits.
  9884. "1ffffffffffffffff\r\n"
  9885. "xyz\r\n",
  9886. &out);
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9890. test_raw_request("GET /hi HTTP/1.1\r\n"
  9891. "Content-Type: text/plain\r\n\r");
  9892. }
  9893. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9894. std::string out;
  9895. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9896. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9897. }
  9898. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9899. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9900. std::string out;
  9901. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9902. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9903. }
  9904. }
  9905. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9906. std::string out;
  9907. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9908. "Host: localhost\r\n"
  9909. "Connection: close\r\n\r\n",
  9910. &out);
  9911. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9912. }
  9913. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9914. Server svr;
  9915. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9916. EXPECT_TRUE(!req.remote_addr.empty());
  9917. });
  9918. thread t = thread([&] { svr.listen(HOST, PORT); });
  9919. auto se = detail::scope_exit([&] {
  9920. svr.stop();
  9921. t.join();
  9922. ASSERT_FALSE(svr.is_running());
  9923. });
  9924. svr.wait_until_ready();
  9925. // Send an invalid request line to trigger Bad Request
  9926. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9927. std::string out;
  9928. ASSERT_TRUE(send_request(5, bad_req, &out));
  9929. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9930. }
  9931. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9932. // answered right away rather than blocking on a read that waits for EOF.
  9933. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9934. std::string out;
  9935. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9936. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9937. }
  9938. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9939. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9940. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9941. for (const auto *method : methods) {
  9942. Server svr;
  9943. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9944. EXPECT_FALSE(svr.is_valid()) << method;
  9945. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9946. }
  9947. }
  9948. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9949. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9950. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9951. for (const auto *method : methods) {
  9952. Server svr;
  9953. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9954. EXPECT_FALSE(svr.is_valid()) << method;
  9955. }
  9956. }
  9957. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9958. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9959. "COPY", "MOVE", "LOCK",
  9960. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9961. Server svr;
  9962. for (const auto *method : methods) {
  9963. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9964. }
  9965. EXPECT_TRUE(svr.is_valid());
  9966. }
  9967. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9968. Server svr;
  9969. svr.CustomRoute("POST", "/x",
  9970. [](const Request &, Response &, const ContentReader &) {});
  9971. EXPECT_FALSE(svr.is_valid());
  9972. }
  9973. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9974. Server svr;
  9975. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9976. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9977. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9978. EXPECT_FALSE(svr.is_valid());
  9979. }
  9980. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9981. Server svr;
  9982. auto captured = Error::Success;
  9983. svr.set_error_logger(
  9984. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9985. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9986. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9987. }
  9988. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9989. std::string out;
  9990. std::string request(
  9991. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9992. test_raw_request(request, &out);
  9993. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9994. }
  9995. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9996. std::string out;
  9997. std::string request(
  9998. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9999. test_raw_request(request, &out);
  10000. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10001. }
  10002. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10003. std::string out;
  10004. std::string request(
  10005. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10006. test_raw_request(request, &out);
  10007. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10008. }
  10009. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10010. std::string out;
  10011. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10012. "Host: localhost\r\n"
  10013. "Test: \r\n\r\n",
  10014. &out);
  10015. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10016. }
  10017. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10018. Server svr;
  10019. std::string x_custom;
  10020. std::string cookie;
  10021. std::string xff;
  10022. std::string x_unicode;
  10023. std::string x_iis;
  10024. svr.Get("/check", [&](const Request &req, Response &res) {
  10025. x_custom = req.get_header_value("X-Custom");
  10026. cookie = req.get_header_value("Cookie");
  10027. xff = req.get_header_value("X-Forwarded-For");
  10028. x_unicode = req.get_header_value("X-Unicode");
  10029. x_iis = req.get_header_value("X-IIS");
  10030. res.set_content("ok", "text/plain");
  10031. });
  10032. thread t = thread([&] { svr.listen(HOST, PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. t.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.wait_until_ready();
  10039. const std::string req = "GET /check HTTP/1.1\r\n"
  10040. "Host: localhost\r\n"
  10041. "X-Custom: a%0D%0AInjected: b\r\n"
  10042. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10043. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10044. "X-Unicode: %E3%81%82\r\n"
  10045. "X-IIS: %u00E9\r\n"
  10046. "Connection: close\r\n"
  10047. "\r\n";
  10048. std::string res;
  10049. ASSERT_TRUE(send_request(5, req, &res));
  10050. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10051. // Every value must be returned verbatim (wire form), with no decoding.
  10052. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10053. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10054. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10055. EXPECT_EQ("%E3%81%82", x_unicode);
  10056. EXPECT_EQ("%u00E9", x_iis);
  10057. }
  10058. // Applications that previously relied on automatic percent-decoding can
  10059. // reproduce the old behavior by explicitly calling decode_path_component()
  10060. // or, for RFC 3986 conformance, decode_uri_component().
  10061. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10062. Server svr;
  10063. std::string decoded;
  10064. svr.Get("/check", [&](const Request &req, Response &res) {
  10065. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10066. res.set_content("ok", "text/plain");
  10067. });
  10068. thread t = thread([&] { svr.listen(HOST, PORT); });
  10069. auto se = detail::scope_exit([&] {
  10070. svr.stop();
  10071. t.join();
  10072. ASSERT_FALSE(svr.is_running());
  10073. });
  10074. svr.wait_until_ready();
  10075. const std::string req = "GET /check HTTP/1.1\r\n"
  10076. "Host: localhost\r\n"
  10077. "X-Custom: hello%20world\r\n"
  10078. "Connection: close\r\n"
  10079. "\r\n";
  10080. std::string res;
  10081. ASSERT_TRUE(send_request(5, req, &res));
  10082. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10083. EXPECT_EQ("hello world", decoded);
  10084. }
  10085. // Regression test for #2033. Browsers send Referer values that include
  10086. // percent-encoded characters such as %0A inside the URL. Decoding the
  10087. // header value would either trip the post-decode CR/LF/NUL guard (the
  10088. // original bug, returning 400) or, after that guard was relaxed, silently
  10089. // store a literal LF — both unacceptable. The wire form must round-trip.
  10090. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10091. Server svr;
  10092. std::string referer;
  10093. svr.Get("/check", [&](const Request &req, Response &res) {
  10094. referer = req.get_header_value("Referer");
  10095. res.set_content("ok", "text/plain");
  10096. });
  10097. thread t = thread([&] { svr.listen(HOST, PORT); });
  10098. auto se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. t.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. const std::string req = "GET /check HTTP/1.1\r\n"
  10105. "Host: localhost\r\n"
  10106. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10107. "Connection: close\r\n"
  10108. "\r\n";
  10109. std::string res;
  10110. ASSERT_TRUE(send_request(5, req, &res));
  10111. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10112. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10113. }
  10114. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10115. Server svr;
  10116. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10117. res.set_header("Cache-Control", "no-cache");
  10118. res.set_chunked_content_provider(
  10119. "text/event-stream", [](size_t offset, DataSink &sink) {
  10120. std::string s = "data:";
  10121. s += std::to_string(offset);
  10122. s += "\n\n";
  10123. auto ret = sink.write(s.data(), s.size());
  10124. EXPECT_TRUE(ret);
  10125. std::this_thread::sleep_for(std::chrono::seconds(1));
  10126. return true;
  10127. });
  10128. });
  10129. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10130. svr.wait_until_ready();
  10131. Client client(HOST, PORT);
  10132. const Headers headers = {{"Accept", "text/event-stream"}};
  10133. auto get_thread = std::thread([&client, &headers]() {
  10134. auto res = client.Get(
  10135. "/events", headers,
  10136. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10137. });
  10138. auto se = detail::scope_exit([&] {
  10139. svr.stop();
  10140. get_thread.join();
  10141. listen_thread.join();
  10142. ASSERT_FALSE(svr.is_running());
  10143. });
  10144. // Give GET time to get a few messages.
  10145. std::this_thread::sleep_for(std::chrono::seconds(2));
  10146. }
  10147. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10148. httplib::Server svr;
  10149. svr.Post("/hi",
  10150. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10151. res.status = StatusCode::OK_200;
  10152. });
  10153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10154. svr.wait_until_ready();
  10155. Client cli(HOST, PORT);
  10156. auto res = cli.Post("/hi", "data", "text/plain");
  10157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10158. EXPECT_EQ(StatusCode::OK_200, res->status);
  10159. svr.stop();
  10160. thread.join();
  10161. ASSERT_FALSE(svr.is_running());
  10162. res = cli.Post("/hi", "data", "text/plain");
  10163. ASSERT_FALSE(res);
  10164. }
  10165. TEST(ServerStopTest, ListenFailure) {
  10166. Server svr;
  10167. auto t = thread([&]() {
  10168. auto ret = svr.listen("????", PORT);
  10169. EXPECT_FALSE(ret);
  10170. });
  10171. svr.wait_until_ready();
  10172. svr.stop();
  10173. t.join();
  10174. }
  10175. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10176. TEST(ServerStopTest, Decommision) {
  10177. Server svr;
  10178. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10179. for (int i = 0; i < 4; i++) {
  10180. auto is_even = !(i % 2);
  10181. std::thread t{[&] {
  10182. try {
  10183. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10184. if (is_even) {
  10185. throw std::runtime_error("Some thing that happens to go wrong.");
  10186. }
  10187. svr.listen(HOST, PORT);
  10188. } catch (...) { svr.decommission(); }
  10189. }};
  10190. svr.wait_until_ready();
  10191. // Server is up
  10192. {
  10193. Client cli(HOST, PORT);
  10194. auto res = cli.Get("/hi");
  10195. if (is_even) {
  10196. EXPECT_FALSE(res);
  10197. } else {
  10198. EXPECT_TRUE(res);
  10199. EXPECT_EQ("hi...", res->body);
  10200. }
  10201. }
  10202. svr.stop();
  10203. t.join();
  10204. // Server is down...
  10205. {
  10206. Client cli(HOST, PORT);
  10207. auto res = cli.Get("/hi");
  10208. EXPECT_FALSE(res);
  10209. }
  10210. }
  10211. }
  10212. #endif
  10213. // Helper function for string body upload progress tests
  10214. template <typename SetupHandler, typename ClientCall>
  10215. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10216. ClientCall &&client_call,
  10217. const string &body) {
  10218. Server svr;
  10219. setup_handler(svr);
  10220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10221. auto se = detail::scope_exit([&] {
  10222. svr.stop();
  10223. t.join();
  10224. });
  10225. svr.wait_until_ready();
  10226. Client cli(HOST, PORT);
  10227. vector<uint64_t> progress_values;
  10228. bool progress_called = false;
  10229. auto res =
  10230. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10231. progress_values.push_back(current);
  10232. progress_called = true;
  10233. return true;
  10234. });
  10235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10236. EXPECT_EQ(200, res->status);
  10237. EXPECT_TRUE(progress_called);
  10238. }
  10239. TEST(UploadProgressTest, PostStringBodyBasic) {
  10240. TestStringBodyUploadProgress(
  10241. [](Server &svr) {
  10242. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10243. res.set_content("received", "text/plain");
  10244. });
  10245. },
  10246. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10247. return cli.Post("/test", body, "text/plain", progress_callback);
  10248. },
  10249. "test data for upload progress");
  10250. }
  10251. TEST(UploadProgressTest, PutStringBodyBasic) {
  10252. TestStringBodyUploadProgress(
  10253. [](Server &svr) {
  10254. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10255. res.set_content("put received", "text/plain");
  10256. });
  10257. },
  10258. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10259. return cli.Put("/test", body, "text/plain", progress_callback);
  10260. },
  10261. "put test data for upload progress");
  10262. }
  10263. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10264. TestStringBodyUploadProgress(
  10265. [](Server &svr) {
  10266. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10267. res.set_content("patch received", "text/plain");
  10268. });
  10269. },
  10270. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10271. return cli.Patch("/test", body, "text/plain", progress_callback);
  10272. },
  10273. "patch test data for upload progress");
  10274. }
  10275. // Helper function for content provider upload progress tests
  10276. template <typename SetupHandler, typename ClientCall>
  10277. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10278. ClientCall &&client_call) {
  10279. Server svr;
  10280. setup_handler(svr);
  10281. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10282. auto se = detail::scope_exit([&] {
  10283. svr.stop();
  10284. t.join();
  10285. });
  10286. svr.wait_until_ready();
  10287. Client cli(HOST, PORT);
  10288. vector<uint64_t> progress_values;
  10289. auto res =
  10290. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10291. progress_values.push_back(current);
  10292. return true;
  10293. });
  10294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10295. EXPECT_EQ(200, res->status);
  10296. EXPECT_FALSE(progress_values.empty());
  10297. }
  10298. TEST(UploadProgressTest, PostContentProviderProgress) {
  10299. TestContentProviderUploadProgress(
  10300. [](Server &svr) {
  10301. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10302. res.set_content("provider received", "text/plain");
  10303. });
  10304. },
  10305. [](Client &cli, UploadProgress progress_callback) {
  10306. return cli.Post(
  10307. "/test", 9,
  10308. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10309. sink.os << "test data";
  10310. return true;
  10311. },
  10312. "text/plain", progress_callback);
  10313. });
  10314. }
  10315. // Helper function for multipart upload progress tests
  10316. template <typename SetupHandler, typename ClientCall>
  10317. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10318. ClientCall &&client_call,
  10319. const string &endpoint) {
  10320. Server svr;
  10321. setup_handler(svr);
  10322. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. t.join();
  10326. });
  10327. svr.wait_until_ready();
  10328. Client cli(HOST, PORT);
  10329. vector<uint64_t> progress_values;
  10330. UploadFormDataItems items = {
  10331. {"field1", "value1", "", ""},
  10332. {"field2", "longer value for progress tracking test", "", ""},
  10333. {"file1", "file content data for upload progress", "test.txt",
  10334. "text/plain"}};
  10335. auto res = client_call(cli, endpoint, items,
  10336. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10337. progress_values.push_back(current);
  10338. return true;
  10339. });
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. EXPECT_EQ(200, res->status);
  10342. EXPECT_FALSE(progress_values.empty());
  10343. }
  10344. TEST(UploadProgressTest, PostMultipartProgress) {
  10345. TestMultipartUploadProgress(
  10346. [](Server &svr) {
  10347. svr.Post("/multipart", [](const Request &req, Response &res) {
  10348. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10349. res.set_content("multipart received", "text/plain");
  10350. });
  10351. },
  10352. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10353. UploadProgress progress_callback) {
  10354. return cli.Post(endpoint, items, progress_callback);
  10355. },
  10356. "/multipart");
  10357. }
  10358. // Helper function for basic download progress tests
  10359. template <typename SetupHandler, typename ClientCall>
  10360. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10361. ClientCall &&client_call, const string &endpoint,
  10362. size_t expected_content_size) {
  10363. Server svr;
  10364. setup_handler(svr);
  10365. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10366. auto se = detail::scope_exit([&] {
  10367. svr.stop();
  10368. t.join();
  10369. });
  10370. svr.wait_until_ready();
  10371. Client cli(HOST, PORT);
  10372. vector<uint64_t> progress_values;
  10373. auto res = client_call(cli, endpoint,
  10374. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10375. progress_values.push_back(current);
  10376. return true;
  10377. });
  10378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10379. EXPECT_EQ(200, res->status);
  10380. EXPECT_FALSE(progress_values.empty());
  10381. EXPECT_EQ(expected_content_size, res->body.size());
  10382. }
  10383. TEST(DownloadProgressTest, GetBasic) {
  10384. TestBasicDownloadProgress(
  10385. [](Server &svr) {
  10386. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10387. string content(1000, 'D');
  10388. res.set_content(content, "text/plain");
  10389. });
  10390. },
  10391. [](Client &cli, const string &endpoint,
  10392. DownloadProgress progress_callback) {
  10393. return cli.Get(endpoint, progress_callback);
  10394. },
  10395. "/download", 1000u);
  10396. }
  10397. // Helper function for content receiver download progress tests
  10398. template <typename SetupHandler, typename ClientCall>
  10399. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10400. ClientCall &&client_call,
  10401. const string &endpoint,
  10402. size_t expected_content_size) {
  10403. Server svr;
  10404. setup_handler(svr);
  10405. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10406. auto se = detail::scope_exit([&] {
  10407. svr.stop();
  10408. t.join();
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, PORT);
  10412. vector<uint64_t> progress_values;
  10413. string received_body;
  10414. auto res = client_call(
  10415. cli, endpoint,
  10416. [&](const char *data, size_t data_length) -> bool {
  10417. received_body.append(data, data_length);
  10418. return true;
  10419. },
  10420. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10421. progress_values.push_back(current);
  10422. return true;
  10423. });
  10424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10425. EXPECT_EQ(200, res->status);
  10426. EXPECT_FALSE(progress_values.empty());
  10427. EXPECT_EQ(expected_content_size, received_body.size());
  10428. EXPECT_TRUE(res->body.empty());
  10429. }
  10430. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10431. TestContentReceiverDownloadProgress(
  10432. [](Server &svr) {
  10433. svr.Get("/download-receiver",
  10434. [](const Request & /*req*/, Response &res) {
  10435. string content(2000, 'R');
  10436. res.set_content(content, "text/plain");
  10437. });
  10438. },
  10439. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10440. DownloadProgress progress_callback) {
  10441. return cli.Get(endpoint, content_receiver, progress_callback);
  10442. },
  10443. "/download-receiver", 2000u);
  10444. }
  10445. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10446. // A provider reaching a pass with nothing to hand over - an empty buffer
  10447. // popped off a queue, say - must not be taken to mean the body is finished.
  10448. // It used to end the loop with the terminating chunk unwritten while the
  10449. // server still considered the response complete, so the peer waited for an
  10450. // end that never arrived.
  10451. Server svr;
  10452. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10453. auto step = std::make_shared<int>(0);
  10454. res.set_chunked_content_provider("text/plain",
  10455. [step](size_t /*offset*/, DataSink &sink) {
  10456. switch ((*step)++) {
  10457. case 0: sink.write("", 0); break;
  10458. case 1: sink.write("hello", 5); break;
  10459. default: sink.done(); break;
  10460. }
  10461. return true;
  10462. });
  10463. });
  10464. auto port = svr.bind_to_any_port(HOST);
  10465. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10466. auto listen_se = detail::scope_exit([&] {
  10467. svr.stop();
  10468. listen_thread.join();
  10469. ASSERT_FALSE(svr.is_running());
  10470. });
  10471. svr.wait_until_ready();
  10472. Client cli(HOST, port);
  10473. // Without the fix the body is never terminated, so bound the wait rather
  10474. // than letting the test hang on the default read timeout.
  10475. cli.set_read_timeout(5, 0);
  10476. auto res = cli.Get("/stream");
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. EXPECT_EQ("hello", res->body);
  10480. }
  10481. TEST(StreamingTest, NoContentLengthStreaming) {
  10482. Server svr;
  10483. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10484. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10485. if (offset < 6) {
  10486. sink.os << (offset < 3 ? "a" : "b");
  10487. } else {
  10488. sink.done();
  10489. }
  10490. return true;
  10491. });
  10492. });
  10493. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10494. auto listen_se = detail::scope_exit([&] {
  10495. svr.stop();
  10496. listen_thread.join();
  10497. ASSERT_FALSE(svr.is_running());
  10498. });
  10499. svr.wait_until_ready();
  10500. Client client(HOST, PORT);
  10501. auto get_thread = std::thread([&client]() {
  10502. std::string s;
  10503. auto res =
  10504. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10505. s += std::string(data, len);
  10506. return true;
  10507. });
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(StatusCode::OK_200, res->status);
  10510. EXPECT_EQ("aaabbb", s);
  10511. });
  10512. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10513. // Give GET time to get a few messages.
  10514. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10515. }
  10516. TEST(MountTest, Unmount) {
  10517. Server svr;
  10518. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10519. auto se = detail::scope_exit([&] {
  10520. svr.stop();
  10521. listen_thread.join();
  10522. ASSERT_FALSE(svr.is_running());
  10523. });
  10524. svr.wait_until_ready();
  10525. Client cli("localhost", PORT);
  10526. svr.set_mount_point("/mount2", "./www2");
  10527. auto res = cli.Get("/");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10530. res = cli.Get("/mount2/dir/test.html");
  10531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10532. EXPECT_EQ(StatusCode::OK_200, res->status);
  10533. svr.set_mount_point("/", "./www");
  10534. res = cli.Get("/dir/");
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(StatusCode::OK_200, res->status);
  10537. svr.remove_mount_point("/");
  10538. res = cli.Get("/dir/");
  10539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10541. svr.remove_mount_point("/mount2");
  10542. res = cli.Get("/mount2/dir/test.html");
  10543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10545. }
  10546. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10547. Server svr;
  10548. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10549. svr.Get("/api/hello", [](const Request &, Response &res) {
  10550. res.set_content("api", "text/plain");
  10551. });
  10552. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. listen_thread.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. });
  10558. svr.wait_until_ready();
  10559. Client cli(HOST, PORT);
  10560. auto res = cli.Get("/dir/test.html");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. res = cli.Get("/api/hello");
  10564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10565. EXPECT_EQ(StatusCode::OK_200, res->status);
  10566. EXPECT_EQ("api", res->body);
  10567. }
  10568. TEST(MountTest, PathSegmentBoundary) {
  10569. Server svr;
  10570. svr.set_mount_point("/mount2", "./www2");
  10571. svr.set_mount_point("/", "./www");
  10572. auto port = svr.bind_to_any_port(HOST);
  10573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10574. auto se = detail::scope_exit([&] {
  10575. svr.stop();
  10576. listen_thread.join();
  10577. ASSERT_FALSE(svr.is_running());
  10578. });
  10579. svr.wait_until_ready();
  10580. Client cli(HOST, port);
  10581. auto res = cli.Get("/mount2/dir/test.html");
  10582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10583. EXPECT_EQ(StatusCode::OK_200, res->status);
  10584. // "/mount2" must not match part-way through a path segment.
  10585. res = cli.Get("/mount2dir/test.html");
  10586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10588. // A mount point ending in '/' keeps matching every path below it.
  10589. res = cli.Get("/dir/test.html");
  10590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10591. EXPECT_EQ(StatusCode::OK_200, res->status);
  10592. }
  10593. TEST(MountTest, Redicect) {
  10594. Server svr;
  10595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10596. auto se = detail::scope_exit([&] {
  10597. svr.stop();
  10598. listen_thread.join();
  10599. ASSERT_FALSE(svr.is_running());
  10600. });
  10601. svr.set_mount_point("/", "./www");
  10602. svr.wait_until_ready();
  10603. Client cli("localhost", PORT);
  10604. auto res = cli.Get("/dir/");
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. EXPECT_EQ(StatusCode::OK_200, res->status);
  10607. res = cli.Get("/dir");
  10608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10609. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10610. res = cli.Get("/file");
  10611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10612. EXPECT_EQ(StatusCode::OK_200, res->status);
  10613. res = cli.Get("/file/");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10616. cli.set_follow_location(true);
  10617. res = cli.Get("/dir");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ(StatusCode::OK_200, res->status);
  10620. }
  10621. TEST(MountTest, MultibytesPathName) {
  10622. Server svr;
  10623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10624. auto se = detail::scope_exit([&] {
  10625. svr.stop();
  10626. listen_thread.join();
  10627. ASSERT_FALSE(svr.is_running());
  10628. });
  10629. svr.set_mount_point("/", "./www");
  10630. svr.wait_until_ready();
  10631. Client cli("localhost", PORT);
  10632. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10634. EXPECT_EQ(StatusCode::OK_200, res->status);
  10635. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10636. }
  10637. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10638. // in the pre-routing handler sees the path of every file that is served
  10639. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10640. Server svr;
  10641. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10642. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10643. if (req.path == "/dir/test.html") {
  10644. res.status = StatusCode::Unauthorized_401;
  10645. return Server::HandlerResponse::Handled;
  10646. }
  10647. return Server::HandlerResponse::Unhandled;
  10648. });
  10649. auto port = svr.bind_to_any_port(HOST);
  10650. ASSERT_LT(0, port);
  10651. thread t = thread([&] { svr.listen_after_bind(); });
  10652. auto se = detail::scope_exit([&] {
  10653. svr.stop();
  10654. t.join();
  10655. ASSERT_FALSE(svr.is_running());
  10656. });
  10657. svr.wait_until_ready();
  10658. Client cli(HOST, port);
  10659. for (auto path :
  10660. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10661. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10662. SCOPED_TRACE(path);
  10663. auto res = cli.Get(path);
  10664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10665. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10666. }
  10667. }
  10668. #ifdef _WIN32
  10669. // Issue #2435: mmap::open() must succeed even when another handle holds
  10670. // the file open for writing (e.g. an active log file).
  10671. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10672. const char *path = "mmap_concurrent_writer_test.txt";
  10673. const char *content = "hello";
  10674. {
  10675. std::ofstream f(path, std::ios::binary);
  10676. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10677. }
  10678. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10679. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10680. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10681. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10682. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10683. detail::mmap m(path);
  10684. ASSERT_TRUE(m.is_open());
  10685. EXPECT_EQ(strlen(content), m.size());
  10686. char buf[8];
  10687. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10688. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10689. }
  10690. #endif
  10691. #ifndef _WIN32
  10692. // A directory or a device has no size to serve.
  10693. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10694. const char *path = "./mmap_not_regular_test_dir";
  10695. ASSERT_EQ(0, ::mkdir(path, 0755));
  10696. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10697. for (auto p : {path, "/dev/null"}) {
  10698. detail::mmap m(p);
  10699. EXPECT_FALSE(m.is_open()) << p;
  10700. EXPECT_EQ(0U, m.size()) << p;
  10701. }
  10702. Server svr;
  10703. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10704. res.set_file_content("/dev/null");
  10705. });
  10706. auto port = svr.bind_to_any_port(HOST);
  10707. thread t = thread([&] { svr.listen_after_bind(); });
  10708. auto se = detail::scope_exit([&] {
  10709. svr.stop();
  10710. t.join();
  10711. });
  10712. svr.wait_until_ready();
  10713. auto res = Client(HOST, port).Get("/null");
  10714. ASSERT_TRUE(res);
  10715. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10716. }
  10717. #endif
  10718. #ifdef __linux__
  10719. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10720. TEST(MmapTest, FileIsNotMapped) {
  10721. const char *path = "mmap_not_mapped_test.txt";
  10722. {
  10723. std::ofstream f(path, std::ios::binary);
  10724. f << "hello";
  10725. }
  10726. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10727. detail::mmap m(path);
  10728. ASSERT_TRUE(m.is_open());
  10729. std::ifstream maps("/proc/self/maps");
  10730. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10731. std::istreambuf_iterator<char>());
  10732. EXPECT_EQ(std::string::npos, mappings.find(path));
  10733. }
  10734. #endif
  10735. TEST(KeepAliveTest, ReadTimeout) {
  10736. Server svr;
  10737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10738. std::this_thread::sleep_for(std::chrono::seconds(2));
  10739. res.set_content("a", "text/plain");
  10740. });
  10741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10742. res.set_content("b", "text/plain");
  10743. });
  10744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. listen_thread.join();
  10748. ASSERT_FALSE(svr.is_running());
  10749. });
  10750. svr.wait_until_ready();
  10751. Client cli("localhost", PORT);
  10752. cli.set_keep_alive(true);
  10753. cli.set_read_timeout(std::chrono::seconds(1));
  10754. auto resa = cli.Get("/a");
  10755. ASSERT_FALSE(resa);
  10756. EXPECT_EQ(Error::Read, resa.error());
  10757. auto resb = cli.Get("/b");
  10758. ASSERT_TRUE(resb);
  10759. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10760. EXPECT_EQ("b", resb->body);
  10761. }
  10762. TEST(KeepAliveTest, MaxCount) {
  10763. size_t keep_alive_max_count = 3;
  10764. Server svr;
  10765. svr.set_keep_alive_max_count(keep_alive_max_count);
  10766. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10767. res.set_content("Hello World!", "text/plain");
  10768. });
  10769. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10770. auto se = detail::scope_exit([&] {
  10771. svr.stop();
  10772. listen_thread.join();
  10773. ASSERT_FALSE(svr.is_running());
  10774. });
  10775. svr.wait_until_ready();
  10776. Client cli(HOST, PORT);
  10777. cli.set_keep_alive(true);
  10778. for (size_t i = 0; i < 5; i++) {
  10779. auto result = cli.Get("/hi");
  10780. ASSERT_TRUE(result);
  10781. EXPECT_EQ(StatusCode::OK_200, result->status);
  10782. if (i == keep_alive_max_count - 1) {
  10783. EXPECT_EQ("close", result->get_header_value("Connection"));
  10784. } else {
  10785. EXPECT_FALSE(result->has_header("Connection"));
  10786. }
  10787. }
  10788. }
  10789. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10790. // can pull the next one into the server's buffer. The server must serve it
  10791. // without waiting for the socket to become readable again. The keep-alive
  10792. // timeout outlasts the client's read timeout, so a request left waiting for it
  10793. // shows up as a missing response.
  10794. static void serve_pipelining_routes(Server &svr,
  10795. const std::function<void(int)> &client) {
  10796. svr.set_keep_alive_timeout(5);
  10797. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10798. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10799. });
  10800. svr.Post("/echo", [](const Request &req, Response &res) {
  10801. res.set_content("echo " + req.body, "text/plain");
  10802. });
  10803. auto port = svr.bind_to_any_port(HOST);
  10804. thread t = thread([&] { svr.listen_after_bind(); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. t.join();
  10808. });
  10809. svr.wait_until_ready();
  10810. client(port);
  10811. }
  10812. static std::string
  10813. send_pipelined_requests(const std::vector<std::string> &parts) {
  10814. Server svr;
  10815. std::string res;
  10816. serve_pipelining_routes(svr, [&](int port) {
  10817. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10818. });
  10819. return res;
  10820. }
  10821. static void expect_in_order(const std::string &res,
  10822. const std::vector<std::string> &bodies) {
  10823. size_t pos = 0;
  10824. for (const auto &body : bodies) {
  10825. pos = res.find(body, pos);
  10826. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10827. pos += body.size();
  10828. }
  10829. }
  10830. TEST(KeepAliveTest, PipelinedRequests) {
  10831. auto res = send_pipelined_requests(
  10832. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10833. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10834. "Content-Length: 4\r\n\r\nbody"
  10835. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10836. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10837. }
  10838. // The second request starts in the server's buffer and ends on the socket.
  10839. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10840. auto res =
  10841. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10842. "GET /hi/2 HTTP/1.1\r\nHo",
  10843. "st: localhost\r\nConnection: close\r\n\r\n"});
  10844. expect_in_order(res, {"hi 1", "hi 2"});
  10845. }
  10846. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10847. // CRLF after a body does not turn into a 400 for the next request.
  10848. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10849. auto res = send_pipelined_requests(
  10850. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10851. "Content-Length: 4\r\n\r\nbody\r\n"
  10852. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10853. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10854. expect_in_order(res, {"echo body", "hi 2"});
  10855. }
  10856. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10857. // must not be served as the next request.
  10858. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10859. auto res = send_pipelined_requests(
  10860. {"INVALID REQUEST LINE\r\n\r\n"
  10861. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10862. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10863. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10864. }
  10865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10866. // Over TLS, the next request is held by the TLS library as already decrypted
  10867. // data rather than on the socket.
  10868. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. std::string res;
  10871. serve_pipelining_routes(svr, [&](int port) {
  10872. // One part, so all three requests arrive in one TLS record
  10873. EXPECT_TRUE(send_ssl_request_in_parts(
  10874. 2,
  10875. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10876. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10877. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10878. &res, port));
  10879. });
  10880. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10881. }
  10882. #endif
  10883. TEST(KeepAliveTest, Issue1041) {
  10884. Server svr;
  10885. svr.set_keep_alive_timeout(3);
  10886. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10887. res.set_content("Hello World!", "text/plain");
  10888. });
  10889. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10890. auto se = detail::scope_exit([&] {
  10891. svr.stop();
  10892. listen_thread.join();
  10893. ASSERT_FALSE(svr.is_running());
  10894. });
  10895. svr.wait_until_ready();
  10896. Client cli(HOST, PORT);
  10897. cli.set_keep_alive(true);
  10898. auto result = cli.Get("/hi");
  10899. ASSERT_TRUE(result);
  10900. EXPECT_EQ(StatusCode::OK_200, result->status);
  10901. std::this_thread::sleep_for(std::chrono::seconds(5));
  10902. result = cli.Get("/hi");
  10903. ASSERT_TRUE(result);
  10904. EXPECT_EQ(StatusCode::OK_200, result->status);
  10905. }
  10906. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10907. Server svr;
  10908. svr.set_keep_alive_max_count(0);
  10909. std::set<int> remote_ports;
  10910. svr.Get("/hi", [&](const Request &req, Response &res) {
  10911. remote_ports.insert(req.remote_port);
  10912. res.set_content("hi", "text/plain");
  10913. });
  10914. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10915. auto se = detail::scope_exit([&] {
  10916. svr.stop();
  10917. listen_thread.join();
  10918. ASSERT_FALSE(svr.is_running());
  10919. });
  10920. svr.wait_until_ready();
  10921. Client cli(HOST, PORT);
  10922. cli.set_keep_alive(true);
  10923. for (int i = 0; i < 3; i++) {
  10924. auto res = cli.Get("/hi");
  10925. ASSERT_TRUE(res);
  10926. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10927. }
  10928. // All three over one connection
  10929. EXPECT_EQ(1u, remote_ports.size());
  10930. }
  10931. TEST(KeepAliveTest, Issue1959) {
  10932. Server svr;
  10933. svr.set_keep_alive_timeout(5);
  10934. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10935. res.set_content("a", "text/plain");
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. if (!svr.is_running()) return;
  10940. svr.stop();
  10941. listen_thread.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. Client cli("localhost", PORT);
  10946. cli.set_keep_alive(true);
  10947. using namespace std::chrono;
  10948. auto start = steady_clock::now();
  10949. cli.Get("/a");
  10950. svr.stop();
  10951. listen_thread.join();
  10952. auto end = steady_clock::now();
  10953. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10954. EXPECT_LT(elapsed, 5000);
  10955. }
  10956. #ifdef CPPHTTPLIB_SSL_ENABLED
  10957. TEST(KeepAliveTest, SSLClientReconnection) {
  10958. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10959. ASSERT_TRUE(svr.is_valid());
  10960. svr.set_keep_alive_timeout(1);
  10961. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10962. res.set_content("Hello World!", "text/plain");
  10963. });
  10964. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. listen_thread.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. SSLClient cli(HOST, PORT);
  10972. cli.enable_server_certificate_verification(false);
  10973. cli.set_keep_alive(true);
  10974. auto result = cli.Get("/hi");
  10975. ASSERT_TRUE(result);
  10976. EXPECT_EQ(StatusCode::OK_200, result->status);
  10977. result = cli.Get("/hi");
  10978. ASSERT_TRUE(result);
  10979. EXPECT_EQ(StatusCode::OK_200, result->status);
  10980. std::this_thread::sleep_for(std::chrono::seconds(2));
  10981. // Recoonect
  10982. result = cli.Get("/hi");
  10983. ASSERT_TRUE(result);
  10984. EXPECT_EQ(StatusCode::OK_200, result->status);
  10985. result = cli.Get("/hi");
  10986. ASSERT_TRUE(result);
  10987. EXPECT_EQ(StatusCode::OK_200, result->status);
  10988. }
  10989. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10991. ASSERT_TRUE(svr.is_valid());
  10992. svr.set_keep_alive_timeout(1);
  10993. std::string content = "reconnect";
  10994. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10995. res.set_content("Hello World!", "text/plain");
  10996. });
  10997. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. listen_thread.join();
  11001. ASSERT_FALSE(svr.is_running());
  11002. });
  11003. svr.wait_until_ready();
  11004. SSLClient cli(HOST, PORT);
  11005. cli.enable_server_certificate_verification(false);
  11006. cli.set_keep_alive(true);
  11007. auto result = cli.Post(
  11008. "/hi", content.size(),
  11009. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11010. sink.write(content.c_str(), content.size());
  11011. return true;
  11012. },
  11013. "text/plain");
  11014. ASSERT_TRUE(result);
  11015. EXPECT_EQ(200, result->status);
  11016. std::this_thread::sleep_for(std::chrono::seconds(2));
  11017. // Recoonect
  11018. result = cli.Post(
  11019. "/hi", content.size(),
  11020. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11021. sink.write(content.c_str(), content.size());
  11022. return true;
  11023. },
  11024. "text/plain");
  11025. ASSERT_TRUE(result);
  11026. EXPECT_EQ(200, result->status);
  11027. result = cli.Post(
  11028. "/hi", content.size(),
  11029. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11030. sink.write(content.c_str(), content.size());
  11031. return true;
  11032. },
  11033. "text/plain");
  11034. ASSERT_TRUE(result);
  11035. EXPECT_EQ(200, result->status);
  11036. }
  11037. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11038. using namespace httplib::tls;
  11039. {
  11040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11041. ASSERT_TRUE(svr.is_valid());
  11042. svr.Get("/sni", [&](const Request &req, Response &res) {
  11043. std::string expected = req.sni();
  11044. EXPECT_EQ(expected, req.get_param_value("expected"));
  11045. res.set_content("ok", "text/plain");
  11046. });
  11047. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. listen_thread.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. {
  11055. SSLClient cli("localhost", PORT);
  11056. cli.enable_server_certificate_verification(false);
  11057. auto res = cli.Get("/sni?expected=localhost");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. }
  11060. {
  11061. SSLClient cli("::1", PORT);
  11062. cli.enable_server_certificate_verification(false);
  11063. auto res = cli.Get("/sni?expected=");
  11064. // NOTE: This may fail if the server is listening on IPv4 only
  11065. // (e.g., when localhost resolves to 127.0.0.1 only)
  11066. if (res) {
  11067. EXPECT_EQ(StatusCode::OK_200, res->status);
  11068. } else {
  11069. EXPECT_EQ(Error::Connection, res.error());
  11070. }
  11071. }
  11072. }
  11073. }
  11074. // The SNI of a failed handshake does not reach the next connection that the
  11075. // same worker thread serves
  11076. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11078. ASSERT_TRUE(svr.is_valid());
  11079. svr.new_task_queue = [] { return new ThreadPool(1); };
  11080. svr.Get("/sni", [](const Request &req, Response &res) {
  11081. res.set_content(req.sni(), "text/plain");
  11082. });
  11083. auto port = svr.bind_to_any_port("127.0.0.1");
  11084. ASSERT_LT(0, port);
  11085. thread t = thread([&] { svr.listen_after_bind(); });
  11086. auto se = detail::scope_exit([&] {
  11087. svr.stop();
  11088. t.join();
  11089. ASSERT_FALSE(svr.is_running());
  11090. });
  11091. svr.wait_until_ready();
  11092. {
  11093. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11094. SSLClient cli("localhost", port);
  11095. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11096. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11097. auto res = cli.Get("/sni");
  11098. ASSERT_FALSE(res);
  11099. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11100. }
  11101. // An IP host sends no SNI (RFC 6066)
  11102. SSLClient cli("127.0.0.1", port);
  11103. cli.enable_server_certificate_verification(false);
  11104. auto res = cli.Get("/sni");
  11105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11106. EXPECT_EQ("", res->body);
  11107. }
  11108. #endif
  11109. TEST(ClientProblemDetectionTest, ContentProvider) {
  11110. Server svr;
  11111. size_t content_length = 1024 * 1024;
  11112. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11113. res.set_content_provider(
  11114. content_length, "text/plain",
  11115. [&](size_t offset, size_t length, DataSink &sink) {
  11116. auto out_len = std::min(length, static_cast<size_t>(1024));
  11117. std::string out(out_len, '@');
  11118. sink.write(out.data(), out_len);
  11119. return offset < 4096;
  11120. },
  11121. [](bool success) { ASSERT_FALSE(success); });
  11122. });
  11123. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11124. res.set_content_provider(
  11125. 0, "text/plain",
  11126. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11127. EXPECT_TRUE(false);
  11128. return true;
  11129. },
  11130. [](bool success) { ASSERT_FALSE(success); });
  11131. });
  11132. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11133. auto se = detail::scope_exit([&] {
  11134. svr.stop();
  11135. listen_thread.join();
  11136. ASSERT_FALSE(svr.is_running());
  11137. });
  11138. svr.wait_until_ready();
  11139. Client cli("localhost", PORT);
  11140. {
  11141. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11142. size_t /*data_length*/) { return false; });
  11143. ASSERT_FALSE(res);
  11144. }
  11145. {
  11146. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11147. size_t /*data_length*/) { return false; });
  11148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11149. }
  11150. }
  11151. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11152. // A provider that reports success without writing anything and without
  11153. // calling done() used to be handed the same offset and length again on every
  11154. // pass, so it spun for as long as the peer stayed connected.
  11155. Server svr;
  11156. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11157. res.set_content("ok", "text/plain");
  11158. });
  11159. auto port = svr.bind_to_any_port(HOST);
  11160. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11161. auto se = detail::scope_exit([&] {
  11162. svr.stop();
  11163. listen_thread.join();
  11164. ASSERT_FALSE(svr.is_running());
  11165. });
  11166. svr.wait_until_ready();
  11167. std::atomic<int> call_count{0};
  11168. Client cli(HOST, port);
  11169. auto res = cli.Post(
  11170. "/", 1024,
  11171. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11172. // Give up after enough passes to show the spin, so that losing the
  11173. // check below fails this test instead of hanging it.
  11174. return ++call_count < 100;
  11175. },
  11176. "text/plain");
  11177. ASSERT_FALSE(res);
  11178. EXPECT_EQ(Error::Write, res.error());
  11179. EXPECT_EQ(1, call_count.load());
  11180. }
  11181. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11182. // A writer only has to assign `write`. The other three used to be left as
  11183. // empty std::functions, so a provider calling one threw
  11184. // std::bad_function_call out of the thread running it and took the whole
  11185. // process down.
  11186. DataSink sink;
  11187. std::string written;
  11188. sink.write = [&](const char *data, size_t data_len) {
  11189. written.append(data, data_len);
  11190. return true;
  11191. };
  11192. EXPECT_TRUE(sink.is_writable());
  11193. sink.done();
  11194. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11195. EXPECT_TRUE(written.empty());
  11196. }
  11197. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11198. // A sink that cannot carry trailers still has to finish.
  11199. DataSink sink;
  11200. auto done_count = 0;
  11201. sink.done = [&]() { done_count++; };
  11202. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11203. EXPECT_EQ(1, done_count);
  11204. }
  11205. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11206. Server svr;
  11207. const std::string body(4096, 'x');
  11208. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11209. res.set_content_provider(body.size(), "text/plain",
  11210. [&](size_t offset, size_t length, DataSink &sink) {
  11211. sink.write(body.data() + offset, length);
  11212. sink.done();
  11213. return true;
  11214. });
  11215. });
  11216. auto port = svr.bind_to_any_port(HOST);
  11217. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11218. auto se = detail::scope_exit([&] {
  11219. svr.stop();
  11220. listen_thread.join();
  11221. ASSERT_FALSE(svr.is_running());
  11222. });
  11223. svr.wait_until_ready();
  11224. Client cli(HOST, port);
  11225. auto res = cli.Get("/");
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_EQ(StatusCode::OK_200, res->status);
  11228. EXPECT_EQ(body, res->body);
  11229. }
  11230. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11231. Server svr;
  11232. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11233. res.set_content_provider(
  11234. 1024, "text/plain",
  11235. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11236. sink.write("hello", 5);
  11237. sink.done(); // short of the 1024 bytes the response promised
  11238. return true;
  11239. });
  11240. });
  11241. auto port = svr.bind_to_any_port(HOST);
  11242. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11243. auto se = detail::scope_exit([&] {
  11244. svr.stop();
  11245. listen_thread.join();
  11246. ASSERT_FALSE(svr.is_running());
  11247. });
  11248. svr.wait_until_ready();
  11249. Client cli(HOST, port);
  11250. cli.set_read_timeout(5, 0);
  11251. // The response is short of its Content-Length, so the client cannot read a
  11252. // complete body. What matters is that this returns at all: a no-op done()
  11253. // would leave the writer looping over a provider that never makes progress.
  11254. auto res = cli.Get("/");
  11255. EXPECT_FALSE(res);
  11256. }
  11257. // Read as the next response by a peer that sees it after a framed body.
  11258. static const std::string smuggled_response =
  11259. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11260. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11261. Server svr;
  11262. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11263. res.set_content_provider(
  11264. 5, "text/plain",
  11265. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11266. auto data = "AAAAA" + smuggled_response;
  11267. sink.write(data.data(), data.size());
  11268. return true;
  11269. });
  11270. });
  11271. thread t = thread([&] { svr.listen(HOST, PORT); });
  11272. auto se = detail::scope_exit([&] {
  11273. svr.stop();
  11274. t.join();
  11275. ASSERT_FALSE(svr.is_running());
  11276. });
  11277. svr.wait_until_ready();
  11278. std::string resp;
  11279. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11280. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11281. resp.clear();
  11282. ASSERT_TRUE(send_request(
  11283. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11284. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11285. }
  11286. TEST(NoContentTest, BodyIsNotSent) {
  11287. Server svr;
  11288. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11289. res.status = StatusCode::NoContent_204;
  11290. res.set_content(smuggled_response, "text/plain");
  11291. });
  11292. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11293. res.status = StatusCode::NotModified_304;
  11294. res.set_chunked_content_provider(
  11295. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11296. sink.write(smuggled_response.data(), smuggled_response.size());
  11297. sink.done();
  11298. return true;
  11299. });
  11300. });
  11301. thread t = thread([&] { svr.listen(HOST, PORT); });
  11302. auto se = detail::scope_exit([&] {
  11303. svr.stop();
  11304. t.join();
  11305. ASSERT_FALSE(svr.is_running());
  11306. });
  11307. svr.wait_until_ready();
  11308. for (auto path : {"/204", "/304"}) {
  11309. std::string resp;
  11310. ASSERT_TRUE(send_request(
  11311. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11312. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11313. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11314. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11315. }
  11316. }
  11317. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11318. Server svr;
  11319. std::atomic<bool> smuggled(false);
  11320. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11321. res.set_content("ok", "text/plain");
  11322. });
  11323. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11324. smuggled = true;
  11325. });
  11326. auto port = svr.bind_to_any_port(HOST);
  11327. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. listen_thread.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. });
  11333. svr.wait_until_ready();
  11334. // What follows the body would be read as the next request.
  11335. Client cli(HOST, port);
  11336. auto res = cli.Post(
  11337. "/", 5,
  11338. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11339. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11340. sink.write(data.data(), data.size());
  11341. return true;
  11342. },
  11343. "text/plain");
  11344. ASSERT_FALSE(res);
  11345. EXPECT_EQ(Error::Write, res.error());
  11346. EXPECT_FALSE(smuggled);
  11347. }
  11348. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11349. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11350. // The compressed path builds the whole body before connecting, so this
  11351. // fails client-side and never reaches a server.
  11352. Client cli(HOST, PORT);
  11353. cli.set_compress(true);
  11354. auto res = cli.Post(
  11355. "/", 1024,
  11356. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11357. sink.write("hello", 5);
  11358. sink.done(); // short of the 1024 bytes the request announced
  11359. return true;
  11360. },
  11361. "text/plain");
  11362. ASSERT_FALSE(res);
  11363. EXPECT_EQ(Error::Write, res.error());
  11364. }
  11365. #endif
  11366. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11367. Server svr;
  11368. svr.set_error_handler([](Request const &, Response &res) -> void {
  11369. res.set_chunked_content_provider(
  11370. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11371. sink.os << "hello";
  11372. sink.os << "world";
  11373. sink.done();
  11374. return true;
  11375. });
  11376. });
  11377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. listen_thread.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. Client cli("localhost", PORT);
  11385. auto res = cli.Get("/");
  11386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11387. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11388. EXPECT_EQ("helloworld", res->body);
  11389. }
  11390. // A body set after a content provider must replace it, not be sent through it.
  11391. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11392. Server svr;
  11393. svr.set_mount_point("/", "./www");
  11394. svr.set_file_request_handler([](const Request &req, Response &res) {
  11395. if (req.path == "/dir/test.html") {
  11396. res.status = StatusCode::Forbidden_403;
  11397. res.set_content(std::string(5000, 'D'), "text/plain");
  11398. } else if (req.path == "/file") {
  11399. res.status = StatusCode::Forbidden_403;
  11400. res.body = "Denied";
  11401. }
  11402. });
  11403. auto port = svr.bind_to_any_port(HOST);
  11404. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11405. auto se = detail::scope_exit([&] {
  11406. svr.stop();
  11407. t.join();
  11408. ASSERT_FALSE(svr.is_running());
  11409. });
  11410. svr.wait_until_ready();
  11411. Client cli(HOST, port);
  11412. {
  11413. auto res = cli.Get("/dir/test.html");
  11414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11415. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11416. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11417. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11418. }
  11419. {
  11420. auto res = cli.Get("/file");
  11421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11422. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11423. EXPECT_EQ("Denied", res->body);
  11424. }
  11425. {
  11426. auto res = cli.Get("/dir/index.html");
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. EXPECT_EQ(StatusCode::OK_200, res->status);
  11429. EXPECT_EQ(0U, res->body.find("<html>"));
  11430. }
  11431. }
  11432. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11433. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11434. Server svr;
  11435. std::vector<bool> released;
  11436. std::mutex released_mutex;
  11437. auto releaser = [&](bool success) {
  11438. std::lock_guard<std::mutex> guard(released_mutex);
  11439. released.push_back(success);
  11440. };
  11441. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11442. return sink.write(&"hello"[offset], length);
  11443. };
  11444. svr.Get("/sized", [&](const Request &, Response &res) {
  11445. res.status = StatusCode::NotFound_404;
  11446. res.set_content_provider(5, "text/plain", provider, releaser);
  11447. });
  11448. svr.Get("/chunked", [&](const Request &, Response &res) {
  11449. res.status = StatusCode::ServiceUnavailable_503;
  11450. res.set_chunked_content_provider(
  11451. "text/plain",
  11452. [](size_t, DataSink &sink) {
  11453. sink.os << "chunk";
  11454. sink.done();
  11455. return true;
  11456. },
  11457. releaser);
  11458. });
  11459. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11460. res.set_content_provider(5, "text/plain", provider, releaser);
  11461. throw std::runtime_error("after the provider");
  11462. });
  11463. svr.set_error_handler([](const Request &req, Response &res) {
  11464. // Leave the exception handler's content to it.
  11465. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11466. res.set_content(std::string(1000, 'E'), "text/html");
  11467. return Server::HandlerResponse::Handled;
  11468. });
  11469. svr.set_exception_handler(
  11470. [](const Request &, Response &res, std::exception_ptr) {
  11471. res.status = StatusCode::InternalServerError_500;
  11472. res.set_content(std::string(1000, 'X'), "text/html");
  11473. });
  11474. auto port = svr.bind_to_any_port(HOST);
  11475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. Client cli(HOST, port);
  11483. {
  11484. auto res = cli.Get("/sized");
  11485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11487. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11488. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11489. }
  11490. {
  11491. auto res = cli.Get("/chunked");
  11492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11493. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11494. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11495. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11496. }
  11497. {
  11498. auto res = cli.Get("/throw");
  11499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11500. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11501. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11502. }
  11503. std::lock_guard<std::mutex> guard(released_mutex);
  11504. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11505. }
  11506. #endif
  11507. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11508. Server svr;
  11509. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11510. return sink.write(&"abc"[offset], length);
  11511. };
  11512. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11513. res.set_file_content("./www/dir/test.html");
  11514. res.set_content("body", "text/plain");
  11515. });
  11516. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11517. res.set_content(std::string(100, 'B'), "text/plain");
  11518. res.set_file_content("./www/dir/test.html");
  11519. });
  11520. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11521. res.set_content(std::string(100, 'B'), "text/plain");
  11522. res.set_content_provider(3, "text/x-provider", abc);
  11523. });
  11524. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11525. res.set_content_provider(3, "text/x-provider", abc);
  11526. res.set_content(std::string(100, 'B'), "text/plain");
  11527. });
  11528. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11529. res.set_content_provider(3, "text/x-provider", abc);
  11530. res.set_file_content("./www/dir/test.html", "text/x-file");
  11531. });
  11532. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11533. res.set_file_content("./www/dir/test.html");
  11534. res.set_header("Content-Type", "text/x-handler");
  11535. });
  11536. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11537. res.set_content_provider(3, "text/plain", abc);
  11538. res.body = "direct";
  11539. });
  11540. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11541. res.set_file_content("./www/dir/test.html");
  11542. res.body = "direct";
  11543. });
  11544. auto port = svr.bind_to_any_port(HOST);
  11545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11546. auto se = detail::scope_exit([&] {
  11547. svr.stop();
  11548. t.join();
  11549. ASSERT_FALSE(svr.is_running());
  11550. });
  11551. svr.wait_until_ready();
  11552. Client cli(HOST, port);
  11553. auto expect_body = [&](const char *path, const std::string &body,
  11554. const std::string &type) {
  11555. // Uncompressed, so Content-Length can be compared with the body.
  11556. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11557. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11558. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11559. EXPECT_EQ(body, res->body) << path;
  11560. EXPECT_EQ(std::to_string(body.size()),
  11561. res->get_header_value("Content-Length"))
  11562. << path;
  11563. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11564. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11565. };
  11566. expect_body("/file-then-body", "body", "text/plain");
  11567. expect_body("/body-then-file", "test.html", "text/html");
  11568. expect_body("/body-then-provider", "abc", "text/x-provider");
  11569. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11570. expect_body("/provider-then-file", "test.html", "text/x-file");
  11571. expect_body("/file-then-header", "test.html", "text/x-handler");
  11572. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11573. expect_body("/file-then-direct-body", "direct", "text/plain");
  11574. // Ranges are checked against the body, not the dropped provider.
  11575. {
  11576. auto res = cli.Get("/provider-then-direct-body",
  11577. Headers{{make_range_header({{1, 2}})}});
  11578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11580. EXPECT_EQ("ir", res->body);
  11581. }
  11582. {
  11583. auto res = cli.Get("/file-then-direct-body",
  11584. Headers{{make_range_header({{7, 8}})}});
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11587. }
  11588. }
  11589. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11590. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11591. const char *path = "./truncated_while_served.txt";
  11592. const size_t size = 32 * 1024 * 1024;
  11593. {
  11594. std::ofstream f(path, std::ios::binary);
  11595. f << std::string(size, 'x');
  11596. }
  11597. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11598. // Over TLS, where the bytes are encrypted in this process rather than
  11599. // copied by send().
  11600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11601. svr.Get("/file", [&](const Request &, Response &res) {
  11602. res.set_file_content(path, "text/plain");
  11603. });
  11604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11605. auto se = detail::scope_exit([&] {
  11606. svr.stop();
  11607. thread.join();
  11608. ASSERT_FALSE(svr.is_running());
  11609. });
  11610. svr.wait_until_ready();
  11611. // The file shrinks once the first bytes are in, as a rewrite in place
  11612. // would, and reading the mapping past its new end used to raise SIGBUS.
  11613. SSLClient cli(HOST, PORT);
  11614. cli.enable_server_certificate_verification(false);
  11615. size_t received = 0;
  11616. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11617. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11618. received += len;
  11619. return true;
  11620. });
  11621. EXPECT_FALSE(res);
  11622. EXPECT_LT(received, size);
  11623. }
  11624. #endif
  11625. // Forward declaration (see the base64_encode note).
  11626. namespace httplib {
  11627. namespace detail {
  11628. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11629. const std::string &content_type,
  11630. EncodingType encoding);
  11631. } // namespace detail
  11632. } // namespace httplib
  11633. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11634. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11635. ASSERT_TRUE(mm->is_open());
  11636. Response res;
  11637. detail::set_file_content_provider(res, mm, "text/html",
  11638. detail::EncodingType::None);
  11639. std::string out;
  11640. DataSink sink;
  11641. sink.write = [&](const char *d, size_t l) {
  11642. out.append(d, l);
  11643. return true;
  11644. };
  11645. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11646. EXPECT_EQ("test.html", out);
  11647. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11648. EXPECT_EQ("test.html", out);
  11649. }
  11650. TEST(LongPollingTest, ClientCloseDetection) {
  11651. Server svr;
  11652. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11653. res.set_chunked_content_provider(
  11654. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11655. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11656. sink.os << "hello";
  11657. auto count = 10;
  11658. while (count > 0 && sink.is_writable()) {
  11659. this_thread::sleep_for(chrono::milliseconds(10));
  11660. count--;
  11661. }
  11662. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11663. return true;
  11664. });
  11665. });
  11666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11667. auto se = detail::scope_exit([&] {
  11668. svr.stop();
  11669. listen_thread.join();
  11670. ASSERT_FALSE(svr.is_running());
  11671. });
  11672. svr.wait_until_ready();
  11673. Client cli("localhost", PORT);
  11674. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11675. EXPECT_EQ("hello", string(data, data_length));
  11676. return false; // close the socket immediately.
  11677. });
  11678. ASSERT_FALSE(res);
  11679. }
  11680. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11681. Server svr;
  11682. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11683. res.set_chunked_content_provider(
  11684. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11685. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11686. sink.os << "hello";
  11687. EXPECT_TRUE(sink.os.good());
  11688. // Wait for the client to close the connection
  11689. auto count = 10;
  11690. while (count > 0 && sink.is_writable()) {
  11691. this_thread::sleep_for(chrono::milliseconds(10));
  11692. count--;
  11693. }
  11694. // After client disconnect, write repeatedly until the socket
  11695. // write actually fails (small writes may be absorbed by the
  11696. // kernel buffer)
  11697. std::string chunk(1024, 'x');
  11698. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11699. sink.os << chunk;
  11700. }
  11701. EXPECT_TRUE(sink.os.fail());
  11702. return true;
  11703. });
  11704. });
  11705. auto port = svr.bind_to_any_port("localhost");
  11706. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11707. auto se = detail::scope_exit([&] {
  11708. svr.stop();
  11709. listen_thread.join();
  11710. ASSERT_FALSE(svr.is_running());
  11711. });
  11712. svr.wait_until_ready();
  11713. Client cli("localhost", port);
  11714. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11715. EXPECT_EQ("hello", string(data, data_length));
  11716. return false; // close the socket immediately.
  11717. });
  11718. ASSERT_FALSE(res);
  11719. }
  11720. TEST(GetWithParametersTest, GetWithParameters) {
  11721. Server svr;
  11722. svr.Get("/", [&](const Request &req, Response &) {
  11723. EXPECT_EQ("world", req.get_param_value("hello"));
  11724. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11725. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11726. });
  11727. svr.Get("/params", [&](const Request &req, Response &) {
  11728. EXPECT_EQ("world", req.get_param_value("hello"));
  11729. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11730. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11731. });
  11732. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11733. EXPECT_EQ("resource-id", req.matches[1]);
  11734. EXPECT_EQ("foo", req.get_param_value("param1"));
  11735. EXPECT_EQ("bar", req.get_param_value("param2"));
  11736. });
  11737. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11738. EXPECT_EQ("user-id", req.path_params.at("id"));
  11739. EXPECT_EQ("foo", req.get_param_value("param1"));
  11740. EXPECT_EQ("bar", req.get_param_value("param2"));
  11741. });
  11742. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11743. auto se = detail::scope_exit([&] {
  11744. svr.stop();
  11745. listen_thread.join();
  11746. ASSERT_FALSE(svr.is_running());
  11747. });
  11748. svr.wait_until_ready();
  11749. {
  11750. Client cli(HOST, PORT);
  11751. Params params;
  11752. params.emplace("hello", "world");
  11753. params.emplace("hello2", "world2");
  11754. params.emplace("hello3", "world3");
  11755. auto res = cli.Get("/", params, Headers{});
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. }
  11759. {
  11760. Client cli(HOST, PORT);
  11761. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11763. EXPECT_EQ(StatusCode::OK_200, res->status);
  11764. }
  11765. {
  11766. Client cli(HOST, PORT);
  11767. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11769. EXPECT_EQ(StatusCode::OK_200, res->status);
  11770. }
  11771. {
  11772. Client cli(HOST, PORT);
  11773. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11775. EXPECT_EQ(StatusCode::OK_200, res->status);
  11776. }
  11777. }
  11778. TEST(GetWithParametersTest, GetWithParameters2) {
  11779. Server svr;
  11780. svr.Get("/", [&](const Request &req, Response &res) {
  11781. auto text = req.get_param_value("hello");
  11782. res.set_content(text, "text/plain");
  11783. });
  11784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11785. auto se = detail::scope_exit([&] {
  11786. svr.stop();
  11787. listen_thread.join();
  11788. ASSERT_FALSE(svr.is_running());
  11789. });
  11790. svr.wait_until_ready();
  11791. Client cli("localhost", PORT);
  11792. Params params;
  11793. params.emplace("hello", "world");
  11794. std::string body;
  11795. auto res = cli.Get("/", params, Headers{},
  11796. [&](const char *data, size_t data_length) {
  11797. body.append(data, data_length);
  11798. return true;
  11799. });
  11800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11801. EXPECT_EQ(StatusCode::OK_200, res->status);
  11802. EXPECT_EQ("world", body);
  11803. }
  11804. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11805. Server svr;
  11806. svr.Get("/search", [&](const Request &req, Response &res) {
  11807. auto q = req.get_param_value("q");
  11808. res.set_content(q, "text/plain");
  11809. });
  11810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11811. auto se = detail::scope_exit([&] {
  11812. svr.stop();
  11813. listen_thread.join();
  11814. ASSERT_FALSE(svr.is_running());
  11815. });
  11816. svr.wait_until_ready();
  11817. Client cli("localhost", PORT);
  11818. // Verify that Get(path, params) works without requiring Headers argument
  11819. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11821. EXPECT_EQ(StatusCode::OK_200, res->status);
  11822. EXPECT_EQ("cpp-httplib", res->body);
  11823. }
  11824. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11825. auto host = "httpbingo.org";
  11826. auto path = std::string{"/range/32"};
  11827. #ifdef CPPHTTPLIB_SSL_ENABLED
  11828. SSLClient cli(host);
  11829. #else
  11830. Client cli(host);
  11831. #endif
  11832. cli.set_default_headers({make_range_header({{1, 10}})});
  11833. cli.set_connection_timeout(5);
  11834. {
  11835. auto res = cli.Get(path);
  11836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11837. EXPECT_EQ("bcdefghijk", res->body);
  11838. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11839. }
  11840. {
  11841. auto res = cli.Get(path);
  11842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11843. EXPECT_EQ("bcdefghijk", res->body);
  11844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11845. }
  11846. }
  11847. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11848. Server svr;
  11849. svr.set_default_headers({{"Hello", "World"}});
  11850. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11851. res.set_content("ok", "text/plain");
  11852. });
  11853. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11854. auto se = detail::scope_exit([&] {
  11855. svr.stop();
  11856. listen_thread.join();
  11857. ASSERT_FALSE(svr.is_running());
  11858. });
  11859. svr.wait_until_ready();
  11860. Client cli("localhost", PORT);
  11861. auto res = cli.Get("/");
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. EXPECT_EQ(StatusCode::OK_200, res->status);
  11864. EXPECT_EQ("ok", res->body);
  11865. EXPECT_EQ("World", res->get_header_value("Hello"));
  11866. }
  11867. #ifdef CPPHTTPLIB_SSL_ENABLED
  11868. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11870. ASSERT_TRUE(svr.is_valid());
  11871. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11872. std::this_thread::sleep_for(std::chrono::seconds(2));
  11873. res.set_content("a", "text/plain");
  11874. });
  11875. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11876. res.set_content("b", "text/plain");
  11877. });
  11878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11879. auto se = detail::scope_exit([&] {
  11880. svr.stop();
  11881. listen_thread.join();
  11882. ASSERT_FALSE(svr.is_running());
  11883. });
  11884. svr.wait_until_ready();
  11885. SSLClient cli("localhost", PORT);
  11886. cli.enable_server_certificate_verification(false);
  11887. cli.set_keep_alive(true);
  11888. cli.set_read_timeout(std::chrono::seconds(1));
  11889. auto resa = cli.Get("/a");
  11890. ASSERT_TRUE(!resa);
  11891. EXPECT_EQ(Error::Read, resa.error());
  11892. auto resb = cli.Get("/b");
  11893. ASSERT_TRUE(resb);
  11894. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11895. EXPECT_EQ("b", resb->body);
  11896. }
  11897. // Closing an idle keep-alive connection sends close_notify and returns. The
  11898. // server must not wait for the client's close_notify: an idle client never
  11899. // sends one, so the worker would be held until the read timeout expires, and
  11900. // stop() would wait for it.
  11901. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11903. ASSERT_TRUE(svr.is_valid());
  11904. svr.set_keep_alive_timeout(1);
  11905. svr.set_read_timeout(10, 0);
  11906. svr.Get("/", [](const Request &, Response &res) {
  11907. res.set_content("ok", "text/plain");
  11908. });
  11909. auto port = svr.bind_to_any_port(HOST);
  11910. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11911. auto se = detail::scope_exit([&] {
  11912. if (listen_thread.joinable()) {
  11913. svr.stop();
  11914. listen_thread.join();
  11915. }
  11916. });
  11917. svr.wait_until_ready();
  11918. SSLClient cli(HOST, port);
  11919. cli.enable_server_certificate_verification(false);
  11920. cli.set_keep_alive(true);
  11921. auto res = cli.Get("/");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::OK_200, res->status);
  11924. // Stay idle past the keep-alive timeout so the server closes the connection.
  11925. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11926. auto start = std::chrono::steady_clock::now();
  11927. svr.stop();
  11928. listen_thread.join();
  11929. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11930. std::chrono::steady_clock::now() - start)
  11931. .count();
  11932. EXPECT_LT(elapsed, 3000);
  11933. }
  11934. #endif
  11935. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11936. protected:
  11937. ServerTestWithAI_PASSIVE()
  11938. : cli_(HOST, PORT)
  11939. #ifdef CPPHTTPLIB_SSL_ENABLED
  11940. ,
  11941. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11942. #endif
  11943. {
  11944. #ifdef CPPHTTPLIB_SSL_ENABLED
  11945. cli_.enable_server_certificate_verification(false);
  11946. #endif
  11947. }
  11948. virtual void SetUp() {
  11949. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11950. res.set_content("Hello World!", "text/plain");
  11951. });
  11952. t_ = thread(
  11953. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11954. svr_.wait_until_ready();
  11955. }
  11956. virtual void TearDown() {
  11957. svr_.stop();
  11958. t_.join();
  11959. }
  11960. #ifdef CPPHTTPLIB_SSL_ENABLED
  11961. SSLClient cli_;
  11962. SSLServer svr_;
  11963. #else
  11964. Client cli_;
  11965. Server svr_;
  11966. #endif
  11967. thread t_;
  11968. };
  11969. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11970. auto res = cli_.Get("/hi");
  11971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11972. EXPECT_EQ(StatusCode::OK_200, res->status);
  11973. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11974. EXPECT_EQ("Hello World!", res->body);
  11975. }
  11976. class ServerUpDownTest : public ::testing::Test {
  11977. protected:
  11978. ServerUpDownTest() : cli_(HOST, PORT) {}
  11979. virtual void SetUp() {
  11980. t_ = thread([&]() {
  11981. svr_.bind_to_any_port(HOST);
  11982. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11983. ASSERT_TRUE(svr_.listen_after_bind());
  11984. });
  11985. svr_.wait_until_ready();
  11986. }
  11987. virtual void TearDown() {
  11988. svr_.stop();
  11989. t_.join();
  11990. }
  11991. Client cli_;
  11992. Server svr_;
  11993. thread t_;
  11994. };
  11995. TEST_F(ServerUpDownTest, QuickStartStop) {
  11996. // Should not crash, especially when run with
  11997. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11998. }
  11999. class PayloadMaxLengthTest : public ::testing::Test {
  12000. protected:
  12001. PayloadMaxLengthTest()
  12002. : cli_(HOST, PORT)
  12003. #ifdef CPPHTTPLIB_SSL_ENABLED
  12004. ,
  12005. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12006. #endif
  12007. {
  12008. #ifdef CPPHTTPLIB_SSL_ENABLED
  12009. cli_.enable_server_certificate_verification(false);
  12010. #endif
  12011. }
  12012. virtual void SetUp() {
  12013. svr_.set_payload_max_length(8);
  12014. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12015. res.set_content("test", "text/plain");
  12016. });
  12017. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12018. svr_.wait_until_ready();
  12019. }
  12020. virtual void TearDown() {
  12021. svr_.stop();
  12022. t_.join();
  12023. }
  12024. #ifdef CPPHTTPLIB_SSL_ENABLED
  12025. SSLClient cli_;
  12026. SSLServer svr_;
  12027. #else
  12028. Client cli_;
  12029. Server svr_;
  12030. #endif
  12031. thread t_;
  12032. };
  12033. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12034. auto res = cli_.Post("/test", "123456789", "text/plain");
  12035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12036. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12037. res = cli_.Post("/test", "12345678", "text/plain");
  12038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12039. EXPECT_EQ(StatusCode::OK_200, res->status);
  12040. }
  12041. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12042. // Test chunked encoding with payload exceeding the 8-byte limit
  12043. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12044. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12046. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12047. }
  12048. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12049. // Test chunked encoding with payload within the 8-byte limit
  12050. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12051. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12053. EXPECT_EQ(StatusCode::OK_200, res->status);
  12054. }
  12055. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12056. // Test using send_request to send chunked data exceeding payload limit
  12057. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12058. "Host: " +
  12059. std::string(HOST) + ":" + std::to_string(PORT) +
  12060. "\r\n"
  12061. "Transfer-Encoding: chunked\r\n"
  12062. "Connection: close\r\n"
  12063. "\r\n"
  12064. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12065. "0123456789\r\n"
  12066. "0\r\n" // End chunk
  12067. "\r\n";
  12068. std::string response;
  12069. bool result = send_request(1, chunked_request, &response);
  12070. if (!result) {
  12071. // If send_request fails, it might be because the server closed the
  12072. // connection due to payload limit enforcement, which is acceptable
  12073. SUCCEED()
  12074. << "Server rejected oversized chunked request (connection closed)";
  12075. } else {
  12076. // If we got a response, check if it's an error response or connection was
  12077. // closed early Short response length indicates connection was closed due to
  12078. // payload limit
  12079. if (response.length() <= 10) {
  12080. SUCCEED() << "Server closed connection for oversized chunked request";
  12081. } else {
  12082. // Check for error status codes
  12083. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12084. response.find("Payload Too Large") != std::string::npos ||
  12085. response.find("400") != std::string::npos);
  12086. }
  12087. }
  12088. }
  12089. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12090. // Test request without Content-Length header exceeding payload limit
  12091. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12092. "Host: " +
  12093. std::string(HOST) + ":" +
  12094. std::to_string(PORT) +
  12095. "\r\n"
  12096. "Connection: close\r\n"
  12097. "\r\n";
  12098. // Add payload exceeding the 8-byte limit
  12099. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12100. request_without_content_length += large_payload;
  12101. std::string response;
  12102. bool result = send_request(1, request_without_content_length, &response);
  12103. if (!result) {
  12104. // If send_request fails, server likely closed connection due to payload
  12105. // limit
  12106. SUCCEED() << "Server rejected oversized request without Content-Length "
  12107. "(connection closed)";
  12108. } else {
  12109. // Check if server responded with error or closed connection early
  12110. if (response.length() <= 10) {
  12111. SUCCEED() << "Server closed connection for oversized request without "
  12112. "Content-Length";
  12113. } else {
  12114. // Check for error status codes
  12115. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12116. response.find("Payload Too Large") != std::string::npos ||
  12117. response.find("400") != std::string::npos);
  12118. }
  12119. }
  12120. }
  12121. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12122. // Test request without Content-Length header within payload limit
  12123. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12124. "Host: " +
  12125. std::string(HOST) + ":" +
  12126. std::to_string(PORT) +
  12127. "\r\n"
  12128. "Connection: close\r\n"
  12129. "\r\n";
  12130. // Add payload within the 8-byte limit
  12131. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12132. request_without_content_length += small_payload;
  12133. std::string response;
  12134. bool result = send_request(1, request_without_content_length, &response);
  12135. // For requests without Content-Length, the server may have different behavior
  12136. // The key is that it should not reject due to payload limit for small
  12137. // payloads
  12138. if (result) {
  12139. // Check for any HTTP response (success or error, but not connection closed)
  12140. if (response.length() > 10) {
  12141. SUCCEED()
  12142. << "Server processed request without Content-Length within limit";
  12143. } else {
  12144. // Short response might indicate connection closed, which is acceptable
  12145. SUCCEED() << "Server closed connection for request without "
  12146. "Content-Length (acceptable behavior)";
  12147. }
  12148. } else {
  12149. // Connection failure might be due to protocol requirements
  12150. SUCCEED() << "Connection issue with request without Content-Length "
  12151. "(environment-specific)";
  12152. }
  12153. }
  12154. class LargePayloadMaxLengthTest : public ::testing::Test {
  12155. protected:
  12156. LargePayloadMaxLengthTest()
  12157. : cli_(HOST, PORT)
  12158. #ifdef CPPHTTPLIB_SSL_ENABLED
  12159. ,
  12160. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12161. #endif
  12162. {
  12163. #ifdef CPPHTTPLIB_SSL_ENABLED
  12164. cli_.enable_server_certificate_verification(false);
  12165. #endif
  12166. }
  12167. virtual void SetUp() {
  12168. // Set 10MB payload limit
  12169. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12170. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12171. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12172. res.set_content("Large payload test", "text/plain");
  12173. });
  12174. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12175. svr_.wait_until_ready();
  12176. }
  12177. virtual void TearDown() {
  12178. svr_.stop();
  12179. t_.join();
  12180. }
  12181. #ifdef CPPHTTPLIB_SSL_ENABLED
  12182. SSLClient cli_;
  12183. SSLServer svr_;
  12184. #else
  12185. Client cli_;
  12186. Server svr_;
  12187. #endif
  12188. thread t_;
  12189. };
  12190. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12191. // Test chunked encoding with payload within 10MB limit
  12192. std::string medium_payload(5 * 1024 * 1024,
  12193. 'A'); // 5MB payload, within 10MB limit
  12194. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12196. EXPECT_EQ(StatusCode::OK_200, res->status);
  12197. }
  12198. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12199. // Test chunked encoding with payload exceeding 10MB limit
  12200. std::string large_payload(12 * 1024 * 1024,
  12201. 'B'); // 12MB payload, exceeds 10MB limit
  12202. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12203. // Server may either return 413 or close the connection
  12204. if (res) {
  12205. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12206. } else {
  12207. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12208. }
  12209. }
  12210. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12211. // Test request without Content-Length header within 10MB limit
  12212. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12213. "Host: " +
  12214. std::string(HOST) + ":" +
  12215. std::to_string(PORT) +
  12216. "\r\n"
  12217. "Connection: close\r\n"
  12218. "\r\n";
  12219. // Add 1MB payload (within 10MB limit)
  12220. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12221. request_without_content_length += medium_payload;
  12222. std::string response;
  12223. bool result = send_request(5, request_without_content_length, &response);
  12224. if (result) {
  12225. // Should get a proper HTTP response for payloads within limit
  12226. if (response.length() > 10) {
  12227. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12228. "10MB limit";
  12229. } else {
  12230. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12231. "Content-Length)";
  12232. }
  12233. } else {
  12234. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12235. }
  12236. }
  12237. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12238. // Test request without Content-Length header exceeding 10MB limit
  12239. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12240. "Host: " +
  12241. std::string(HOST) + ":" +
  12242. std::to_string(PORT) +
  12243. "\r\n"
  12244. "Connection: close\r\n"
  12245. "\r\n";
  12246. // Add 12MB payload (exceeds 10MB limit)
  12247. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12248. request_without_content_length += large_payload;
  12249. std::string response;
  12250. bool result = send_request(10, request_without_content_length, &response);
  12251. if (!result) {
  12252. // Server should close connection due to payload limit
  12253. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12254. "(connection closed)";
  12255. } else {
  12256. // Check for error response
  12257. if (response.length() <= 10) {
  12258. SUCCEED()
  12259. << "Server closed connection for 12MB request exceeding 10MB limit";
  12260. } else {
  12261. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12262. response.find("Payload Too Large") != std::string::npos ||
  12263. response.find("400") != std::string::npos);
  12264. }
  12265. }
  12266. }
  12267. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12268. Server svr;
  12269. svr.Get("/", [](const Request &, Response &res) {
  12270. // Claims the most the client accepts, far more than it sends, then drops
  12271. // the connection.
  12272. res.set_content_provider(std::string().max_size(), "text/plain",
  12273. [](size_t, size_t, DataSink &sink) {
  12274. sink.write("abc", 3);
  12275. return false;
  12276. });
  12277. });
  12278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12279. auto se = detail::scope_exit([&] {
  12280. svr.stop();
  12281. thread.join();
  12282. ASSERT_FALSE(svr.is_running());
  12283. });
  12284. svr.wait_until_ready();
  12285. Client cli(HOST, PORT);
  12286. cli.set_payload_max_length(0);
  12287. EXPECT_FALSE(cli.Get("/"));
  12288. }
  12289. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12290. // Stream API does, not as a plain read failure
  12291. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12292. Server svr;
  12293. svr.Get("/big", [](const Request &, Response &res) {
  12294. res.set_content(std::string(100000, 'b'), "text/plain");
  12295. });
  12296. auto port = svr.bind_to_any_port(HOST);
  12297. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12298. auto se = detail::scope_exit([&] {
  12299. svr.stop();
  12300. thread.join();
  12301. });
  12302. svr.wait_until_ready();
  12303. Client cli(HOST, port);
  12304. cli.set_payload_max_length(1000);
  12305. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12306. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12307. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12308. [](const char *, size_t) { return true; });
  12309. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12311. // Small on the wire, over the limit once decompressed
  12312. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12313. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12314. #endif
  12315. }
  12316. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12317. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12318. // path.
  12319. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12320. Server svr;
  12321. const size_t LIMIT = 64 * 1024; // 64KB
  12322. svr.set_payload_max_length(LIMIT);
  12323. size_t total = 0;
  12324. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12325. const ContentReader &content_reader) {
  12326. content_reader([&](const char * /*data*/, size_t len) {
  12327. total += len;
  12328. return true;
  12329. });
  12330. res.status = 200;
  12331. res.set_content("stream_ok", "text/plain");
  12332. });
  12333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. thread.join();
  12337. ASSERT_FALSE(svr.is_running());
  12338. });
  12339. svr.wait_until_ready();
  12340. // Prepare 256KB raw data and gzip-compress it
  12341. std::string raw(256 * 1024, 'A');
  12342. std::string gz;
  12343. {
  12344. z_stream zs{};
  12345. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12346. Z_DEFAULT_STRATEGY);
  12347. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12348. zs.avail_in = static_cast<uInt>(raw.size());
  12349. char outbuf[4096];
  12350. int ret;
  12351. do {
  12352. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12353. zs.avail_out = sizeof(outbuf);
  12354. ret = deflate(&zs, Z_FINISH);
  12355. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12356. } while (ret != Z_STREAM_END);
  12357. deflateEnd(&zs);
  12358. }
  12359. Client cli(HOST, PORT);
  12360. cli.set_connection_timeout(std::chrono::seconds(5));
  12361. Headers headers = {{"Content-Encoding", "gzip"}};
  12362. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12363. "application/octet-stream");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. // Server must reject oversized decompressed payloads with 413.
  12366. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12367. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12368. EXPECT_LE(total, LIMIT);
  12369. }
  12370. #ifndef CPPHTTPLIB_SSL_ENABLED
  12371. // For a request with neither Content-Length nor Transfer-Encoding, the
  12372. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12373. // compressed wire bytes straight to the ContentReader without ever routing
  12374. // them through the decompressor, so payload_max_length_ only bounded the
  12375. // compressed size on the wire, not the decompressed size.
  12376. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12377. Server svr;
  12378. const size_t LIMIT = 64 * 1024; // 64KB
  12379. svr.set_payload_max_length(LIMIT);
  12380. size_t total = 0;
  12381. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12382. const ContentReader &content_reader) {
  12383. content_reader([&](const char * /*data*/, size_t len) {
  12384. total += len;
  12385. return true;
  12386. });
  12387. res.status = 200;
  12388. res.set_content("stream_ok", "text/plain");
  12389. });
  12390. auto port = svr.bind_to_any_port(HOST);
  12391. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12392. auto se = detail::scope_exit([&] {
  12393. svr.stop();
  12394. thread.join();
  12395. ASSERT_FALSE(svr.is_running());
  12396. });
  12397. svr.wait_until_ready();
  12398. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12399. // StreamingGzipDecompression test above.
  12400. std::string raw(256 * 1024, 'A');
  12401. std::string gz;
  12402. {
  12403. httplib::detail::gzip_compressor compressor;
  12404. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12405. [&](const char *chunk, size_t len) {
  12406. gz.append(chunk, len);
  12407. return true;
  12408. });
  12409. ASSERT_TRUE(result);
  12410. }
  12411. // Send the gzip body over raw TCP with neither Content-Length nor
  12412. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12413. // kicks in.
  12414. std::string req = "POST /stream HTTP/1.1\r\n"
  12415. "Host: " +
  12416. std::string(HOST) + ":" + std::to_string(port) +
  12417. "\r\n"
  12418. "Content-Encoding: gzip\r\n"
  12419. "Connection: close\r\n"
  12420. "\r\n" +
  12421. gz;
  12422. std::string response;
  12423. ASSERT_TRUE(send_request(5, req, &response, port));
  12424. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12425. EXPECT_LE(total, LIMIT);
  12426. }
  12427. #endif
  12428. #endif
  12429. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12430. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12431. // the payload must be passed through untouched instead of being rejected.
  12432. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12433. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12434. Server svr;
  12435. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12436. res.set_content(body, "image/jpeg");
  12437. res.set_header("Content-Encoding", "UTF-8");
  12438. });
  12439. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12440. res.set_content(body, "image/jpeg");
  12441. res.set_header("Content-Encoding", "identity");
  12442. });
  12443. svr.Post("/echo", [](const Request &req, Response &res) {
  12444. res.set_content(req.body, "image/jpeg");
  12445. });
  12446. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12447. auto se = detail::scope_exit([&] {
  12448. svr.stop();
  12449. t.join();
  12450. ASSERT_FALSE(svr.is_running());
  12451. });
  12452. svr.wait_until_ready();
  12453. Client cli(HOST, PORT);
  12454. {
  12455. auto res = cli.Get("/image");
  12456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12457. EXPECT_EQ(StatusCode::OK_200, res->status);
  12458. EXPECT_EQ(body, res->body);
  12459. }
  12460. {
  12461. auto res = cli.Get("/identity");
  12462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12463. EXPECT_EQ(StatusCode::OK_200, res->status);
  12464. EXPECT_EQ(body, res->body);
  12465. }
  12466. {
  12467. // The same applies to a request body reaching the server.
  12468. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12469. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12471. EXPECT_EQ(StatusCode::OK_200, res->status);
  12472. EXPECT_EQ(body, res->body);
  12473. }
  12474. }
  12475. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12476. // gzip-encoded response even when the build has no zlib support.
  12477. static const char GZIPPED_HELLO_WORLD[] = {
  12478. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12479. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12480. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12481. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12482. // A content coding is a whole token, not something the field value merely
  12483. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12484. // as "fibre" look like Brotli, and turned a multi-coding value like
  12485. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12486. // it was never meant to see.
  12487. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12488. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12489. Server svr;
  12490. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12491. res.set_content(body, "image/jpeg");
  12492. res.set_header("Content-Encoding", "fibre");
  12493. });
  12494. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12495. res.set_content(body, "image/jpeg");
  12496. res.set_header("Content-Encoding", "gzip, br");
  12497. });
  12498. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12499. res.set_content(body, "image/jpeg");
  12500. res.set_header("Content-Encoding", "x-zstd-ish");
  12501. });
  12502. auto port = svr.bind_to_any_port(HOST);
  12503. thread t = thread([&]() { svr.listen_after_bind(); });
  12504. auto se = detail::scope_exit([&] {
  12505. svr.stop();
  12506. t.join();
  12507. ASSERT_FALSE(svr.is_running());
  12508. });
  12509. svr.wait_until_ready();
  12510. Client cli(HOST, port);
  12511. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12512. auto res = cli.Get(path);
  12513. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12514. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12515. // Not a coding we recognize, so the payload comes back untouched
  12516. EXPECT_EQ(body, res->body) << path;
  12517. }
  12518. }
  12519. // A content coding cpp-httplib recognizes but was not built with must be
  12520. // reported as such. Handing the still-compressed payload back to the caller
  12521. // would silently corrupt it.
  12522. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12523. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12524. Server svr;
  12525. // "image/jpeg" keeps the server from applying a content coding of its own,
  12526. // so the hand-crafted Content-Encoding below survives.
  12527. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12528. res.set_content(gzipped, "image/jpeg");
  12529. res.set_header("Content-Encoding", "gzip");
  12530. });
  12531. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12532. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12533. res.set_content(gzipped, "image/jpeg");
  12534. res.set_header("Content-Encoding", "GZIP");
  12535. });
  12536. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12537. auto se = detail::scope_exit([&] {
  12538. svr.stop();
  12539. t.join();
  12540. ASSERT_FALSE(svr.is_running());
  12541. });
  12542. svr.wait_until_ready();
  12543. Client cli(HOST, PORT);
  12544. {
  12545. auto res = cli.Get("/gzipped");
  12546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12548. EXPECT_EQ("Hello World!", res->body);
  12549. #else
  12550. ASSERT_FALSE(res);
  12551. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12552. #endif
  12553. }
  12554. {
  12555. // open_stream() must behave the same way.
  12556. auto handle = cli.open_stream("GET", "/gzipped");
  12557. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12558. ASSERT_TRUE(handle.is_valid());
  12559. std::string received;
  12560. char buf[256];
  12561. ssize_t n;
  12562. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12563. received.append(buf, static_cast<size_t>(n));
  12564. }
  12565. EXPECT_EQ("Hello World!", received);
  12566. #else
  12567. EXPECT_FALSE(handle.is_valid());
  12568. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12569. #endif
  12570. }
  12571. {
  12572. // A differently-cased coding must not be mistaken for an unknown one, or
  12573. // the body would be handed back still compressed.
  12574. auto res = cli.Get("/gzipped-uppercase");
  12575. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. EXPECT_EQ("Hello World!", res->body);
  12578. #else
  12579. ASSERT_FALSE(res);
  12580. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12581. #endif
  12582. }
  12583. }
  12584. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12585. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12586. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12587. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12588. // body a second time and appending a second Content-Encoding field line, so
  12589. // clients that decode one coding per listed value handed back raw gzip bytes.
  12590. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12591. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12592. Server svr;
  12593. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12594. // keeps the server from applying a coding of its own.
  12595. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12596. res.set_content(gzipped, "text/plain");
  12597. res.set_header("Content-Encoding", "gzip");
  12598. });
  12599. auto port = svr.bind_to_any_port(HOST);
  12600. thread t = thread([&]() { svr.listen_after_bind(); });
  12601. auto se = detail::scope_exit([&] {
  12602. svr.stop();
  12603. t.join();
  12604. ASSERT_FALSE(svr.is_running());
  12605. });
  12606. svr.wait_until_ready();
  12607. Client cli(HOST, port);
  12608. Headers headers = {{"Accept-Encoding", "gzip"}};
  12609. auto res = cli.Get("/pre-gzipped", headers);
  12610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12611. EXPECT_EQ(StatusCode::OK_200, res->status);
  12612. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12613. EXPECT_EQ("Hello World!", res->body);
  12614. }
  12615. // A chunked provider settles its coding where the headers are written and
  12616. // reuses it at write time. Both ends of that have to hold: a handler's own
  12617. // Content-Encoding suppresses the coding, and a response without one is still
  12618. // compressed as it always was.
  12619. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12620. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12621. const std::string plain = "Hello World! Hello World! Hello World!";
  12622. Server svr;
  12623. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12624. res.set_header("Content-Encoding", "gzip");
  12625. res.set_chunked_content_provider(
  12626. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12627. sink.write(gzipped.data(), gzipped.size());
  12628. sink.done();
  12629. return true;
  12630. });
  12631. });
  12632. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12633. res.set_chunked_content_provider(
  12634. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12635. sink.write(plain.data(), plain.size());
  12636. sink.done();
  12637. return true;
  12638. });
  12639. });
  12640. auto port = svr.bind_to_any_port(HOST);
  12641. thread t = thread([&]() { svr.listen_after_bind(); });
  12642. auto se = detail::scope_exit([&] {
  12643. svr.stop();
  12644. t.join();
  12645. ASSERT_FALSE(svr.is_running());
  12646. });
  12647. svr.wait_until_ready();
  12648. Client cli(HOST, port);
  12649. Headers headers = {{"Accept-Encoding", "gzip"}};
  12650. {
  12651. auto res = cli.Get("/pre-gzipped", headers);
  12652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12653. EXPECT_EQ(StatusCode::OK_200, res->status);
  12654. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12655. EXPECT_EQ("Hello World!", res->body);
  12656. }
  12657. {
  12658. auto res = cli.Get("/negotiated", headers);
  12659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12660. EXPECT_EQ(StatusCode::OK_200, res->status);
  12661. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12662. EXPECT_EQ(plain, res->body);
  12663. }
  12664. }
  12665. #endif
  12666. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12667. // the same message as the comma-joined one, so both have to be read the same
  12668. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12669. // single gzip coding, and a body the sender says was encoded twice was handed
  12670. // back after one pass, still compressed but presented as decoded.
  12671. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12672. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12673. Server svr;
  12674. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12675. res.set_content(body, "image/jpeg");
  12676. res.headers.emplace("Content-Encoding", "gzip");
  12677. res.headers.emplace("Content-Encoding", "gzip");
  12678. });
  12679. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12680. res.set_content(body, "image/jpeg");
  12681. res.set_header("Content-Encoding", "gzip, gzip");
  12682. });
  12683. auto port = svr.bind_to_any_port(HOST);
  12684. thread t = thread([&]() { svr.listen_after_bind(); });
  12685. auto se = detail::scope_exit([&] {
  12686. svr.stop();
  12687. t.join();
  12688. ASSERT_FALSE(svr.is_running());
  12689. });
  12690. svr.wait_until_ready();
  12691. Client cli(HOST, port);
  12692. // Two codings is not something cpp-httplib decodes, so both representations
  12693. // take the pass-through path rather than one of them being gunzipped once.
  12694. for (const char *path : {"/split", "/joined"}) {
  12695. auto res = cli.Get(path);
  12696. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12697. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12698. EXPECT_EQ(body, res->body) << path;
  12699. }
  12700. }
  12701. // Regression test for DoS vulnerability: a malicious server sending a response
  12702. // without Content-Length header must not cause unbounded memory consumption on
  12703. // the client side. The client should stop reading after a reasonable limit,
  12704. // similar to the server-side set_payload_max_length protection.
  12705. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12706. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12707. #ifndef _WIN32
  12708. signal(SIGPIPE, SIG_IGN);
  12709. #endif
  12710. auto server_thread = std::thread([] {
  12711. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12712. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12713. default_socket_options(srv);
  12714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12715. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12716. sockaddr_in addr{};
  12717. addr.sin_family = AF_INET;
  12718. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12719. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12720. int opt = 1;
  12721. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12722. #ifdef _WIN32
  12723. reinterpret_cast<const char *>(&opt),
  12724. #else
  12725. &opt,
  12726. #endif
  12727. sizeof(opt));
  12728. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12729. ::listen(srv, 1);
  12730. sockaddr_in cli_addr{};
  12731. socklen_t cli_len = sizeof(cli_addr);
  12732. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12733. if (cli != INVALID_SOCKET) {
  12734. char buf[4096];
  12735. ::recv(cli, buf, sizeof(buf), 0);
  12736. // Malicious response: no Content-Length, no chunked encoding
  12737. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12738. "Connection: close\r\n"
  12739. "\r\n";
  12740. ::send(cli,
  12741. #ifdef _WIN32
  12742. static_cast<const char *>(response_header.c_str()),
  12743. static_cast<int>(response_header.size()),
  12744. #else
  12745. response_header.c_str(), response_header.size(),
  12746. #endif
  12747. 0);
  12748. // Send 10MB of data
  12749. std::string chunk(64 * 1024, 'A');
  12750. size_t total_sent = 0;
  12751. while (total_sent < MALICIOUS_DATA_SIZE) {
  12752. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12753. auto sent = ::send(cli,
  12754. #ifdef _WIN32
  12755. static_cast<const char *>(chunk.c_str()),
  12756. static_cast<int>(to_send),
  12757. #else
  12758. chunk.c_str(), to_send,
  12759. #endif
  12760. 0);
  12761. if (sent <= 0) break;
  12762. total_sent += static_cast<size_t>(sent);
  12763. }
  12764. detail::close_socket(cli);
  12765. }
  12766. detail::close_socket(srv);
  12767. });
  12768. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12769. size_t total_read = 0;
  12770. {
  12771. Client cli("127.0.0.1", PORT + 2);
  12772. cli.set_read_timeout(5, 0);
  12773. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12774. auto stream = cli.open_stream("GET", "/malicious");
  12775. ASSERT_TRUE(stream.is_valid());
  12776. char buffer[64 * 1024];
  12777. ssize_t n;
  12778. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12779. total_read += static_cast<size_t>(n);
  12780. }
  12781. } // StreamHandle and Client destroyed here, closing the socket
  12782. server_thread.join();
  12783. // With set_payload_max_length, the client must stop reading before consuming
  12784. // all 10MB. The read loop should be cut off at or near the configured limit.
  12785. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12786. << "Client read " << total_read << " bytes, exceeding the configured "
  12787. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12788. }
  12789. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12790. // the entire response body without truncation.
  12791. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12792. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12793. #ifndef _WIN32
  12794. signal(SIGPIPE, SIG_IGN);
  12795. #endif
  12796. auto server_thread = std::thread([] {
  12797. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12798. default_socket_options(srv);
  12799. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12800. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12801. sockaddr_in addr{};
  12802. addr.sin_family = AF_INET;
  12803. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12804. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12805. int opt = 1;
  12806. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12807. #ifdef _WIN32
  12808. reinterpret_cast<const char *>(&opt),
  12809. #else
  12810. &opt,
  12811. #endif
  12812. sizeof(opt));
  12813. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12814. ::listen(srv, 1);
  12815. sockaddr_in cli_addr{};
  12816. socklen_t cli_len = sizeof(cli_addr);
  12817. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12818. if (cli != INVALID_SOCKET) {
  12819. char buf[4096];
  12820. ::recv(cli, buf, sizeof(buf), 0);
  12821. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12822. "Connection: close\r\n"
  12823. "\r\n";
  12824. ::send(cli,
  12825. #ifdef _WIN32
  12826. static_cast<const char *>(response_header.c_str()),
  12827. static_cast<int>(response_header.size()),
  12828. #else
  12829. response_header.c_str(), response_header.size(),
  12830. #endif
  12831. 0);
  12832. std::string chunk(64 * 1024, 'A');
  12833. size_t total_sent = 0;
  12834. while (total_sent < DATA_SIZE) {
  12835. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12836. auto sent = ::send(cli,
  12837. #ifdef _WIN32
  12838. static_cast<const char *>(chunk.c_str()),
  12839. static_cast<int>(to_send),
  12840. #else
  12841. chunk.c_str(), to_send,
  12842. #endif
  12843. 0);
  12844. if (sent <= 0) break;
  12845. total_sent += static_cast<size_t>(sent);
  12846. }
  12847. #ifdef _WIN32
  12848. ::shutdown(cli, SD_SEND);
  12849. #else
  12850. ::shutdown(cli, SHUT_WR);
  12851. #endif
  12852. // Drain until the client closes its end, ensuring all data is delivered
  12853. char drain[1024];
  12854. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12855. detail::close_socket(cli);
  12856. }
  12857. detail::close_socket(srv);
  12858. });
  12859. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12860. size_t total_read = 0;
  12861. {
  12862. Client cli("127.0.0.1", PORT + 2);
  12863. cli.set_read_timeout(5, 0);
  12864. cli.set_payload_max_length(0); // 0 means no limit
  12865. auto stream = cli.open_stream("GET", "/data");
  12866. ASSERT_TRUE(stream.is_valid());
  12867. char buffer[64 * 1024];
  12868. ssize_t n;
  12869. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12870. total_read += static_cast<size_t>(n);
  12871. }
  12872. }
  12873. server_thread.join();
  12874. EXPECT_EQ(total_read, DATA_SIZE)
  12875. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12876. << " bytes without truncation, but only read " << total_read << " bytes.";
  12877. }
  12878. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12879. // enormous Content-Length must not cause the client to pre-allocate a huge
  12880. // response body buffer. The reservation is capped at payload_max_length_, and
  12881. // the read itself fails when the body exceeds the limit.
  12882. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12883. #ifndef _WIN32
  12884. signal(SIGPIPE, SIG_IGN);
  12885. #endif
  12886. auto server_thread = std::thread([] {
  12887. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12888. default_socket_options(srv);
  12889. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12890. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12891. sockaddr_in addr{};
  12892. addr.sin_family = AF_INET;
  12893. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12894. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12895. int opt = 1;
  12896. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12897. #ifdef _WIN32
  12898. reinterpret_cast<const char *>(&opt),
  12899. #else
  12900. &opt,
  12901. #endif
  12902. sizeof(opt));
  12903. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12904. ::listen(srv, 1);
  12905. sockaddr_in cli_addr{};
  12906. socklen_t cli_len = sizeof(cli_addr);
  12907. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12908. if (cli != INVALID_SOCKET) {
  12909. char buf[4096];
  12910. ::recv(cli, buf, sizeof(buf), 0);
  12911. // Malicious response: claim a 20GB body but send only a tiny payload.
  12912. std::string response = "HTTP/1.1 200 OK\r\n"
  12913. "Content-Length: 20000000000\r\n"
  12914. "\r\n"
  12915. "abc";
  12916. ::send(cli,
  12917. #ifdef _WIN32
  12918. static_cast<const char *>(response.c_str()),
  12919. static_cast<int>(response.size()),
  12920. #else
  12921. response.c_str(), response.size(),
  12922. #endif
  12923. 0);
  12924. detail::close_socket(cli);
  12925. }
  12926. detail::close_socket(srv);
  12927. });
  12928. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12929. {
  12930. Client cli("127.0.0.1", PORT + 2);
  12931. cli.set_read_timeout(5, 0);
  12932. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12933. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12934. // (server claims more bytes than payload_max_length permits), but it must
  12935. // not exhaust memory before getting there.
  12936. auto res = cli.Get("/malicious");
  12937. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12938. }
  12939. server_thread.join();
  12940. }
  12941. // Verify that content_receiver bypasses the default payload_max_length,
  12942. // allowing streaming downloads larger than 100MB without requiring an explicit
  12943. // set_payload_max_length call.
  12944. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12945. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12946. #ifndef _WIN32
  12947. signal(SIGPIPE, SIG_IGN);
  12948. #endif
  12949. auto server_thread = std::thread([] {
  12950. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12951. default_socket_options(srv);
  12952. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12953. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12954. sockaddr_in addr{};
  12955. addr.sin_family = AF_INET;
  12956. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12957. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12958. int opt = 1;
  12959. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12960. #ifdef _WIN32
  12961. reinterpret_cast<const char *>(&opt),
  12962. #else
  12963. &opt,
  12964. #endif
  12965. sizeof(opt));
  12966. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12967. ::listen(srv, 1);
  12968. sockaddr_in cli_addr{};
  12969. socklen_t cli_len = sizeof(cli_addr);
  12970. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12971. if (cli != INVALID_SOCKET) {
  12972. char buf[4096];
  12973. ::recv(cli, buf, sizeof(buf), 0);
  12974. // Response with Content-Length larger than default 100MB limit
  12975. auto content_length = std::to_string(DATA_SIZE);
  12976. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12977. "Content-Length: " +
  12978. content_length +
  12979. "\r\n"
  12980. "Connection: close\r\n"
  12981. "\r\n";
  12982. ::send(cli,
  12983. #ifdef _WIN32
  12984. static_cast<const char *>(response_header.c_str()),
  12985. static_cast<int>(response_header.size()),
  12986. #else
  12987. response_header.c_str(), response_header.size(),
  12988. #endif
  12989. 0);
  12990. std::string chunk(64 * 1024, 'A');
  12991. size_t total_sent = 0;
  12992. while (total_sent < DATA_SIZE) {
  12993. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12994. auto sent = ::send(cli,
  12995. #ifdef _WIN32
  12996. static_cast<const char *>(chunk.c_str()),
  12997. static_cast<int>(to_send),
  12998. #else
  12999. chunk.c_str(), to_send,
  13000. #endif
  13001. 0);
  13002. if (sent <= 0) break;
  13003. total_sent += static_cast<size_t>(sent);
  13004. }
  13005. detail::close_socket(cli);
  13006. }
  13007. detail::close_socket(srv);
  13008. });
  13009. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13010. size_t total_received = 0;
  13011. {
  13012. Client cli("127.0.0.1", PORT + 2);
  13013. cli.set_read_timeout(10, 0);
  13014. // Do NOT call set_payload_max_length — use the default 100MB limit
  13015. auto res =
  13016. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13017. total_received += data_length;
  13018. return true;
  13019. });
  13020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13021. EXPECT_EQ(StatusCode::OK_200, res->status);
  13022. }
  13023. server_thread.join();
  13024. EXPECT_EQ(total_received, DATA_SIZE)
  13025. << "With content_receiver, the client should read all " << DATA_SIZE
  13026. << " bytes despite the default 100MB payload_max_length, but only read "
  13027. << total_received << " bytes.";
  13028. }
  13029. // Verify that an explicit set_payload_max_length smaller than the response is
  13030. // enforced even when a content_receiver is used.
  13031. TEST(ClientVulnerabilityTest,
  13032. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13033. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13034. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13035. #ifndef _WIN32
  13036. signal(SIGPIPE, SIG_IGN);
  13037. #endif
  13038. auto server_thread = std::thread([] {
  13039. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13040. default_socket_options(srv);
  13041. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13042. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13043. sockaddr_in addr{};
  13044. addr.sin_family = AF_INET;
  13045. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13046. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13047. int opt = 1;
  13048. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13049. #ifdef _WIN32
  13050. reinterpret_cast<const char *>(&opt),
  13051. #else
  13052. &opt,
  13053. #endif
  13054. sizeof(opt));
  13055. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13056. ::listen(srv, 1);
  13057. sockaddr_in cli_addr{};
  13058. socklen_t cli_len = sizeof(cli_addr);
  13059. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13060. if (cli != INVALID_SOCKET) {
  13061. char buf[4096];
  13062. ::recv(cli, buf, sizeof(buf), 0);
  13063. auto content_length = std::to_string(DATA_SIZE);
  13064. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13065. "Content-Length: " +
  13066. content_length +
  13067. "\r\n"
  13068. "Connection: close\r\n"
  13069. "\r\n";
  13070. ::send(cli,
  13071. #ifdef _WIN32
  13072. static_cast<const char *>(response_header.c_str()),
  13073. static_cast<int>(response_header.size()),
  13074. #else
  13075. response_header.c_str(), response_header.size(),
  13076. #endif
  13077. 0);
  13078. std::string chunk(64 * 1024, 'A');
  13079. size_t total_sent = 0;
  13080. while (total_sent < DATA_SIZE) {
  13081. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13082. auto sent = ::send(cli,
  13083. #ifdef _WIN32
  13084. static_cast<const char *>(chunk.c_str()),
  13085. static_cast<int>(to_send),
  13086. #else
  13087. chunk.c_str(), to_send,
  13088. #endif
  13089. 0);
  13090. if (sent <= 0) break;
  13091. total_sent += static_cast<size_t>(sent);
  13092. }
  13093. detail::close_socket(cli);
  13094. }
  13095. detail::close_socket(srv);
  13096. });
  13097. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13098. size_t total_received = 0;
  13099. {
  13100. Client cli("127.0.0.1", PORT + 2);
  13101. cli.set_read_timeout(10, 0);
  13102. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13103. auto res =
  13104. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13105. total_received += data_length;
  13106. return true;
  13107. });
  13108. // Should fail because 200MB exceeds the explicit 150MB limit
  13109. EXPECT_FALSE(res);
  13110. }
  13111. server_thread.join();
  13112. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13113. << "Client with content_receiver should respect the explicit "
  13114. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13115. << total_received << " bytes.";
  13116. }
  13117. // Verify that an explicit set_payload_max_length larger than the response
  13118. // allows the content_receiver to read all data successfully.
  13119. TEST(ClientVulnerabilityTest,
  13120. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13121. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13122. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13123. #ifndef _WIN32
  13124. signal(SIGPIPE, SIG_IGN);
  13125. #endif
  13126. auto server_thread = std::thread([] {
  13127. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13128. default_socket_options(srv);
  13129. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13130. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13131. sockaddr_in addr{};
  13132. addr.sin_family = AF_INET;
  13133. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13134. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13135. int opt = 1;
  13136. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13137. #ifdef _WIN32
  13138. reinterpret_cast<const char *>(&opt),
  13139. #else
  13140. &opt,
  13141. #endif
  13142. sizeof(opt));
  13143. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13144. ::listen(srv, 1);
  13145. sockaddr_in cli_addr{};
  13146. socklen_t cli_len = sizeof(cli_addr);
  13147. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13148. if (cli != INVALID_SOCKET) {
  13149. char buf[4096];
  13150. ::recv(cli, buf, sizeof(buf), 0);
  13151. auto content_length = std::to_string(DATA_SIZE);
  13152. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13153. "Content-Length: " +
  13154. content_length +
  13155. "\r\n"
  13156. "Connection: close\r\n"
  13157. "\r\n";
  13158. ::send(cli,
  13159. #ifdef _WIN32
  13160. static_cast<const char *>(response_header.c_str()),
  13161. static_cast<int>(response_header.size()),
  13162. #else
  13163. response_header.c_str(), response_header.size(),
  13164. #endif
  13165. 0);
  13166. std::string chunk(64 * 1024, 'A');
  13167. size_t total_sent = 0;
  13168. while (total_sent < DATA_SIZE) {
  13169. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13170. auto sent = ::send(cli,
  13171. #ifdef _WIN32
  13172. static_cast<const char *>(chunk.c_str()),
  13173. static_cast<int>(to_send),
  13174. #else
  13175. chunk.c_str(), to_send,
  13176. #endif
  13177. 0);
  13178. if (sent <= 0) break;
  13179. total_sent += static_cast<size_t>(sent);
  13180. }
  13181. #ifdef _WIN32
  13182. ::shutdown(cli, SD_SEND);
  13183. #else
  13184. ::shutdown(cli, SHUT_WR);
  13185. #endif
  13186. char drain[1024];
  13187. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13188. detail::close_socket(cli);
  13189. }
  13190. detail::close_socket(srv);
  13191. });
  13192. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13193. size_t total_received = 0;
  13194. {
  13195. Client cli("127.0.0.1", PORT + 2);
  13196. cli.set_read_timeout(10, 0);
  13197. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13198. auto res =
  13199. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13200. total_received += data_length;
  13201. return true;
  13202. });
  13203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13204. EXPECT_EQ(StatusCode::OK_200, res->status);
  13205. }
  13206. server_thread.join();
  13207. EXPECT_EQ(total_received, DATA_SIZE)
  13208. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13209. << " bytes (larger than " << DATA_SIZE
  13210. << " bytes response), content_receiver should read all data, but only "
  13211. "read "
  13212. << total_received << " bytes.";
  13213. }
  13214. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13215. // Regression test for "zip bomb" attack on the client side: a malicious server
  13216. // sends a small gzip-compressed response that decompresses to a huge payload.
  13217. // The client must enforce payload_max_length on the decompressed size.
  13218. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13219. constexpr size_t DECOMPRESSED_SIZE =
  13220. 10 * 1024 * 1024; // 10MB after decompression
  13221. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13222. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13223. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13224. std::string compressed;
  13225. {
  13226. httplib::detail::gzip_compressor compressor;
  13227. bool ok =
  13228. compressor.compress(uncompressed.data(), uncompressed.size(),
  13229. /*last=*/true, [&](const char *buf, size_t len) {
  13230. compressed.append(buf, len);
  13231. return true;
  13232. });
  13233. ASSERT_TRUE(ok);
  13234. }
  13235. // Sanity: compressed data should be much smaller than the decompressed size
  13236. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13237. #ifndef _WIN32
  13238. signal(SIGPIPE, SIG_IGN);
  13239. #endif
  13240. // Set up the listening socket in the main thread so the server is guaranteed
  13241. // to be ready before the client connects (eliminates race condition).
  13242. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13243. default_socket_options(srv);
  13244. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13245. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13246. sockaddr_in addr{};
  13247. addr.sin_family = AF_INET;
  13248. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13249. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13250. int opt = 1;
  13251. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13252. #ifdef _WIN32
  13253. reinterpret_cast<const char *>(&opt),
  13254. #else
  13255. &opt,
  13256. #endif
  13257. sizeof(opt));
  13258. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13259. ASSERT_EQ(0, ::listen(srv, 1));
  13260. auto server_thread = std::thread([&compressed, srv] {
  13261. sockaddr_in cli_addr{};
  13262. socklen_t cli_len = sizeof(cli_addr);
  13263. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13264. if (cli != INVALID_SOCKET) {
  13265. // Read the full HTTP request (until \r\n\r\n)
  13266. char buf[4096];
  13267. size_t total = 0;
  13268. while (total < sizeof(buf)) {
  13269. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13270. if (n <= 0) break;
  13271. total += static_cast<size_t>(n);
  13272. // Check for end of headers
  13273. if (total >= 4) {
  13274. std::string req(buf, total);
  13275. if (req.find("\r\n\r\n") != std::string::npos) break;
  13276. }
  13277. }
  13278. // Malicious response: gzip-compressed body, no Content-Length
  13279. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13280. "Content-Encoding: gzip\r\n"
  13281. "Connection: close\r\n"
  13282. "\r\n";
  13283. ::send(cli,
  13284. #ifdef _WIN32
  13285. static_cast<const char *>(response_header.c_str()),
  13286. static_cast<int>(response_header.size()),
  13287. #else
  13288. response_header.c_str(), response_header.size(),
  13289. #endif
  13290. 0);
  13291. // Send the compressed payload (small on the wire, huge when decompressed)
  13292. size_t total_sent = 0;
  13293. while (total_sent < compressed.size()) {
  13294. auto to_send = std::min(compressed.size() - total_sent,
  13295. static_cast<size_t>(64 * 1024));
  13296. auto sent =
  13297. ::send(cli,
  13298. #ifdef _WIN32
  13299. static_cast<const char *>(compressed.c_str() + total_sent),
  13300. static_cast<int>(to_send),
  13301. #else
  13302. compressed.c_str() + total_sent, to_send,
  13303. #endif
  13304. 0);
  13305. if (sent <= 0) break;
  13306. total_sent += static_cast<size_t>(sent);
  13307. }
  13308. detail::close_socket(cli);
  13309. }
  13310. });
  13311. auto se = detail::scope_exit([&] {
  13312. detail::close_socket(srv);
  13313. server_thread.join();
  13314. });
  13315. size_t total_decompressed = 0;
  13316. {
  13317. Client cli("127.0.0.1", PORT + 3);
  13318. cli.set_read_timeout(5, 0);
  13319. cli.set_decompress(true);
  13320. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13321. auto stream = cli.open_stream("GET", "/zipbomb");
  13322. ASSERT_TRUE(stream.is_valid());
  13323. char buffer[64 * 1024];
  13324. ssize_t n;
  13325. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13326. total_decompressed += static_cast<size_t>(n);
  13327. }
  13328. }
  13329. // The decompressed size must be capped by payload_max_length. Without
  13330. // protection, the client would decompress the full 10MB from a tiny
  13331. // compressed payload, enabling a zip bomb DoS attack.
  13332. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13333. << "Client decompressed " << total_decompressed
  13334. << " bytes from a gzip response. The decompressed size should be "
  13335. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13336. }
  13337. #endif
  13338. TEST(HostAndPortPropertiesTest, NoSSL) {
  13339. httplib::Client cli("www.google.com", 1234);
  13340. ASSERT_EQ("www.google.com", cli.host());
  13341. ASSERT_EQ(1234, cli.port());
  13342. }
  13343. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13344. httplib::Client cli("www.google.com:1234");
  13345. ASSERT_EQ("www.google.com", cli.host());
  13346. ASSERT_EQ(1234, cli.port());
  13347. }
  13348. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13349. // Port number that overflows int — should not crash, client becomes invalid
  13350. httplib::Client cli("http://www.google.com:99999999999999999999");
  13351. ASSERT_FALSE(cli.is_valid());
  13352. }
  13353. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13354. // Port 99999 exceeds valid range (1-65535) — should not crash
  13355. httplib::Client cli("http://www.google.com:99999");
  13356. ASSERT_FALSE(cli.is_valid());
  13357. auto res = cli.Get("/");
  13358. EXPECT_FALSE(res);
  13359. EXPECT_EQ(Error::Connection, res.error());
  13360. }
  13361. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13362. httplib::Client cli("http://user:pass@localhost:1234");
  13363. ASSERT_FALSE(cli.is_valid());
  13364. EXPECT_FALSE(cli.Get("/"));
  13365. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13366. }
  13367. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13368. httplib::Client cli("http://www.google.com:80abc");
  13369. ASSERT_FALSE(cli.is_valid());
  13370. }
  13371. #ifdef CPPHTTPLIB_SSL_ENABLED
  13372. TEST(HostAndPortPropertiesTest, SSL) {
  13373. httplib::SSLClient cli("www.google.com");
  13374. ASSERT_EQ("www.google.com", cli.host());
  13375. ASSERT_EQ(443, cli.port());
  13376. }
  13377. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13378. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13379. std::string cert;
  13380. read_file(CA_CERT_FILE, cert);
  13381. httplib::SSLClient httplib_client("www.google.com");
  13382. // Load CA store first time
  13383. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13384. // Load CA store second time (update)
  13385. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13386. // Verify client is still valid and can make connections
  13387. httplib_client.enable_server_certificate_verification(true);
  13388. auto res = httplib_client.Get("/");
  13389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13390. // Google may return 200 or 301 depending on various factors
  13391. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13392. res->status == StatusCode::MovedPermanently_301);
  13393. }
  13394. TEST(SSLClientTest, ServerNameIndication_Online) {
  13395. auto host = "httpbingo.org";
  13396. auto path = std::string{"/get"};
  13397. SSLClient cli(host, 443);
  13398. auto res = cli.Get(path);
  13399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13400. ASSERT_EQ(StatusCode::OK_200, res->status);
  13401. }
  13402. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13403. // Use a site that will cause SSL verification failure due to self-signed cert
  13404. SSLClient cli("self-signed.badssl.com", 443);
  13405. cli.enable_server_certificate_verification(true);
  13406. auto res = cli.Get("/");
  13407. ASSERT_TRUE(!res);
  13408. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13409. // Verify backend error is captured for SSLServerVerification
  13410. // This occurs when certificate verification fails
  13411. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13412. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13413. EXPECT_NE(0UL, res.ssl_backend_error());
  13414. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13415. res.ssl_error());
  13416. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13417. #if !defined(_WIN32) || \
  13418. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13419. // On non-Windows or when Windows Schannel is disabled, the error comes
  13420. // from OpenSSL's verification
  13421. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13422. res.ssl_backend_error());
  13423. #endif
  13424. #endif
  13425. }
  13426. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13427. // Use a site where hostname doesn't match the certificate
  13428. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13429. SSLClient cli("wrong.host.badssl.com", 443);
  13430. cli.enable_server_certificate_verification(true);
  13431. cli.enable_server_hostname_verification(true);
  13432. auto res = cli.Get("/");
  13433. ASSERT_TRUE(!res);
  13434. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13435. // Verify backend error is captured for hostname verification failure
  13436. EXPECT_NE(0UL, res.ssl_backend_error());
  13437. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13438. res.ssl_error());
  13439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13440. #if !defined(_WIN32) || \
  13441. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13442. // On non-Windows or when Windows Schannel is disabled, the error comes
  13443. // from OpenSSL's hostname verification
  13444. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13445. res.ssl_backend_error());
  13446. #endif
  13447. #endif
  13448. }
  13449. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13450. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13451. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13452. SSLClient cli("www.google.com", 443);
  13453. cli.enable_server_certificate_verification(true);
  13454. auto res = cli.Get("/");
  13455. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13456. }
  13457. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13458. SSLClient cli("www.google.com", 443);
  13459. cli.enable_server_certificate_verification(true);
  13460. cli.enable_windows_certificate_verification(false);
  13461. auto res = cli.Get("/");
  13462. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13463. }
  13464. // The server sends an intermediate cross-signed by a root Windows trusts,
  13465. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13466. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13467. SSLClient cli("accounts.spotify.com", 443);
  13468. auto res = cli.Get("/");
  13469. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13470. << " ssl_backend_error=" << res.ssl_backend_error();
  13471. }
  13472. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13473. // policy status, which no backend reports for a self-signed certificate.
  13474. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13475. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13476. ASSERT_TRUE(svr.is_valid());
  13477. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13478. auto se = detail::scope_exit([&] {
  13479. svr.stop();
  13480. t.join();
  13481. ASSERT_FALSE(svr.is_running());
  13482. });
  13483. svr.wait_until_ready();
  13484. SSLClient cli("127.0.0.1", PORT);
  13485. cli.set_connection_timeout(30);
  13486. auto res = cli.Get("/");
  13487. ASSERT_FALSE(res);
  13488. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13489. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13490. }
  13491. #endif
  13492. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13493. Client cli("https://google.com");
  13494. auto res = cli.Get("/");
  13495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13496. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13497. }
  13498. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13499. SSLClient cli("google.com");
  13500. cli.set_ca_cert_path(CA_CERT_FILE);
  13501. auto res = cli.Get("/");
  13502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13503. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13504. }
  13505. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13506. SSLClient cli("google.com");
  13507. cli.enable_server_certificate_verification(true);
  13508. cli.set_ca_cert_path("hello");
  13509. auto res = cli.Get("/");
  13510. ASSERT_TRUE(!res);
  13511. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13512. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13513. // should be set
  13514. EXPECT_EQ(0, res.ssl_error());
  13515. // Verify backend error is captured for SSLLoadingCerts
  13516. // This error occurs when loading CA certificates fails
  13517. EXPECT_NE(0UL, res.ssl_backend_error());
  13518. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13519. // OpenSSL specific error codes:
  13520. // > openssl errstr 0x80000002
  13521. // error:80000002:system library::No such file or directory
  13522. // > openssl errstr 0xA000126
  13523. // error:0A000126:SSL routines::unexpected eof while reading
  13524. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13525. res.ssl_backend_error() == 0xA000126);
  13526. #endif
  13527. }
  13528. TEST(SSLClientTest, ServerCertificateVerification4) {
  13529. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13530. ASSERT_TRUE(svr.is_valid());
  13531. svr.Get("/test", [&](const Request &, Response &res) {
  13532. res.set_content("test", "text/plain");
  13533. svr.stop();
  13534. ASSERT_TRUE(true);
  13535. });
  13536. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13537. auto se = detail::scope_exit([&] {
  13538. t.join();
  13539. ASSERT_FALSE(svr.is_running());
  13540. });
  13541. svr.wait_until_ready();
  13542. SSLClient cli("127.0.0.1", PORT);
  13543. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13544. cli.enable_server_certificate_verification(true);
  13545. cli.set_connection_timeout(30);
  13546. auto res = cli.Get("/test");
  13547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13548. ASSERT_EQ(StatusCode::OK_200, res->status);
  13549. }
  13550. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13551. std::string cert;
  13552. read_file(CA_CERT_FILE, cert);
  13553. SSLClient cli("google.com");
  13554. cli.load_ca_cert_store(cert.data(), cert.size());
  13555. const auto res = cli.Get("/");
  13556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13557. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13558. }
  13559. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13560. // clang-format off
  13561. static constexpr char cert[] =
  13562. "GlobalSign Root CA\n"
  13563. "==================\n"
  13564. "-----BEGIN CERTIFICATE-----\n"
  13565. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13566. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13567. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13568. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13569. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13570. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13571. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13572. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13573. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13574. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13575. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13576. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13577. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13578. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13579. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13580. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13581. "-----END CERTIFICATE-----\n";
  13582. // clang-format on
  13583. SSLClient cli("google.com");
  13584. cli.load_ca_cert_store(cert, sizeof(cert));
  13585. const auto res = cli.Get("/");
  13586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13587. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13588. }
  13589. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13590. SSLClient cli("www.youtube.com");
  13591. cli.set_ca_cert_path(CA_CERT_FILE);
  13592. cli.enable_server_certificate_verification(true);
  13593. cli.set_follow_location(true);
  13594. auto res = cli.Get("/");
  13595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13596. ASSERT_EQ(StatusCode::OK_200, res->status);
  13597. }
  13598. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13599. SSLClient cli("wWw.YouTube.Com");
  13600. cli.set_ca_cert_path(CA_CERT_FILE);
  13601. cli.enable_server_certificate_verification(true);
  13602. cli.enable_server_hostname_verification(true);
  13603. cli.set_follow_location(true);
  13604. auto res = cli.Get("/");
  13605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13606. ASSERT_EQ(StatusCode::OK_200, res->status);
  13607. }
  13608. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13609. SSLClient cli("gOoGlE.COm");
  13610. cli.enable_server_certificate_verification(true);
  13611. cli.enable_server_hostname_verification(true);
  13612. cli.set_follow_location(true);
  13613. auto res = cli.Get("/");
  13614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13615. ASSERT_EQ(StatusCode::OK_200, res->status);
  13616. }
  13617. TEST(SSLClientTest, Issue2004_Online) {
  13618. Client client("https://google.com");
  13619. client.set_follow_location(true);
  13620. auto res = client.Get("/");
  13621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13622. ASSERT_EQ(StatusCode::OK_200, res->status);
  13623. auto body = res->body;
  13624. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13625. }
  13626. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13627. // Create SSLClient with invalid cert/key to make is_valid() return false
  13628. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13629. "nonexistent_key.pem");
  13630. // is_valid() should be false due to cert loading failure
  13631. ASSERT_FALSE(cli.is_valid());
  13632. auto res = cli.Get("/");
  13633. ASSERT_FALSE(res);
  13634. EXPECT_EQ(Error::SSLConnection, res.error());
  13635. }
  13636. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13637. // Test for Issue #2251: SSL error not properly reported when client cert
  13638. // and key paths are swapped or mismatched
  13639. // This simulates the scenario where user accidentally swaps the cert and key
  13640. // files
  13641. // Using client cert file as private key and vice versa (completely wrong)
  13642. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13643. // Should fail validation due to cert/key mismatch
  13644. ASSERT_FALSE(cli.is_valid());
  13645. // Attempt to make a request should fail with proper error
  13646. auto res = cli.Get("/");
  13647. ASSERT_FALSE(res);
  13648. EXPECT_EQ(Error::SSLConnection, res.error());
  13649. // SSL error should be recorded in the Result object (this is the key fix for
  13650. // Issue #2251)
  13651. auto backend_error = res.ssl_backend_error();
  13652. EXPECT_NE(0u, backend_error);
  13653. }
  13654. // Tests cert/key mismatch detection at the TLS context level
  13655. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13656. // Test that using mismatched cert/key causes connection failure.
  13657. // We verify this at the SSLClient level rather than through internal
  13658. // TLS API functions.
  13659. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13660. cli.enable_server_certificate_verification(false);
  13661. cli.set_connection_timeout(2);
  13662. // The mismatch should cause a connection or handshake error
  13663. auto res = cli.Get("/test");
  13664. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13665. // Either way, the request should fail
  13666. EXPECT_FALSE(res);
  13667. }
  13668. #endif
  13669. #if 0
  13670. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13671. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13672. ASSERT_TRUE(cli != nullptr);
  13673. cli->set_address_family(AF_INET6);
  13674. cli->set_interface("en0");
  13675. auto res = cli->Get("/get");
  13676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13677. ASSERT_EQ(StatusCode::OK_200, res->status);
  13678. }
  13679. #endif
  13680. // Client certificate tests - work with all TLS backends
  13681. #ifdef CPPHTTPLIB_SSL_ENABLED
  13682. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13683. void ClientCertPresent(
  13684. const std::string &client_cert_file,
  13685. const std::string &client_private_key_file,
  13686. const std::string &client_encrypted_private_key_pass = std::string(),
  13687. const ClientCertServerSetup &setup = nullptr) {
  13688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13689. ASSERT_TRUE(svr.is_valid());
  13690. if (setup) { setup(svr); }
  13691. svr.Get("/test", [&](const Request &req, Response &res) {
  13692. res.set_content("test", "text/plain");
  13693. auto cert = req.peer_cert();
  13694. ASSERT_TRUE(static_cast<bool>(cert));
  13695. std::string common_name = cert.subject_cn();
  13696. EXPECT_EQ("Common Name", common_name);
  13697. });
  13698. auto port = svr.bind_to_any_port(HOST);
  13699. ASSERT_LT(0, port);
  13700. thread t = thread([&]() { svr.listen_after_bind(); });
  13701. auto se = detail::scope_exit([&] {
  13702. svr.stop();
  13703. t.join();
  13704. ASSERT_FALSE(svr.is_running());
  13705. });
  13706. svr.wait_until_ready();
  13707. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13708. client_encrypted_private_key_pass);
  13709. cli.enable_server_certificate_verification(false);
  13710. cli.set_connection_timeout(30);
  13711. auto res = cli.Get("/test");
  13712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13713. ASSERT_EQ(StatusCode::OK_200, res->status);
  13714. }
  13715. TEST(SSLClientServerTest, ClientCertPresent) {
  13716. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13717. }
  13718. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13719. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13720. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13721. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13722. }
  13723. // Expects svr, which must require client certificates, to reject a client
  13724. // that has none
  13725. void RejectsClientWithoutCert(SSLServer &svr) {
  13726. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13727. auto port = svr.bind_to_any_port(HOST);
  13728. ASSERT_LT(0, port);
  13729. thread t = thread([&]() { svr.listen_after_bind(); });
  13730. auto se = detail::scope_exit([&] {
  13731. svr.stop();
  13732. t.join();
  13733. ASSERT_FALSE(svr.is_running());
  13734. });
  13735. svr.wait_until_ready();
  13736. SSLClient cli(HOST, port);
  13737. cli.set_connection_timeout(30);
  13738. // Skip the server certificate check, so that the request fails because the
  13739. // client certificate is missing rather than because cert.pem is not trusted
  13740. cli.enable_server_certificate_verification(false);
  13741. auto res = cli.Get("/test");
  13742. ASSERT_FALSE(res);
  13743. // The server rejects the client during the handshake, or on TLS 1.3 right
  13744. // after it, which the client notices on its first write or read
  13745. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13746. res.error() == Error::Write || res.error() == Error::Read)
  13747. << to_string(res.error());
  13748. if (res.error() == Error::SSLConnection) {
  13749. EXPECT_NE(0UL, res.ssl_backend_error());
  13750. }
  13751. // A rejection noticed on the write keeps the TLS error the write hit
  13752. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13753. }
  13754. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13756. ASSERT_TRUE(svr.is_valid());
  13757. if (setup) { setup(svr); }
  13758. RejectsClientWithoutCert(svr);
  13759. }
  13760. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13761. // A server that requires client certificates must keep requiring them after
  13762. // setup changes it, and keep accepting a client that has one
  13763. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13764. ClientCertMissing(setup);
  13765. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13766. setup);
  13767. }
  13768. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13769. ClientCertStillRequired([](SSLServer &svr) {
  13770. ASSERT_TRUE(tls::set_verify_callback(
  13771. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13772. });
  13773. }
  13774. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13775. ClientCertStillRequired([](SSLServer &svr) {
  13776. ASSERT_TRUE(tls::set_verify_callback(
  13777. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13778. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13779. });
  13780. }
  13781. // The client verifies the server certificate during the handshake, so a
  13782. // server that fails the check never gets the client certificate, even when a
  13783. // verifier of the client's own accepts it
  13784. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13785. struct Case {
  13786. const char *trusted_ca;
  13787. const char *host;
  13788. Error error;
  13789. };
  13790. // cert2.pem names localhost: the first client does not trust it, and the
  13791. // second trusts it but asks for another name
  13792. for (const auto &c :
  13793. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13794. Case{SERVER_CERT2_FILE, "example.com",
  13795. Error::SSLServerHostnameVerification}}) {
  13796. for (auto with_verifier : {false, true}) {
  13797. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13798. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13799. CLIENT_CA_CERT_FILE);
  13800. ASSERT_TRUE(svr.is_valid());
  13801. std::atomic<bool> got_client_cert{false};
  13802. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13803. [&](const tls::VerifyContext &) {
  13804. got_client_cert = true;
  13805. return true;
  13806. }));
  13807. auto port = svr.bind_to_any_port("127.0.0.1");
  13808. ASSERT_LT(0, port);
  13809. thread t = thread([&] { svr.listen_after_bind(); });
  13810. svr.wait_until_ready();
  13811. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13812. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13813. cli.set_ca_cert_path(c.trusted_ca);
  13814. if (with_verifier) {
  13815. cli.set_server_certificate_verifier(
  13816. [](const tls::VerifyContext &) { return true; });
  13817. }
  13818. auto res = cli.Get("/");
  13819. EXPECT_FALSE(res);
  13820. EXPECT_EQ(c.error, res.error());
  13821. svr.stop();
  13822. t.join();
  13823. EXPECT_FALSE(got_client_cert);
  13824. }
  13825. }
  13826. }
  13827. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13828. std::string cert_pem, key_pem, ca_pem;
  13829. read_file(SERVER_CERT_FILE, cert_pem);
  13830. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13831. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13832. ASSERT_TRUE(
  13833. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13834. }
  13835. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13837. ASSERT_TRUE(svr.is_valid());
  13838. UpdateCertsPemWithClientCA(svr);
  13839. RejectsClientWithoutCert(svr);
  13840. }
  13841. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13842. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13843. }
  13844. // A TLS error from one request must not show up in a later request's Result
  13845. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13847. ASSERT_TRUE(svr.is_valid());
  13848. svr.Get("/test", [](const Request &, Response &res) {
  13849. res.set_content("test", "text/plain");
  13850. });
  13851. auto port = svr.bind_to_any_port(HOST);
  13852. ASSERT_LT(0, port);
  13853. thread t = thread([&]() { svr.listen_after_bind(); });
  13854. auto se = detail::scope_exit([&] {
  13855. svr.stop();
  13856. t.join();
  13857. ASSERT_FALSE(svr.is_running());
  13858. });
  13859. svr.wait_until_ready();
  13860. SSLClient cli(HOST, port);
  13861. cli.set_connection_timeout(30);
  13862. cli.enable_server_hostname_verification(false);
  13863. // cert.pem is not trusted, so the handshake fails
  13864. ASSERT_FALSE(cli.Get("/test"));
  13865. cli.enable_server_certificate_verification(false);
  13866. auto res = cli.Get("/test");
  13867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13868. EXPECT_EQ(0, res.ssl_error());
  13869. EXPECT_EQ(0UL, res.ssl_backend_error());
  13870. }
  13871. // PEM memory-based constructor tests (works with all TLS backends).
  13872. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13873. // terminator after it.
  13874. void PemMemoryClientCertPresent(
  13875. const std::string &client_cert_file,
  13876. const std::string &client_private_key_file,
  13877. const std::string &client_encrypted_private_key_pass = std::string(),
  13878. bool exact_size = false) {
  13879. // Read PEM files into memory
  13880. std::string server_cert_pem, server_key_pem;
  13881. std::string client_ca_pem;
  13882. std::string client_cert_pem, client_key_pem;
  13883. read_file(SERVER_CERT_FILE, server_cert_pem);
  13884. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13885. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13886. read_file(client_cert_file, client_cert_pem);
  13887. read_file(client_private_key_file, client_key_pem);
  13888. std::list<std::vector<char>> exact_copies;
  13889. auto data = [&](const std::string &pem) -> const char * {
  13890. if (!exact_size) { return pem.c_str(); }
  13891. exact_copies.emplace_back(pem.begin(), pem.end());
  13892. return exact_copies.back().data();
  13893. };
  13894. // Create server with PEM memory
  13895. SSLServer::PemMemory server_pem = {
  13896. data(server_cert_pem),
  13897. server_cert_pem.size(),
  13898. data(server_key_pem),
  13899. server_key_pem.size(),
  13900. data(client_ca_pem),
  13901. client_ca_pem.size(),
  13902. nullptr // no password for server key
  13903. };
  13904. SSLServer svr(server_pem);
  13905. ASSERT_TRUE(svr.is_valid());
  13906. svr.Get("/test", [&](const Request &req, Response &res) {
  13907. res.set_content("test", "text/plain");
  13908. auto cert = req.peer_cert();
  13909. ASSERT_TRUE(static_cast<bool>(cert));
  13910. EXPECT_EQ("Common Name", cert.subject_cn());
  13911. });
  13912. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13913. auto se = detail::scope_exit([&] {
  13914. svr.stop();
  13915. t.join();
  13916. ASSERT_FALSE(svr.is_running());
  13917. });
  13918. svr.wait_until_ready();
  13919. // Create client with PEM memory
  13920. const char *password = client_encrypted_private_key_pass.empty()
  13921. ? nullptr
  13922. : client_encrypted_private_key_pass.c_str();
  13923. SSLClient::PemMemory client_pem = {
  13924. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13925. client_key_pem.size(), password};
  13926. SSLClient cli(HOST, PORT, client_pem);
  13927. cli.enable_server_certificate_verification(false);
  13928. cli.set_connection_timeout(30);
  13929. auto res = cli.Get("/test");
  13930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13931. ASSERT_EQ(StatusCode::OK_200, res->status);
  13932. }
  13933. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13934. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13935. }
  13936. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13937. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13938. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13939. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13940. }
  13941. // A server built from PEM memory with a client CA requires client certificates,
  13942. // also when the CA is a NUL-terminated string passed with a length of 0
  13943. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13944. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13945. read_file(SERVER_CERT_FILE, server_cert_pem);
  13946. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13947. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13948. SSLServer::PemMemory server_pem = {
  13949. server_cert_pem.c_str(),
  13950. server_cert_pem.size(),
  13951. server_key_pem.c_str(),
  13952. server_key_pem.size(),
  13953. client_ca_pem.c_str(),
  13954. client_ca_pem.size(),
  13955. nullptr // no password for server key
  13956. };
  13957. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13958. SCOPED_TRACE(client_ca_pem_len);
  13959. server_pem.client_ca_pem_len = client_ca_pem_len;
  13960. SSLServer svr(server_pem);
  13961. ASSERT_TRUE(svr.is_valid());
  13962. RejectsClientWithoutCert(svr);
  13963. }
  13964. // An empty CA fails to load instead of turning the check off
  13965. server_pem.client_ca_pem = "";
  13966. server_pem.client_ca_pem_len = 0;
  13967. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13968. }
  13969. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13970. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13971. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13972. true);
  13973. }
  13974. // A length shorter than the PEM cuts it short, so it no longer loads
  13975. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13976. std::string cert, key;
  13977. read_file(SERVER_CERT_FILE, cert);
  13978. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13979. for (auto cut_cert : {true, false}) {
  13980. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13981. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13982. SSLServer::PemMemory server_pem = {
  13983. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13984. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13985. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13986. key_len, nullptr};
  13987. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13988. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13989. key.c_str(), key_len, nullptr};
  13990. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13991. }
  13992. }
  13993. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13994. class NoListenSSLServer : public SSLServer {
  13995. public:
  13996. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13997. const char *client_ca_cert_file_path,
  13998. const char *client_ca_cert_dir_path = nullptr)
  13999. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14000. client_ca_cert_dir_path),
  14001. stop_(false) {}
  14002. std::atomic_bool stop_;
  14003. private:
  14004. bool process_and_close_socket(socket_t /*sock*/) override {
  14005. // Don't create SSL context
  14006. while (!stop_.load()) {
  14007. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14008. }
  14009. return true;
  14010. }
  14011. };
  14012. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14013. CLIENT_CA_CERT_FILE);
  14014. ASSERT_TRUE(svr.is_valid());
  14015. svr.Get("/test", [&](const Request &, Response &res) {
  14016. res.set_content("test", "text/plain");
  14017. });
  14018. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14019. auto se = detail::scope_exit([&] {
  14020. svr.stop_ = true;
  14021. svr.stop();
  14022. t.join();
  14023. ASSERT_FALSE(svr.is_running());
  14024. });
  14025. svr.wait_until_ready();
  14026. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14027. cli.enable_server_certificate_verification(false);
  14028. cli.set_connection_timeout(1);
  14029. auto res = cli.Get("/test");
  14030. ASSERT_TRUE(!res);
  14031. EXPECT_EQ(Error::SSLConnection, res.error());
  14032. // Timeout results in WantRead error code (maps to backend-specific value)
  14033. EXPECT_NE(0, res.ssl_error());
  14034. }
  14035. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14036. // Test SSLServer with client certificate verification using the standard
  14037. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14039. CLIENT_CA_CERT_DIR);
  14040. ASSERT_TRUE(svr.is_valid());
  14041. svr.Get("/test", [&](const Request &req, Response &res) {
  14042. res.set_content("test", "text/plain");
  14043. auto cert = req.peer_cert();
  14044. ASSERT_TRUE(static_cast<bool>(cert));
  14045. auto common_name = cert.subject_cn();
  14046. EXPECT_EQ("Common Name", common_name);
  14047. });
  14048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14049. auto se = detail::scope_exit([&] {
  14050. svr.stop();
  14051. t.join();
  14052. ASSERT_FALSE(svr.is_running());
  14053. });
  14054. svr.wait_until_ready();
  14055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14056. cli.enable_server_certificate_verification(false);
  14057. cli.set_connection_timeout(30);
  14058. auto res = cli.Get("/test");
  14059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14060. ASSERT_EQ(StatusCode::OK_200, res->status);
  14061. }
  14062. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14063. // Verifies that wildcard matching and exact matching work consistently
  14064. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14065. using namespace httplib::tls;
  14066. // We need a running server to test against
  14067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14068. ASSERT_TRUE(svr.is_valid());
  14069. svr.Get("/test", [](const Request &, Response &res) {
  14070. res.set_content("ok", "text/plain");
  14071. });
  14072. thread t([&]() { svr.listen(HOST, PORT); });
  14073. auto se = detail::scope_exit([&] {
  14074. svr.stop();
  14075. t.join();
  14076. });
  14077. svr.wait_until_ready();
  14078. bool verify_callback_called = false;
  14079. bool verify_result_wrong = false;
  14080. SSLClient cli(HOST, PORT);
  14081. cli.enable_server_certificate_verification(true);
  14082. cli.set_ca_cert_path(CA_CERT_FILE);
  14083. cli.set_connection_timeout(5);
  14084. // Note: Test certificate has CN="Common Name", not "localhost"
  14085. bool verify_result_cn = false;
  14086. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14087. verify_callback_called = true;
  14088. if (!ctx.cert) return false;
  14089. // Test 1: "Common Name" should match (our test server cert CN)
  14090. verify_result_cn = ctx.check_hostname("Common Name");
  14091. // Test 2: wrong hostname should not match
  14092. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14093. return true; // Accept for the purpose of this test
  14094. });
  14095. auto res = cli.Get("/test");
  14096. // The request may succeed or fail depending on cert configuration
  14097. // but the callback should have been called
  14098. ASSERT_TRUE(verify_callback_called)
  14099. << "Verify callback should have been called";
  14100. // CN="Common Name" should match our test certificate
  14101. //
  14102. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14103. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14104. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14105. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14106. // <openssl/base.h>, which is included transitively when
  14107. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14108. #if defined(OPENSSL_IS_BORINGSSL)
  14109. EXPECT_FALSE(verify_result_cn)
  14110. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14111. #else
  14112. EXPECT_TRUE(verify_result_cn)
  14113. << "verify_hostname should match 'Common Name' (certificate CN)";
  14114. #endif
  14115. // Wrong hostname should not match
  14116. EXPECT_FALSE(verify_result_wrong)
  14117. << "verify_hostname should not match 'wronghost.example.com'";
  14118. }
  14119. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14120. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14121. // X509_check_ip behavior and must hold for every backend.
  14122. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14123. using namespace httplib::tls;
  14124. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14125. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14126. ASSERT_TRUE(svr.is_valid());
  14127. svr.Get("/test", [](const Request &, Response &res) {
  14128. res.set_content("ok", "text/plain");
  14129. });
  14130. thread t([&]() { svr.listen(HOST, PORT); });
  14131. auto se = detail::scope_exit([&] {
  14132. svr.stop();
  14133. t.join();
  14134. });
  14135. svr.wait_until_ready();
  14136. bool verify_callback_called = false;
  14137. bool ip_matched_via_cn = true;
  14138. SSLClient cli(HOST, PORT);
  14139. cli.enable_server_certificate_verification(true);
  14140. cli.set_ca_cert_path(CA_CERT_FILE);
  14141. cli.set_connection_timeout(5);
  14142. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14143. verify_callback_called = true;
  14144. if (!ctx.cert) return false;
  14145. // The IP appears only in the CN, so it must NOT be accepted.
  14146. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14147. return true; // Accept for the purpose of this test
  14148. });
  14149. cli.Get("/test");
  14150. ASSERT_TRUE(verify_callback_called)
  14151. << "Verify callback should have been called";
  14152. EXPECT_FALSE(ip_matched_via_cn)
  14153. << "An IP host must not be authenticated via the certificate CN";
  14154. }
  14155. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14156. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14157. using namespace httplib::tls;
  14158. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14159. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14160. ASSERT_TRUE(svr.is_valid());
  14161. svr.Get("/test", [](const Request &, Response &res) {
  14162. res.set_content("ok", "text/plain");
  14163. });
  14164. thread t([&]() { svr.listen(HOST, PORT); });
  14165. auto se = detail::scope_exit([&] {
  14166. svr.stop();
  14167. t.join();
  14168. });
  14169. svr.wait_until_ready();
  14170. bool verify_callback_called = false;
  14171. bool san_matched = false;
  14172. bool wrong_ipv6_matched = true;
  14173. bool cn_ipv6_matched = true;
  14174. SSLClient cli(HOST, PORT);
  14175. cli.enable_server_certificate_verification(true);
  14176. cli.set_ca_cert_path(CA_CERT_FILE);
  14177. cli.set_connection_timeout(5);
  14178. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14179. verify_callback_called = true;
  14180. if (!ctx.cert) return false;
  14181. // Matches the IPv6 iPAddress SAN.
  14182. san_matched = ctx.check_hostname("2001:db8::1");
  14183. // A different IPv6 address must not match.
  14184. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14185. // "::1" lives only in the CN, so it must not be accepted.
  14186. cn_ipv6_matched = ctx.check_hostname("::1");
  14187. return true; // Accept for the purpose of this test
  14188. });
  14189. cli.Get("/test");
  14190. ASSERT_TRUE(verify_callback_called)
  14191. << "Verify callback should have been called";
  14192. EXPECT_TRUE(san_matched)
  14193. << "verify_hostname should match an IPv6 iPAddress SAN";
  14194. EXPECT_FALSE(wrong_ipv6_matched)
  14195. << "verify_hostname should not match a non-matching IPv6 address";
  14196. EXPECT_FALSE(cn_ipv6_matched)
  14197. << "An IPv6 host must not be authenticated via the certificate CN";
  14198. }
  14199. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14200. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14201. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14202. using namespace httplib::tls;
  14203. // SANs: DNS:a.zz, IP:42.46.122.122
  14204. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14205. ASSERT_TRUE(svr.is_valid());
  14206. svr.Get("/test", [](const Request &, Response &res) {
  14207. res.set_content("ok", "text/plain");
  14208. });
  14209. auto port = svr.bind_to_any_port(HOST);
  14210. thread t([&]() { svr.listen_after_bind(); });
  14211. auto se = detail::scope_exit([&] {
  14212. svr.stop();
  14213. t.join();
  14214. });
  14215. svr.wait_until_ready();
  14216. bool verify_callback_called = false;
  14217. bool dns_san_matched = false;
  14218. bool ip_san_matched = false;
  14219. bool ip_matched_via_dns_san = true;
  14220. bool dns_matched_via_ip_san = true;
  14221. bool cn_matched_next_to_dns_san = true;
  14222. SSLClient cli(HOST, port);
  14223. cli.enable_server_certificate_verification(true);
  14224. cli.set_ca_cert_path(CA_CERT_FILE);
  14225. cli.set_connection_timeout(5);
  14226. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14227. verify_callback_called = true;
  14228. if (!ctx.cert) return false;
  14229. dns_san_matched = ctx.check_hostname("a.zz");
  14230. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14231. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14232. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14233. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14234. return true; // Accept for the purpose of this test
  14235. });
  14236. cli.Get("/test");
  14237. ASSERT_TRUE(verify_callback_called)
  14238. << "Verify callback should have been called";
  14239. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14240. EXPECT_TRUE(ip_san_matched)
  14241. << "verify_hostname should match an iPAddress SAN";
  14242. EXPECT_FALSE(ip_matched_via_dns_san)
  14243. << "An IP host must not be authenticated via a dNSName SAN";
  14244. EXPECT_FALSE(dns_matched_via_ip_san)
  14245. << "A DNS host must not be authenticated via an iPAddress SAN";
  14246. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14247. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14248. }
  14249. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14250. // "www.*.example.test" names one host and not every host under example.test.
  14251. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14252. using namespace httplib::tls;
  14253. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14254. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14255. ASSERT_TRUE(svr.is_valid());
  14256. svr.Get("/test", [](const Request &, Response &res) {
  14257. res.set_content("ok", "text/plain");
  14258. });
  14259. auto port = svr.bind_to_any_port(HOST);
  14260. thread t([&]() { svr.listen_after_bind(); });
  14261. auto se = detail::scope_exit([&] {
  14262. svr.stop();
  14263. t.join();
  14264. });
  14265. svr.wait_until_ready();
  14266. bool verify_callback_called = false;
  14267. bool leftmost_wildcard_matched = false;
  14268. bool wildcard_spanned_labels = true;
  14269. bool inner_wildcard_matched = true;
  14270. SSLClient cli(HOST, port);
  14271. cli.enable_server_certificate_verification(true);
  14272. cli.set_ca_cert_path(CA_CERT_FILE);
  14273. cli.set_connection_timeout(5);
  14274. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14275. verify_callback_called = true;
  14276. if (!ctx.cert) return false;
  14277. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14278. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14279. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14280. return true; // Accept for the purpose of this test
  14281. });
  14282. cli.Get("/test");
  14283. ASSERT_TRUE(verify_callback_called)
  14284. << "Verify callback should have been called";
  14285. EXPECT_TRUE(leftmost_wildcard_matched)
  14286. << "A leftmost wildcard should match a single label";
  14287. EXPECT_FALSE(wildcard_spanned_labels)
  14288. << "A wildcard label must not match more than one label";
  14289. EXPECT_FALSE(inner_wildcard_matched)
  14290. << "A wildcard outside the leftmost label must not be honoured";
  14291. }
  14292. // sans() must report each SAN entry under its own type.
  14293. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14294. using namespace httplib::tls;
  14295. // SANs: DNS:a.zz, IP:42.46.122.122
  14296. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14297. ASSERT_TRUE(svr.is_valid());
  14298. svr.Get("/test", [](const Request &, Response &res) {
  14299. res.set_content("ok", "text/plain");
  14300. });
  14301. auto port = svr.bind_to_any_port(HOST);
  14302. thread t([&]() { svr.listen_after_bind(); });
  14303. auto se = detail::scope_exit([&] {
  14304. svr.stop();
  14305. t.join();
  14306. });
  14307. svr.wait_until_ready();
  14308. bool verify_callback_called = false;
  14309. std::vector<SanEntry> sans;
  14310. SSLClient cli(HOST, port);
  14311. cli.enable_server_certificate_verification(true);
  14312. cli.set_ca_cert_path(CA_CERT_FILE);
  14313. cli.set_connection_timeout(5);
  14314. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14315. verify_callback_called = true;
  14316. if (!ctx.cert) return false;
  14317. sans = ctx.sans();
  14318. return true; // Accept for the purpose of this test
  14319. });
  14320. cli.Get("/test");
  14321. ASSERT_TRUE(verify_callback_called)
  14322. << "Verify callback should have been called";
  14323. auto has_san = [&](SanType type, const std::string &value) {
  14324. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14325. return san.type == type && san.value == value;
  14326. });
  14327. };
  14328. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14329. << "sans() should report the dNSName SAN";
  14330. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14331. << "sans() should report the iPAddress SAN";
  14332. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14333. << "sans() must not report the dNSName SAN as an address";
  14334. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14335. << "sans() must not report the iPAddress SAN as a DNS name";
  14336. }
  14337. #endif
  14338. // mbedTLS-specific callback constructor test
  14339. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14340. #ifdef CPPHTTPLIB_SSL_ENABLED
  14341. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14343. ASSERT_TRUE(svr.is_valid());
  14344. // Set up a handler to verify client certificate is present
  14345. bool client_cert_verified = false;
  14346. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14347. // Verify that client certificate was provided
  14348. client_cert_verified = true;
  14349. res.set_content("success", "text/plain");
  14350. });
  14351. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14352. auto se = detail::scope_exit([&] {
  14353. svr.stop();
  14354. t.join();
  14355. ASSERT_FALSE(svr.is_running());
  14356. });
  14357. svr.wait_until_ready();
  14358. // Client with certificate
  14359. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14360. cli.enable_server_certificate_verification(false);
  14361. cli.set_connection_timeout(30);
  14362. auto res = cli.Get("/test");
  14363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14364. ASSERT_EQ(StatusCode::OK_200, res->status);
  14365. ASSERT_TRUE(client_cert_verified);
  14366. EXPECT_EQ("success", res->body);
  14367. }
  14368. #endif
  14369. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14370. // backends
  14371. #ifdef CPPHTTPLIB_SSL_ENABLED
  14372. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14373. using namespace httplib::tls;
  14374. // Test that when client CA cert file is provided,
  14375. // the server properly requests and validates client certificates
  14376. // Create a server with client authentication
  14377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14378. ASSERT_TRUE(svr.is_valid());
  14379. bool handler_called = false;
  14380. svr.Get("/test", [&](const Request &req, Response &res) {
  14381. handler_called = true;
  14382. // Verify that a client certificate was provided
  14383. auto cert = req.peer_cert();
  14384. ASSERT_TRUE(static_cast<bool>(cert));
  14385. // Get the issuer name
  14386. std::string issuer_str = cert.issuer_name();
  14387. ASSERT_FALSE(issuer_str.empty());
  14388. // The client certificate should be issued by our test CA
  14389. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14390. res.set_content("authenticated", "text/plain");
  14391. });
  14392. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14393. auto se = detail::scope_exit([&] {
  14394. svr.stop();
  14395. t.join();
  14396. ASSERT_FALSE(svr.is_running());
  14397. });
  14398. svr.wait_until_ready();
  14399. // Connect with a client certificate issued by the CA
  14400. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14401. cli.enable_server_certificate_verification(false);
  14402. cli.set_connection_timeout(30);
  14403. auto res = cli.Get("/test");
  14404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14405. ASSERT_EQ(StatusCode::OK_200, res->status);
  14406. ASSERT_TRUE(handler_called);
  14407. EXPECT_EQ("authenticated", res->body);
  14408. }
  14409. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14410. using namespace httplib::tls;
  14411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14412. ASSERT_TRUE(svr.is_valid());
  14413. svr.Get("/test", [](const Request &, Response &res) {
  14414. res.set_content("ok", "text/plain");
  14415. });
  14416. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14417. auto se = detail::scope_exit([&] {
  14418. svr.stop();
  14419. t.join();
  14420. });
  14421. svr.wait_until_ready();
  14422. SSLClient cli(HOST, PORT);
  14423. cli.enable_server_certificate_verification(false);
  14424. cli.set_connection_timeout(30);
  14425. bool cert_checked = false;
  14426. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14427. if (ctx.cert) {
  14428. auto sans = ctx.sans();
  14429. // Test certificate may or may not have SANs - just verify the API
  14430. // works If SANs exist, verify the types are valid
  14431. for (const auto &san : sans) {
  14432. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14433. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14434. san.type == SanType::OTHER);
  14435. EXPECT_FALSE(san.value.empty());
  14436. }
  14437. cert_checked = true;
  14438. }
  14439. return true;
  14440. });
  14441. auto res = cli.Get("/test");
  14442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14443. EXPECT_TRUE(cert_checked);
  14444. }
  14445. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14446. using namespace httplib::tls;
  14447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14448. ASSERT_TRUE(svr.is_valid());
  14449. svr.Get("/test", [](const Request &, Response &res) {
  14450. res.set_content("ok", "text/plain");
  14451. });
  14452. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14453. auto se = detail::scope_exit([&] {
  14454. svr.stop();
  14455. t.join();
  14456. });
  14457. svr.wait_until_ready();
  14458. SSLClient cli(HOST, PORT);
  14459. cli.enable_server_certificate_verification(false);
  14460. cli.set_connection_timeout(30);
  14461. bool validity_checked = false;
  14462. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14463. if (ctx.cert) {
  14464. time_t not_before = 0, not_after = 0;
  14465. bool result = ctx.validity(not_before, not_after);
  14466. EXPECT_TRUE(result);
  14467. // Verify that not_before < now < not_after for a valid cert
  14468. time_t now = time(nullptr);
  14469. EXPECT_LT(not_before, now);
  14470. EXPECT_GT(not_after, now);
  14471. validity_checked = true;
  14472. }
  14473. return true;
  14474. });
  14475. auto res = cli.Get("/test");
  14476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14477. EXPECT_TRUE(validity_checked);
  14478. }
  14479. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14480. using namespace httplib::tls;
  14481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14482. ASSERT_TRUE(svr.is_valid());
  14483. svr.Get("/test", [](const Request &, Response &res) {
  14484. res.set_content("ok", "text/plain");
  14485. });
  14486. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14487. auto se = detail::scope_exit([&] {
  14488. svr.stop();
  14489. t.join();
  14490. });
  14491. svr.wait_until_ready();
  14492. SSLClient cli(HOST, PORT);
  14493. cli.enable_server_certificate_verification(false);
  14494. cli.set_connection_timeout(30);
  14495. bool serial_checked = false;
  14496. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14497. if (ctx.cert) {
  14498. std::string serial = ctx.serial();
  14499. EXPECT_FALSE(serial.empty());
  14500. // Serial should be a hex string
  14501. for (char c : serial) {
  14502. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14503. (c >= 'a' && c <= 'f'));
  14504. }
  14505. serial_checked = true;
  14506. }
  14507. return true;
  14508. });
  14509. auto res = cli.Get("/test");
  14510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14511. EXPECT_TRUE(serial_checked);
  14512. }
  14513. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14514. // Test 1: Valid CA file - no error should be recorded
  14515. {
  14516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14517. CLIENT_CA_CERT_FILE);
  14518. ASSERT_TRUE(svr.is_valid());
  14519. // With valid setup, last_ssl_error should be 0
  14520. EXPECT_EQ(0, svr.ssl_last_error());
  14521. }
  14522. // Test 2: Invalid CA file content
  14523. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14524. {
  14525. // Create a temporary file with completely invalid content
  14526. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14527. {
  14528. std::ofstream ofs(temp_invalid_ca);
  14529. ofs << "This is not a certificate file at all\n";
  14530. ofs << "Just plain text content\n";
  14531. }
  14532. // Create server with invalid CA file
  14533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14534. // Clean up temporary file
  14535. std::remove(temp_invalid_ca);
  14536. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14537. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14538. // Note: SSL_CTX_load_verify_locations typically fails first,
  14539. // but our error handling code path is still exercised
  14540. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14541. }
  14542. }
  14543. TEST(VerifyCallbackTest, VerifyContextFields) {
  14544. using namespace httplib::tls;
  14545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14546. ASSERT_TRUE(svr.is_valid());
  14547. svr.Get("/test", [](const Request &, Response &res) {
  14548. res.set_content("ok", "text/plain");
  14549. });
  14550. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14551. auto se = detail::scope_exit([&] {
  14552. svr.stop();
  14553. t.join();
  14554. });
  14555. svr.wait_until_ready();
  14556. SSLClient cli(HOST, PORT);
  14557. cli.enable_server_certificate_verification(false);
  14558. cli.set_connection_timeout(30);
  14559. int callback_count = 0;
  14560. bool saw_leaf_cert = false;
  14561. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14562. if (ctx.cert) {
  14563. callback_count++;
  14564. // We should see at least one certificate (the leaf)
  14565. std::string cn = ctx.subject_cn();
  14566. if (!cn.empty()) { saw_leaf_cert = true; }
  14567. // Verify context fields are populated
  14568. EXPECT_NE(ctx.session, nullptr);
  14569. EXPECT_GE(ctx.depth, 0);
  14570. }
  14571. return true;
  14572. });
  14573. auto res = cli.Get("/test");
  14574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14575. EXPECT_GT(callback_count, 0);
  14576. EXPECT_TRUE(saw_leaf_cert);
  14577. }
  14578. // A verifier that accepts runs alongside the built-in verification, and is the
  14579. // only check once that is turned off.
  14580. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14581. using namespace httplib::tls;
  14582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14583. ASSERT_TRUE(svr.is_valid());
  14584. svr.Get("/test", [](const Request &, Response &res) {
  14585. res.set_content("ok", "text/plain");
  14586. });
  14587. auto port = svr.bind_to_any_port(HOST);
  14588. thread t([&]() { svr.listen_after_bind(); });
  14589. auto se = detail::scope_exit([&] {
  14590. svr.stop();
  14591. t.join();
  14592. });
  14593. svr.wait_until_ready();
  14594. SSLClient cli(HOST, port);
  14595. cli.enable_server_hostname_verification(false);
  14596. auto calls = 0;
  14597. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14598. calls++;
  14599. return true;
  14600. });
  14601. // cert.pem is not trusted
  14602. auto res = cli.Get("/test");
  14603. ASSERT_FALSE(res);
  14604. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14605. EXPECT_GT(calls, 0);
  14606. cli.enable_server_certificate_verification(false);
  14607. res = cli.Get("/test");
  14608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14609. EXPECT_EQ("ok", res->body);
  14610. }
  14611. // A verifier belongs to the client that set it, not to the thread that set it.
  14612. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14613. using namespace httplib::tls;
  14614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14615. ASSERT_TRUE(svr.is_valid());
  14616. svr.Get("/test", [](const Request &, Response &res) {
  14617. res.set_content("ok", "text/plain");
  14618. });
  14619. auto port = svr.bind_to_any_port(HOST);
  14620. thread t([&]() { svr.listen_after_bind(); });
  14621. auto se = detail::scope_exit([&] {
  14622. svr.stop();
  14623. t.join();
  14624. });
  14625. svr.wait_until_ready();
  14626. auto rejecting_calls = 0;
  14627. SSLClient rejecting(HOST, port);
  14628. rejecting.enable_server_certificate_verification(false);
  14629. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14630. rejecting_calls++;
  14631. return false;
  14632. });
  14633. auto accepting_calls = 0;
  14634. SSLClient accepting(HOST, port);
  14635. accepting.enable_server_certificate_verification(false);
  14636. // Set on another thread than the requests below.
  14637. thread([&]() {
  14638. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14639. accepting_calls++;
  14640. return true;
  14641. });
  14642. }).join();
  14643. // Requested on another thread than the verifier was set on.
  14644. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14645. EXPECT_GT(rejecting_calls, 0);
  14646. auto res = accepting.Get("/test");
  14647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14648. EXPECT_GT(accepting_calls, 0);
  14649. }
  14650. // A verifier replaced while a handshake runs it lives until it returns.
  14651. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14652. using namespace httplib::tls;
  14653. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14654. ASSERT_TRUE(svr.is_valid());
  14655. svr.Get("/test", [](const Request &, Response &res) {
  14656. res.set_content("ok", "text/plain");
  14657. });
  14658. auto port = svr.bind_to_any_port(HOST);
  14659. thread t([&]() { svr.listen_after_bind(); });
  14660. auto se = detail::scope_exit([&] {
  14661. svr.stop();
  14662. t.join();
  14663. });
  14664. svr.wait_until_ready();
  14665. SSLClient cli(HOST, port);
  14666. cli.enable_server_certificate_verification(false);
  14667. std::promise<void> entered;
  14668. std::promise<void> replaced;
  14669. auto replaced_future = replaced.get_future();
  14670. auto first_call = true;
  14671. // Long enough to live on the heap
  14672. std::string expected(64, 'v');
  14673. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14674. if (first_call) {
  14675. first_call = false;
  14676. entered.set_value();
  14677. replaced_future.wait();
  14678. }
  14679. return expected == std::string(64, 'v');
  14680. });
  14681. thread request([&]() {
  14682. auto res = cli.Get("/test");
  14683. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14684. });
  14685. entered.get_future().wait();
  14686. cli.set_server_certificate_verifier(
  14687. [](const VerifyContext &) { return true; });
  14688. replaced.set_value();
  14689. request.join();
  14690. }
  14691. // VerifyContext::session is the same handle the other tls:: functions take.
  14692. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14693. using namespace httplib::tls;
  14694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14695. ASSERT_TRUE(svr.is_valid());
  14696. svr.Get("/test", [](const Request &, Response &res) {
  14697. res.set_content("ok", "text/plain");
  14698. });
  14699. auto port = svr.bind_to_any_port(HOST);
  14700. thread t([&]() { svr.listen_after_bind(); });
  14701. auto se = detail::scope_exit([&] {
  14702. svr.stop();
  14703. t.join();
  14704. });
  14705. svr.wait_until_ready();
  14706. SSLClient cli(HOST, port);
  14707. cli.enable_server_certificate_verification(false);
  14708. session_t verifier_session = nullptr;
  14709. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14710. verifier_session = ctx.session;
  14711. return true;
  14712. });
  14713. session_t session_verifier_session = nullptr;
  14714. cli.set_session_verifier([&](session_t session) {
  14715. session_verifier_session = session;
  14716. return SSLVerifierResponse::NoDecisionMade;
  14717. });
  14718. auto res = cli.Get("/test");
  14719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14720. EXPECT_NE(nullptr, verifier_session);
  14721. EXPECT_EQ(session_verifier_session, verifier_session);
  14722. }
  14723. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14724. using httplib::tls::TlsError;
  14725. // Test that verify_error_to_string returns empty for success
  14726. std::string success_str = TlsError::verify_error_to_string(0);
  14727. EXPECT_TRUE(success_str.empty());
  14728. // Test that verify_error_to_string returns non-empty for error codes
  14729. // Using a common error code (certificate expired)
  14730. std::string error_str =
  14731. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14732. EXPECT_FALSE(error_str.empty());
  14733. }
  14734. TEST(SessionVerifierTest, CertificateAccepted) {
  14735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14736. ASSERT_TRUE(svr.is_valid());
  14737. svr.Get("/test", [](const Request &, Response &res) {
  14738. res.set_content("ok", "text/plain");
  14739. });
  14740. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14741. auto se = detail::scope_exit([&] {
  14742. svr.stop();
  14743. t.join();
  14744. });
  14745. svr.wait_until_ready();
  14746. SSLClient cli(HOST, PORT);
  14747. cli.enable_server_certificate_verification(false);
  14748. cli.set_connection_timeout(30);
  14749. bool callback_called = false;
  14750. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14751. EXPECT_NE(session, nullptr);
  14752. callback_called = true;
  14753. return SSLVerifierResponse::CertificateAccepted;
  14754. });
  14755. auto res = cli.Get("/test");
  14756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14757. EXPECT_EQ(200, res->status);
  14758. EXPECT_TRUE(callback_called);
  14759. }
  14760. TEST(SessionVerifierTest, CertificateRejected) {
  14761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14762. ASSERT_TRUE(svr.is_valid());
  14763. svr.Get("/test", [](const Request &, Response &res) {
  14764. res.set_content("ok", "text/plain");
  14765. });
  14766. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14767. auto se = detail::scope_exit([&] {
  14768. svr.stop();
  14769. t.join();
  14770. });
  14771. svr.wait_until_ready();
  14772. SSLClient cli(HOST, PORT);
  14773. cli.enable_server_certificate_verification(false);
  14774. cli.set_connection_timeout(30);
  14775. bool callback_called = false;
  14776. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14777. EXPECT_NE(session, nullptr);
  14778. callback_called = true;
  14779. return SSLVerifierResponse::CertificateRejected;
  14780. });
  14781. auto res = cli.Get("/test");
  14782. EXPECT_FALSE(res);
  14783. EXPECT_TRUE(callback_called);
  14784. }
  14785. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14787. ASSERT_TRUE(svr.is_valid());
  14788. svr.Get("/test", [](const Request &, Response &res) {
  14789. res.set_content("ok", "text/plain");
  14790. });
  14791. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14792. auto se = detail::scope_exit([&] {
  14793. svr.stop();
  14794. t.join();
  14795. });
  14796. svr.wait_until_ready();
  14797. // NoDecisionMade with verification disabled should succeed (no default check)
  14798. SSLClient cli(HOST, PORT);
  14799. cli.enable_server_certificate_verification(false);
  14800. cli.set_connection_timeout(30);
  14801. bool callback_called = false;
  14802. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14803. EXPECT_NE(session, nullptr);
  14804. callback_called = true;
  14805. return SSLVerifierResponse::NoDecisionMade;
  14806. });
  14807. auto res = cli.Get("/test");
  14808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14809. EXPECT_EQ(200, res->status);
  14810. EXPECT_TRUE(callback_called);
  14811. }
  14812. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14814. ASSERT_TRUE(svr.is_valid());
  14815. svr.Get("/test", [](const Request &, Response &res) {
  14816. res.set_content("ok", "text/plain");
  14817. });
  14818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. t.join();
  14822. });
  14823. svr.wait_until_ready();
  14824. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14825. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14826. // so we only check that the request fails, not whether the callback was
  14827. // called.
  14828. SSLClient cli(HOST, PORT);
  14829. cli.enable_server_certificate_verification(true);
  14830. cli.set_connection_timeout(30);
  14831. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14832. EXPECT_NE(session, nullptr);
  14833. return SSLVerifierResponse::NoDecisionMade;
  14834. });
  14835. auto res = cli.Get("/test");
  14836. EXPECT_FALSE(res);
  14837. }
  14838. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14839. // Test SSL server using PemMemory constructor with client CA certificates
  14840. // Read PEM files
  14841. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14842. read_file(SERVER_CERT_FILE, server_cert_pem);
  14843. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14844. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14845. // Create SSLServer with PemMemory constructor including client CA
  14846. SSLServer::PemMemory server_pem = {
  14847. server_cert_pem.c_str(),
  14848. server_cert_pem.size(),
  14849. server_key_pem.c_str(),
  14850. server_key_pem.size(),
  14851. client_ca_pem.c_str(),
  14852. client_ca_pem.size(),
  14853. nullptr // no password for server key
  14854. };
  14855. SSLServer svr(server_pem);
  14856. ASSERT_TRUE(svr.is_valid());
  14857. // No SSL error should be recorded for valid setup
  14858. EXPECT_EQ(0, svr.ssl_last_error());
  14859. // Set up server endpoints
  14860. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14861. res.set_content("ok", "text/plain");
  14862. });
  14863. // Start server in a thread
  14864. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14865. svr.wait_until_ready();
  14866. // Connect with client certificate (using constructor with paths)
  14867. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14868. cli.enable_server_certificate_verification(false);
  14869. auto res = cli.Get("/test-pem-ca");
  14870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14871. EXPECT_EQ(200, res->status);
  14872. EXPECT_EQ("ok", res->body);
  14873. svr.stop();
  14874. server_thread.join();
  14875. }
  14876. #endif
  14877. #ifdef _WIN32
  14878. TEST(CleanupTest, WSACleanup) {
  14879. int ret = WSACleanup();
  14880. ASSERT_EQ(0, ret);
  14881. }
  14882. #endif
  14883. #ifndef CPPHTTPLIB_SSL_ENABLED
  14884. TEST(NoSSLSupport, SimpleInterface) {
  14885. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14886. }
  14887. #endif
  14888. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14889. TEST(InvalidScheme, SimpleInterface) {
  14890. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14891. }
  14892. #endif
  14893. TEST(NoScheme, SimpleInterface) {
  14894. Client cli("yahoo.com:80");
  14895. ASSERT_TRUE(cli.is_valid());
  14896. }
  14897. TEST(SendAPI, SimpleInterface_Online) {
  14898. Client cli("http://yahoo.com");
  14899. Request req;
  14900. req.method = "GET";
  14901. req.path = "/";
  14902. auto res = cli.send(req);
  14903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14904. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14905. }
  14906. TEST(SendAPI, WithParamsInRequest) {
  14907. Server svr;
  14908. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14909. EXPECT_TRUE(req.has_param("test"));
  14910. EXPECT_EQ("test_value", req.get_param_value("test"));
  14911. });
  14912. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14913. auto se = detail::scope_exit([&] {
  14914. svr.stop();
  14915. t.join();
  14916. ASSERT_FALSE(svr.is_running());
  14917. });
  14918. svr.wait_until_ready();
  14919. Client cli(HOST, PORT);
  14920. {
  14921. Request req;
  14922. req.method = "GET";
  14923. req.path = "/";
  14924. req.params.emplace("test", "test_value");
  14925. auto res = cli.send(req);
  14926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14927. }
  14928. {
  14929. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14931. }
  14932. }
  14933. TEST(ClientImplMethods, GetSocketTest) {
  14934. httplib::Server svr;
  14935. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14936. res.status = StatusCode::OK_200;
  14937. });
  14938. auto port = svr.bind_to_any_port("127.0.0.1");
  14939. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14940. auto se = detail::scope_exit([&] {
  14941. svr.stop();
  14942. thread.join();
  14943. ASSERT_FALSE(svr.is_running());
  14944. });
  14945. svr.wait_until_ready();
  14946. {
  14947. httplib::Client cli("127.0.0.1", port);
  14948. cli.set_keep_alive(true);
  14949. // Use the behavior of cpp-httplib of opening the connection
  14950. // only when the first request happens. If that changes,
  14951. // this test would be obsolete.
  14952. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14953. // This also implicitly tests the server. But other tests would fail much
  14954. // earlier than this one to be considered.
  14955. auto res = cli.Get("/");
  14956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14957. EXPECT_EQ(StatusCode::OK_200, res->status);
  14958. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14959. }
  14960. }
  14961. #ifdef CPPHTTPLIB_SSL_ENABLED
  14962. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14963. Client cli("http://yahoo.com");
  14964. auto res = cli.Get("/");
  14965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14966. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14967. cli.set_follow_location(true);
  14968. res = cli.Get("/");
  14969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14970. EXPECT_EQ(StatusCode::OK_200, res->status);
  14971. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14972. }
  14973. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14974. Client cli("https://yahoo.com");
  14975. auto res = cli.Get("/");
  14976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14977. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14978. cli.set_follow_location(true);
  14979. res = cli.Get("/");
  14980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14981. EXPECT_EQ(StatusCode::OK_200, res->status);
  14982. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14983. }
  14984. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14985. Client cli("https://yahoo.com");
  14986. auto res = cli.Get("/");
  14987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14988. ASSERT_FALSE(!res);
  14989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14990. ASSERT_FALSE(res == nullptr);
  14991. ASSERT_TRUE(res != nullptr);
  14992. EXPECT_EQ(Error::Success, res.error());
  14993. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14994. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14995. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14996. cli.set_follow_location(true);
  14997. res = cli.Get("/");
  14998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14999. EXPECT_EQ(Error::Success, res.error());
  15000. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15001. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15002. EXPECT_EQ(StatusCode::OK_200, res->status);
  15003. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15004. }
  15005. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15006. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15007. Client cli("https://cdnjs.cloudflare.com");
  15008. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15009. Headers{{"Accept-Encoding", "br"}});
  15010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15011. EXPECT_EQ(StatusCode::OK_200, res->status);
  15012. EXPECT_EQ(287630U, res->body.size());
  15013. EXPECT_EQ("application/javascript; charset=utf-8",
  15014. res->get_header_value("Content-Type"));
  15015. }
  15016. #endif
  15017. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15018. #undef REDIR_HOST // Silence compiler warning
  15019. #define REDIR_HOST "https://httpbingo.org"
  15020. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15021. Client cli(REDIR_HOST);
  15022. cli.set_follow_location(true);
  15023. auto res =
  15024. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15026. EXPECT_EQ(StatusCode::OK_200, res->status);
  15027. }
  15028. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15029. Client cli(REDIR_HOST);
  15030. cli.set_follow_location(true);
  15031. Params params;
  15032. params.emplace("url", "http://example.com");
  15033. params.emplace("status_code", "302");
  15034. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15036. EXPECT_EQ(StatusCode::OK_200, res->status);
  15037. }
  15038. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15039. Client cli(REDIR_HOST);
  15040. cli.set_follow_location(true);
  15041. Params params;
  15042. params.emplace("url", "http://example.com");
  15043. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15045. EXPECT_EQ(StatusCode::OK_200, res->status);
  15046. }
  15047. TEST(HttpToHttpsRedirectTest, CertFile) {
  15048. auto ssl_port = PORT + 1;
  15049. Server svr;
  15050. ASSERT_TRUE(svr.is_valid());
  15051. svr.Get("/index", [&](const Request &, Response &res) {
  15052. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15053. "/index");
  15054. svr.stop();
  15055. });
  15056. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15057. ASSERT_TRUE(ssl_svr.is_valid());
  15058. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15059. res.set_content("test", "text/plain");
  15060. ssl_svr.stop();
  15061. });
  15062. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15063. thread t2 =
  15064. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15065. auto se = detail::scope_exit([&] {
  15066. t2.join();
  15067. t.join();
  15068. ASSERT_FALSE(svr.is_running());
  15069. });
  15070. svr.wait_until_ready();
  15071. ssl_svr.wait_until_ready();
  15072. Client cli("127.0.0.1", PORT);
  15073. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15074. cli.enable_server_certificate_verification(true);
  15075. cli.set_follow_location(true);
  15076. cli.set_connection_timeout(30);
  15077. auto res = cli.Get("/index");
  15078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15079. ASSERT_EQ(StatusCode::OK_200, res->status);
  15080. }
  15081. TEST(SSLClientRedirectTest, CertFile) {
  15082. auto ssl_port = PORT + 1;
  15083. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15084. ASSERT_TRUE(ssl_svr1.is_valid());
  15085. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15086. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15087. "/index");
  15088. ssl_svr1.stop();
  15089. });
  15090. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15091. ASSERT_TRUE(ssl_svr2.is_valid());
  15092. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15093. res.set_content("test", "text/plain");
  15094. ssl_svr2.stop();
  15095. });
  15096. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15097. thread t2 =
  15098. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15099. auto se = detail::scope_exit([&] {
  15100. t2.join();
  15101. t.join();
  15102. ASSERT_FALSE(ssl_svr1.is_running());
  15103. });
  15104. ssl_svr1.wait_until_ready();
  15105. ssl_svr2.wait_until_ready();
  15106. SSLClient cli("127.0.0.1", PORT);
  15107. std::string cert;
  15108. read_file(SERVER_CERT2_FILE, cert);
  15109. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15110. cli.enable_server_certificate_verification(true);
  15111. cli.set_follow_location(true);
  15112. cli.set_connection_timeout(30);
  15113. auto res = cli.Get("/index");
  15114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15115. ASSERT_EQ(StatusCode::OK_200, res->status);
  15116. }
  15117. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15118. // another port, so the client follows it with a new client.
  15119. static Result GetThroughTlsRedirectToDifferentPort(
  15120. const std::function<void(SSLClient &)> &setup,
  15121. const char *target_cert = SERVER_CERT2_FILE,
  15122. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15123. auto ssl_port = PORT + 1;
  15124. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15125. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15126. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15127. "/index");
  15128. });
  15129. SSLServer ssl_svr2(target_cert, target_key);
  15130. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15131. res.set_content("test", "text/plain");
  15132. });
  15133. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15134. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15135. auto se = detail::scope_exit([&] {
  15136. ssl_svr2.stop();
  15137. ssl_svr1.stop();
  15138. t2.join();
  15139. t.join();
  15140. });
  15141. ssl_svr1.wait_until_ready();
  15142. ssl_svr2.wait_until_ready();
  15143. SSLClient cli("127.0.0.1", PORT);
  15144. cli.set_follow_location(true);
  15145. cli.set_connection_timeout(30);
  15146. setup(cli);
  15147. return cli.Get("/index");
  15148. }
  15149. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15150. auto calls = 0;
  15151. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15152. cli.enable_server_certificate_verification(false);
  15153. // Accept the first server only.
  15154. cli.set_session_verifier([&](tls::session_t) {
  15155. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15156. : SSLVerifierResponse::CertificateRejected;
  15157. });
  15158. });
  15159. ASSERT_FALSE(res);
  15160. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15161. EXPECT_EQ(2, calls);
  15162. }
  15163. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15164. std::string pinned;
  15165. auto res = GetThroughTlsRedirectToDifferentPort(
  15166. [&](SSLClient &cli) {
  15167. cli.enable_server_certificate_verification(false);
  15168. // Pin the first certificate seen.
  15169. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15170. if (pinned.empty()) { pinned = ctx.serial(); }
  15171. return ctx.serial() == pinned;
  15172. });
  15173. },
  15174. // A certificate other than the first server's.
  15175. SERVER_CERT_FILE);
  15176. EXPECT_FALSE(res);
  15177. EXPECT_FALSE(pinned.empty());
  15178. }
  15179. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15180. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15181. std::string cert;
  15182. read_file(SERVER_CERT2_FILE, cert);
  15183. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15184. });
  15185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15186. EXPECT_EQ(StatusCode::OK_200, res->status);
  15187. }
  15188. // The target's certificate is signed by the root CA, which the first server's
  15189. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15190. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15191. auto res = GetThroughTlsRedirectToDifferentPort(
  15192. [](SSLClient &cli) {
  15193. std::string root_ca, cert;
  15194. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15195. read_file(SERVER_CERT2_FILE, cert);
  15196. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15197. cli.load_ca_cert_store(cert.data(), cert.size());
  15198. cli.enable_server_hostname_verification(false);
  15199. },
  15200. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15202. EXPECT_EQ(StatusCode::OK_200, res->status);
  15203. }
  15204. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15205. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15206. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15207. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15208. auto res = GetThroughTlsRedirectToDifferentPort(
  15209. [](SSLClient &cli) {
  15210. std::string root_ca, cert;
  15211. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15212. read_file(SERVER_CERT2_FILE, cert);
  15213. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15214. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15215. cli.enable_server_hostname_verification(false);
  15216. },
  15217. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15218. ASSERT_FALSE(res);
  15219. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15220. }
  15221. #endif
  15222. #endif
  15223. #ifdef CPPHTTPLIB_SSL_ENABLED
  15224. // Test that set_ca_cert_store() skips system certs (consistent with
  15225. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15226. // should be trusted - system certs should NOT be loaded.
  15227. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15228. // Load a specific cert that is NOT a system CA cert
  15229. std::string cert;
  15230. read_file(SERVER_CERT2_FILE, cert);
  15231. SSLClient cli("google.com");
  15232. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15233. cli.enable_server_certificate_verification(true);
  15234. // This should FAIL because:
  15235. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15236. // 2. System certs should NOT be loaded when custom store is set
  15237. // If system certs WERE loaded, this would succeed
  15238. auto res = cli.Get("/");
  15239. ASSERT_FALSE(res);
  15240. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15241. }
  15242. // Same as above, but through the native store handle path. Regression test:
  15243. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15244. // merged system certs into the user-provided store.
  15245. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15246. std::string cert;
  15247. read_file(SERVER_CERT2_FILE, cert);
  15248. SSLClient cli("google.com");
  15249. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15250. cli.enable_server_certificate_verification(true);
  15251. auto res = cli.Get("/");
  15252. ASSERT_FALSE(res);
  15253. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15254. }
  15255. // A custom store set via the native handle must still verify a server whose
  15256. // cert it does contain.
  15257. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15258. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15259. ASSERT_TRUE(svr.is_valid());
  15260. svr.Get("/test", [&](const Request &, Response &res) {
  15261. res.set_content("test", "text/plain");
  15262. });
  15263. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15264. auto se = detail::scope_exit([&] {
  15265. svr.stop();
  15266. t.join();
  15267. ASSERT_FALSE(svr.is_running());
  15268. });
  15269. svr.wait_until_ready();
  15270. SSLClient cli("127.0.0.1", PORT);
  15271. std::string cert;
  15272. read_file(SERVER_CERT2_FILE, cert);
  15273. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15274. cli.enable_server_certificate_verification(true);
  15275. cli.set_connection_timeout(30);
  15276. auto res = cli.Get("/test");
  15277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15278. ASSERT_EQ(StatusCode::OK_200, res->status);
  15279. }
  15280. // CA certs loaded through the universal Client must be transferred to the
  15281. // client created internally for following an HTTPS redirect. Regression test:
  15282. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15283. // the CA data for redirect transfer.
  15284. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15285. auto ssl_port = PORT + 1;
  15286. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15287. ASSERT_TRUE(ssl_svr1.is_valid());
  15288. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15289. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15290. "/index");
  15291. });
  15292. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15293. ASSERT_TRUE(ssl_svr2.is_valid());
  15294. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15295. res.set_content("test", "text/plain");
  15296. });
  15297. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15298. thread t2 =
  15299. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15300. auto se = detail::scope_exit([&] {
  15301. ssl_svr2.stop();
  15302. ssl_svr1.stop();
  15303. t2.join();
  15304. t.join();
  15305. ASSERT_FALSE(ssl_svr1.is_running());
  15306. });
  15307. ssl_svr1.wait_until_ready();
  15308. ssl_svr2.wait_until_ready();
  15309. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15310. std::string cert;
  15311. read_file(SERVER_CERT2_FILE, cert);
  15312. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15313. cli.enable_server_certificate_verification(true);
  15314. cli.set_follow_location(true);
  15315. cli.set_connection_timeout(30);
  15316. auto res = cli.Get("/index");
  15317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15318. ASSERT_EQ(StatusCode::OK_200, res->status);
  15319. }
  15320. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15321. // so a host signed by a system CA verifies even though a custom CA is set
  15322. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15323. std::string cert;
  15324. read_file(SERVER_CERT2_FILE, cert);
  15325. SSLClient cli("google.com");
  15326. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15327. cli.enable_system_ca(true);
  15328. cli.enable_server_certificate_verification(true);
  15329. auto res = cli.Get("/");
  15330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15331. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15332. }
  15333. // The custom CA remains effective when combined with the system CA
  15334. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15335. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15336. ASSERT_TRUE(svr.is_valid());
  15337. svr.Get("/test", [&](const Request &, Response &res) {
  15338. res.set_content("test", "text/plain");
  15339. });
  15340. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15341. auto se = detail::scope_exit([&] {
  15342. svr.stop();
  15343. t.join();
  15344. ASSERT_FALSE(svr.is_running());
  15345. });
  15346. svr.wait_until_ready();
  15347. SSLClient cli("127.0.0.1", PORT);
  15348. std::string cert;
  15349. read_file(SERVER_CERT2_FILE, cert);
  15350. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15351. cli.enable_system_ca(true);
  15352. cli.enable_server_certificate_verification(true);
  15353. cli.set_connection_timeout(30);
  15354. auto res = cli.Get("/test");
  15355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15356. ASSERT_EQ(StatusCode::OK_200, res->status);
  15357. }
  15358. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15359. // skip chain verification entirely (only the certificate identity was
  15360. // checked), so a server presenting an untrusted certificate with a matching
  15361. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15362. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15363. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15364. ASSERT_TRUE(svr.is_valid());
  15365. svr.Get("/test", [&](const Request &, Response &res) {
  15366. res.set_content("test", "text/plain");
  15367. });
  15368. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15369. auto se = detail::scope_exit([&] {
  15370. svr.stop();
  15371. t.join();
  15372. ASSERT_FALSE(svr.is_running());
  15373. });
  15374. svr.wait_until_ready();
  15375. SSLClient cli("127.0.0.1", PORT);
  15376. std::string cert;
  15377. // A trusted CA that did not sign the server certificate. The server cert
  15378. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15379. // this connection.
  15380. read_file(CLIENT_CA_CERT_FILE, cert);
  15381. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15382. cli.enable_server_certificate_verification(true);
  15383. cli.set_connection_timeout(30);
  15384. auto res = cli.Get("/test");
  15385. ASSERT_FALSE(res);
  15386. }
  15387. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15388. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15389. // CA that failed to come through fails verification instead of trusting them.
  15390. // (wolfSSL does not list the system CAs it loaded.)
  15391. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15392. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15393. ASSERT_TRUE(svr.is_valid());
  15394. auto port = svr.bind_to_any_port("127.0.0.1");
  15395. ASSERT_LT(0, port);
  15396. thread t = thread([&] { svr.listen_after_bind(); });
  15397. auto se = detail::scope_exit([&] {
  15398. svr.stop();
  15399. t.join();
  15400. ASSERT_FALSE(svr.is_running());
  15401. });
  15402. svr.wait_until_ready();
  15403. // The CAs a client trusts once its first request has loaded them
  15404. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15405. Client cli("https://127.0.0.1:" + std::to_string(port));
  15406. setup(cli);
  15407. cli.Get("/");
  15408. return tls::get_ca_names(cli.tls_context()).size();
  15409. };
  15410. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15411. EXPECT_EQ(0u,
  15412. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15413. }
  15414. #endif
  15415. // enable_system_ca(false) prevents system CA loading entirely
  15416. TEST(SSLClientTest, DisableSystemCa_Online) {
  15417. SSLClient cli("google.com");
  15418. cli.enable_system_ca(false);
  15419. cli.enable_server_certificate_verification(true);
  15420. auto res = cli.Get("/");
  15421. ASSERT_FALSE(res);
  15422. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15423. // itself when the CA chain is empty
  15424. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15425. res.error() == Error::SSLConnection);
  15426. }
  15427. // The universal Client forwards enable_system_ca()
  15428. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15429. std::string cert;
  15430. read_file(SERVER_CERT2_FILE, cert);
  15431. Client cli("https://google.com");
  15432. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15433. cli.enable_system_ca(true);
  15434. cli.enable_server_certificate_verification(true);
  15435. auto res = cli.Get("/");
  15436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15437. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15438. }
  15439. // The system CA policy must carry over to the client created internally for
  15440. // following a cross-host HTTPS redirect
  15441. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15442. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15443. ASSERT_TRUE(svr.is_valid());
  15444. svr.Get("/index", [&](const Request &, Response &res) {
  15445. res.set_redirect("https://www.google.com/");
  15446. });
  15447. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15448. auto se = detail::scope_exit([&] {
  15449. svr.stop();
  15450. t.join();
  15451. ASSERT_FALSE(svr.is_running());
  15452. });
  15453. svr.wait_until_ready();
  15454. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15455. std::string cert;
  15456. read_file(SERVER_CERT2_FILE, cert);
  15457. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15458. cli.enable_system_ca(true);
  15459. cli.enable_server_certificate_verification(true);
  15460. cli.set_follow_location(true);
  15461. cli.set_connection_timeout(30);
  15462. // Receiving any response proves the redirect client completed the TLS
  15463. // handshake with a system-CA-signed host
  15464. auto res = cli.Get("/index");
  15465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15466. }
  15467. TEST(MultipartFormDataTest, LargeData) {
  15468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15469. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15470. const ContentReader &content_reader) {
  15471. if (req.is_multipart_form_data()) {
  15472. std::vector<FormData> items;
  15473. content_reader(
  15474. [&](const FormData &file) {
  15475. items.push_back(file);
  15476. return true;
  15477. },
  15478. [&](const char *data, size_t data_length) {
  15479. items.back().content.append(data, data_length);
  15480. return true;
  15481. });
  15482. EXPECT_TRUE(std::string(items[0].name) == "document");
  15483. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15484. EXPECT_TRUE(items[0].filename == "2MB_data");
  15485. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15486. EXPECT_TRUE(items[1].name == "hello");
  15487. EXPECT_TRUE(items[1].content == "world");
  15488. EXPECT_TRUE(items[1].filename == "");
  15489. EXPECT_TRUE(items[1].content_type == "");
  15490. } else {
  15491. std::string body;
  15492. content_reader([&](const char *data, size_t data_length) {
  15493. body.append(data, data_length);
  15494. return true;
  15495. });
  15496. }
  15497. });
  15498. auto port = svr.bind_to_any_port(HOST);
  15499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15500. auto se = detail::scope_exit([&] {
  15501. svr.stop();
  15502. t.join();
  15503. ASSERT_FALSE(svr.is_running());
  15504. });
  15505. svr.wait_until_ready();
  15506. {
  15507. std::string data(1024 * 1024 * 2, '.');
  15508. std::stringstream buffer;
  15509. buffer << data;
  15510. SSLClient cli(HOST, port);
  15511. cli.enable_server_certificate_verification(false);
  15512. UploadFormDataItems items{
  15513. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15514. {"hello", "world", "", ""},
  15515. };
  15516. auto res = cli.Post("/post", items);
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. ASSERT_EQ(StatusCode::OK_200, res->status);
  15519. }
  15520. }
  15521. TEST(MultipartFormDataTest, DataProviderItems) {
  15522. std::random_device seed_gen;
  15523. std::mt19937 random(seed_gen());
  15524. std::string rand1;
  15525. rand1.resize(1000);
  15526. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15527. std::string rand2;
  15528. rand2.resize(3000);
  15529. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15531. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15532. const ContentReader &content_reader) {
  15533. ASSERT_FALSE(req.is_multipart_form_data());
  15534. std::string body;
  15535. content_reader([&](const char *data, size_t data_length) {
  15536. body.append(data, data_length);
  15537. return true;
  15538. });
  15539. EXPECT_EQ(body, "");
  15540. });
  15541. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15542. const ContentReader &content_reader) {
  15543. ASSERT_TRUE(req.is_multipart_form_data());
  15544. std::vector<FormData> items;
  15545. content_reader(
  15546. [&](const FormData &file) {
  15547. items.push_back(file);
  15548. return true;
  15549. },
  15550. [&](const char *data, size_t data_length) {
  15551. items.back().content.append(data, data_length);
  15552. return true;
  15553. });
  15554. ASSERT_TRUE(items.size() == 2);
  15555. EXPECT_EQ(std::string(items[0].name), "name1");
  15556. EXPECT_EQ(items[0].content, "Testing123");
  15557. EXPECT_EQ(items[0].filename, "filename1");
  15558. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15559. EXPECT_EQ(items[1].name, "name2");
  15560. EXPECT_EQ(items[1].content, "Testing456");
  15561. EXPECT_EQ(items[1].filename, "");
  15562. EXPECT_EQ(items[1].content_type, "");
  15563. });
  15564. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15565. const ContentReader &content_reader) {
  15566. ASSERT_TRUE(req.is_multipart_form_data());
  15567. std::vector<FormData> items;
  15568. content_reader(
  15569. [&](const FormData &file) {
  15570. items.push_back(file);
  15571. return true;
  15572. },
  15573. [&](const char *data, size_t data_length) {
  15574. items.back().content.append(data, data_length);
  15575. return true;
  15576. });
  15577. ASSERT_TRUE(items.size() == 2);
  15578. EXPECT_EQ(items[0].name, "name3");
  15579. EXPECT_EQ(items[0].content, rand1);
  15580. EXPECT_EQ(items[0].filename, "filename3");
  15581. EXPECT_EQ(items[0].content_type, "");
  15582. EXPECT_EQ(items[1].name, "name4");
  15583. EXPECT_EQ(items[1].content, rand2);
  15584. EXPECT_EQ(items[1].filename, "filename4");
  15585. EXPECT_EQ(items[1].content_type, "");
  15586. });
  15587. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15588. const ContentReader &content_reader) {
  15589. ASSERT_TRUE(req.is_multipart_form_data());
  15590. std::vector<FormData> items;
  15591. content_reader(
  15592. [&](const FormData &file) {
  15593. items.push_back(file);
  15594. return true;
  15595. },
  15596. [&](const char *data, size_t data_length) {
  15597. items.back().content.append(data, data_length);
  15598. return true;
  15599. });
  15600. ASSERT_TRUE(items.size() == 4);
  15601. EXPECT_EQ(std::string(items[0].name), "name1");
  15602. EXPECT_EQ(items[0].content, "Testing123");
  15603. EXPECT_EQ(items[0].filename, "filename1");
  15604. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15605. EXPECT_EQ(items[1].name, "name2");
  15606. EXPECT_EQ(items[1].content, "Testing456");
  15607. EXPECT_EQ(items[1].filename, "");
  15608. EXPECT_EQ(items[1].content_type, "");
  15609. EXPECT_EQ(items[2].name, "name3");
  15610. EXPECT_EQ(items[2].content, rand1);
  15611. EXPECT_EQ(items[2].filename, "filename3");
  15612. EXPECT_EQ(items[2].content_type, "");
  15613. EXPECT_EQ(items[3].name, "name4");
  15614. EXPECT_EQ(items[3].content, rand2);
  15615. EXPECT_EQ(items[3].filename, "filename4");
  15616. EXPECT_EQ(items[3].content_type, "");
  15617. });
  15618. auto port = svr.bind_to_any_port("localhost");
  15619. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15620. auto se = detail::scope_exit([&] {
  15621. svr.stop();
  15622. t.join();
  15623. ASSERT_FALSE(svr.is_running());
  15624. });
  15625. svr.wait_until_ready();
  15626. {
  15627. SSLClient cli("localhost", port);
  15628. cli.enable_server_certificate_verification(false);
  15629. UploadFormDataItems items{
  15630. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15631. {"name2", "Testing456", "", ""}, // not a file
  15632. };
  15633. {
  15634. auto res = cli.Post("/post-none", {}, {}, {});
  15635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15636. ASSERT_EQ(StatusCode::OK_200, res->status);
  15637. }
  15638. FormDataProviderItems providers;
  15639. {
  15640. auto res =
  15641. cli.Post("/post-items", {}, items, providers); // empty providers
  15642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15643. ASSERT_EQ(StatusCode::OK_200, res->status);
  15644. }
  15645. providers.push_back({"name3",
  15646. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15647. // test the offset is given correctly at each step
  15648. if (!offset)
  15649. sink.os.write(rand1.data(), 30);
  15650. else if (offset == 30)
  15651. sink.os.write(rand1.data() + 30, 300);
  15652. else if (offset == 330)
  15653. sink.os.write(rand1.data() + 330, 670);
  15654. else if (offset == rand1.size())
  15655. sink.done();
  15656. return true;
  15657. },
  15658. "filename3",
  15659. {}});
  15660. providers.push_back({"name4",
  15661. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15662. // test the offset is given correctly at each step
  15663. if (!offset)
  15664. sink.os.write(rand2.data(), 2000);
  15665. else if (offset == 2000)
  15666. sink.os.write(rand2.data() + 2000, 1);
  15667. else if (offset == 2001)
  15668. sink.os.write(rand2.data() + 2001, 999);
  15669. else if (offset == rand2.size())
  15670. sink.done();
  15671. return true;
  15672. },
  15673. "filename4",
  15674. {}});
  15675. {
  15676. auto res = cli.Post("/post-providers", {}, {}, providers);
  15677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15678. ASSERT_EQ(StatusCode::OK_200, res->status);
  15679. }
  15680. {
  15681. auto res = cli.Post("/post-both", {}, items, providers);
  15682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15683. ASSERT_EQ(StatusCode::OK_200, res->status);
  15684. }
  15685. }
  15686. }
  15687. TEST(MultipartFormDataTest, BadHeader) {
  15688. Server svr;
  15689. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15690. res.set_content("ok", "text/plain");
  15691. });
  15692. thread t = thread([&] { svr.listen(HOST, PORT); });
  15693. auto se = detail::scope_exit([&] {
  15694. svr.stop();
  15695. t.join();
  15696. ASSERT_FALSE(svr.is_running());
  15697. });
  15698. svr.wait_until_ready();
  15699. const std::string body =
  15700. "This is the preamble. It is to be ignored, though it\r\n"
  15701. "is a handy place for composition agents to include an\r\n"
  15702. "explanatory note to non-MIME conformant readers.\r\n"
  15703. "\r\n"
  15704. "\r\n"
  15705. "--simple boundary\r\n"
  15706. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15707. ": BAD...\r\n"
  15708. "\r\n"
  15709. "value1\r\n"
  15710. "--simple boundary\r\n"
  15711. "Content-Disposition: form-data; name=\"field2\"; "
  15712. "filename=\"example.txt\"\r\n"
  15713. "\r\n"
  15714. "value2\r\n"
  15715. "--simple boundary--\r\n"
  15716. "This is the epilogue. It is also to be ignored.\r\n";
  15717. std::string content_type =
  15718. R"(multipart/form-data; boundary="simple boundary")";
  15719. Client cli(HOST, PORT);
  15720. auto res = cli.Post("/post", body, content_type.c_str());
  15721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15722. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15723. }
  15724. TEST(MultipartFormDataTest, WithPreamble) {
  15725. Server svr;
  15726. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15727. res.set_content("ok", "text/plain");
  15728. });
  15729. thread t = thread([&] { svr.listen(HOST, PORT); });
  15730. auto se = detail::scope_exit([&] {
  15731. svr.stop();
  15732. t.join();
  15733. ASSERT_FALSE(svr.is_running());
  15734. });
  15735. svr.wait_until_ready();
  15736. const std::string body =
  15737. "This is the preamble. It is to be ignored, though it\r\n"
  15738. "is a handy place for composition agents to include an\r\n"
  15739. "explanatory note to non-MIME conformant readers.\r\n"
  15740. "\r\n"
  15741. "\r\n"
  15742. "--simple boundary\r\n"
  15743. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15744. "\r\n"
  15745. "value1\r\n"
  15746. "--simple boundary\r\n"
  15747. "Content-Disposition: form-data; name=\"field2\"; "
  15748. "filename=\"example.txt\"\r\n"
  15749. "\r\n"
  15750. "value2\r\n"
  15751. "--simple boundary--\r\n"
  15752. "This is the epilogue. It is also to be ignored.\r\n";
  15753. std::string content_type =
  15754. R"(multipart/form-data; boundary="simple boundary")";
  15755. Client cli(HOST, PORT);
  15756. auto res = cli.Post("/post", body, content_type.c_str());
  15757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15758. EXPECT_EQ(StatusCode::OK_200, res->status);
  15759. }
  15760. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15762. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15763. const ContentReader &content_reader) {
  15764. if (req.is_multipart_form_data()) {
  15765. std::vector<FormData> items;
  15766. content_reader(
  15767. [&](const FormData &file) {
  15768. items.push_back(file);
  15769. return true;
  15770. },
  15771. [&](const char *data, size_t data_length) {
  15772. items.back().content.append(data, data_length);
  15773. return true;
  15774. });
  15775. EXPECT_TRUE(std::string(items[0].name) == "document");
  15776. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15777. EXPECT_TRUE(items[0].filename == "2MB_data");
  15778. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15779. EXPECT_TRUE(items[1].name == "hello");
  15780. EXPECT_TRUE(items[1].content == "world");
  15781. EXPECT_TRUE(items[1].filename == "");
  15782. EXPECT_TRUE(items[1].content_type == "");
  15783. } else {
  15784. std::string body;
  15785. content_reader([&](const char *data, size_t data_length) {
  15786. body.append(data, data_length);
  15787. return true;
  15788. });
  15789. }
  15790. });
  15791. auto port = svr.bind_to_any_port("localhost");
  15792. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15793. auto se = detail::scope_exit([&] {
  15794. svr.stop();
  15795. t.join();
  15796. ASSERT_FALSE(svr.is_running());
  15797. });
  15798. svr.wait_until_ready();
  15799. {
  15800. std::string data(1024 * 1024 * 2, '.');
  15801. std::stringstream buffer;
  15802. buffer << data;
  15803. SSLClient cli("localhost", port);
  15804. cli.enable_server_certificate_verification(false);
  15805. UploadFormDataItems items{
  15806. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15807. {"hello", "world", "", ""},
  15808. };
  15809. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15811. ASSERT_EQ(StatusCode::OK_200, res->status);
  15812. }
  15813. }
  15814. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15815. std::string data(1024 * 1024 * 2, '&');
  15816. std::stringstream buffer;
  15817. buffer << data;
  15818. Client cli("https://localhost:8080");
  15819. UploadFormDataItems items{
  15820. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15821. {"hello", "world", "", ""},
  15822. };
  15823. for (const char &c : " \t\r\n") {
  15824. auto res =
  15825. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15826. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15827. ASSERT_FALSE(res);
  15828. }
  15829. }
  15830. TEST(MultipartFormDataTest, PutFormData) {
  15831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15832. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15833. const ContentReader &content_reader) {
  15834. if (req.is_multipart_form_data()) {
  15835. std::vector<FormData> items;
  15836. content_reader(
  15837. [&](const FormData &file) {
  15838. items.push_back(file);
  15839. return true;
  15840. },
  15841. [&](const char *data, size_t data_length) {
  15842. items.back().content.append(data, data_length);
  15843. return true;
  15844. });
  15845. EXPECT_TRUE(std::string(items[0].name) == "document");
  15846. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15847. EXPECT_TRUE(items[0].filename == "2MB_data");
  15848. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15849. EXPECT_TRUE(items[1].name == "hello");
  15850. EXPECT_TRUE(items[1].content == "world");
  15851. EXPECT_TRUE(items[1].filename == "");
  15852. EXPECT_TRUE(items[1].content_type == "");
  15853. } else {
  15854. std::string body;
  15855. content_reader([&](const char *data, size_t data_length) {
  15856. body.append(data, data_length);
  15857. return true;
  15858. });
  15859. }
  15860. });
  15861. auto port = svr.bind_to_any_port("localhost");
  15862. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15863. auto se = detail::scope_exit([&] {
  15864. svr.stop();
  15865. t.join();
  15866. ASSERT_FALSE(svr.is_running());
  15867. });
  15868. svr.wait_until_ready();
  15869. {
  15870. std::string data(1024 * 1024 * 2, '&');
  15871. std::stringstream buffer;
  15872. buffer << data;
  15873. SSLClient cli("localhost", port);
  15874. cli.enable_server_certificate_verification(false);
  15875. UploadFormDataItems items{
  15876. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15877. {"hello", "world", "", ""},
  15878. };
  15879. auto res = cli.Put("/put", items);
  15880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15881. ASSERT_EQ(StatusCode::OK_200, res->status);
  15882. }
  15883. }
  15884. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15886. svr.Put("/put_customboundary",
  15887. [&](const Request &req, const Response & /*res*/,
  15888. const ContentReader &content_reader) {
  15889. if (req.is_multipart_form_data()) {
  15890. std::vector<FormData> items;
  15891. content_reader(
  15892. [&](const FormData &file) {
  15893. items.push_back(file);
  15894. return true;
  15895. },
  15896. [&](const char *data, size_t data_length) {
  15897. items.back().content.append(data, data_length);
  15898. return true;
  15899. });
  15900. EXPECT_TRUE(std::string(items[0].name) == "document");
  15901. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15902. EXPECT_TRUE(items[0].filename == "2MB_data");
  15903. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15904. EXPECT_TRUE(items[1].name == "hello");
  15905. EXPECT_TRUE(items[1].content == "world");
  15906. EXPECT_TRUE(items[1].filename == "");
  15907. EXPECT_TRUE(items[1].content_type == "");
  15908. } else {
  15909. std::string body;
  15910. content_reader([&](const char *data, size_t data_length) {
  15911. body.append(data, data_length);
  15912. return true;
  15913. });
  15914. }
  15915. });
  15916. auto port = svr.bind_to_any_port("localhost");
  15917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15918. auto se = detail::scope_exit([&] {
  15919. svr.stop();
  15920. t.join();
  15921. ASSERT_FALSE(svr.is_running());
  15922. });
  15923. svr.wait_until_ready();
  15924. {
  15925. std::string data(1024 * 1024 * 2, '&');
  15926. std::stringstream buffer;
  15927. buffer << data;
  15928. SSLClient cli("localhost", port);
  15929. cli.enable_server_certificate_verification(false);
  15930. UploadFormDataItems items{
  15931. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15932. {"hello", "world", "", ""},
  15933. };
  15934. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15936. ASSERT_EQ(StatusCode::OK_200, res->status);
  15937. }
  15938. }
  15939. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15940. std::string data(1024 * 1024 * 2, '&');
  15941. std::stringstream buffer;
  15942. buffer << data;
  15943. Client cli("https://localhost:8080");
  15944. cli.enable_server_certificate_verification(false);
  15945. UploadFormDataItems items{
  15946. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15947. {"hello", "world", "", ""},
  15948. };
  15949. for (const char &c : " \t\r\n") {
  15950. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15951. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15952. ASSERT_FALSE(res);
  15953. }
  15954. }
  15955. TEST(MultipartFormDataTest, AlternateFilename) {
  15956. auto handled = false;
  15957. Server svr;
  15958. svr.Post("/test", [&](const Request &req, Response &res) {
  15959. ASSERT_EQ(2u, req.form.files.size());
  15960. ASSERT_EQ(1u, req.form.fields.size());
  15961. // Test files
  15962. const auto &file1 = req.form.get_file("file1");
  15963. ASSERT_EQ("file1", file1.name);
  15964. ASSERT_EQ("A.txt", file1.filename);
  15965. ASSERT_EQ("text/plain", file1.content_type);
  15966. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15967. const auto &file2 = req.form.get_file("file2");
  15968. ASSERT_EQ("file2", file2.name);
  15969. ASSERT_EQ("a.html", file2.filename);
  15970. ASSERT_EQ("text/html", file2.content_type);
  15971. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15972. file2.content);
  15973. // Test text field
  15974. const auto &text = req.form.get_field("text");
  15975. ASSERT_EQ("text default", text);
  15976. res.set_content("ok", "text/plain");
  15977. handled = true;
  15978. });
  15979. thread t = thread([&] { svr.listen(HOST, PORT); });
  15980. auto se = detail::scope_exit([&] {
  15981. svr.stop();
  15982. t.join();
  15983. ASSERT_FALSE(svr.is_running());
  15984. ASSERT_TRUE(handled);
  15985. });
  15986. svr.wait_until_ready();
  15987. auto req = "POST /test HTTP/1.1\r\n"
  15988. "Host: localhost\r\n"
  15989. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15990. "Content-Length: 399\r\n"
  15991. "\r\n"
  15992. "----------\r\n"
  15993. "Content-Disposition: form-data; name=\"text\"\r\n"
  15994. "\r\n"
  15995. "text default\r\n"
  15996. "----------\r\n"
  15997. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15998. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15999. "Content-Type: text/plain\r\n"
  16000. "\r\n"
  16001. "Content of a.txt.\r\n"
  16002. "\r\n"
  16003. "----------\r\n"
  16004. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16005. "\"a.html\"\r\n"
  16006. "Content-Type: text/html\r\n"
  16007. "\r\n"
  16008. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16009. "\r\n"
  16010. "------------\r\n";
  16011. ASSERT_TRUE(send_request(1, req));
  16012. }
  16013. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16014. auto handled = false;
  16015. Server svr;
  16016. svr.Post("/test", [&](const Request &req, Response &res) {
  16017. // Case-insensitive "utf-8''" prefix with a long value
  16018. const auto &file = req.form.get_file("file1");
  16019. ASSERT_EQ("file1", file.name);
  16020. // 8000 chars exercises both the Content-Disposition parser and the
  16021. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16022. // Prior to the fix, std::regex_match on this header would cause O(N)
  16023. // stack recursion in libstdc++, leading to SIGSEGV.
  16024. std::string expected_filename(8000, 'A');
  16025. ASSERT_EQ(expected_filename, file.filename);
  16026. res.set_content("ok", "text/plain");
  16027. handled = true;
  16028. });
  16029. thread t = thread([&] { svr.listen(HOST, PORT); });
  16030. auto se = detail::scope_exit([&] {
  16031. svr.stop();
  16032. t.join();
  16033. ASSERT_FALSE(svr.is_running());
  16034. ASSERT_TRUE(handled);
  16035. });
  16036. svr.wait_until_ready();
  16037. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16038. // Regression test for GHSA-qq6v-r583-3h69
  16039. std::string long_filename(8000, 'A');
  16040. std::string body = "----------\r\n"
  16041. "Content-Disposition: form-data; name=\"file1\"; "
  16042. "filename*=\"Utf-8''" +
  16043. long_filename +
  16044. "\"\r\n"
  16045. "\r\n"
  16046. "hello\r\n"
  16047. "------------\r\n";
  16048. auto req = "POST /test HTTP/1.1\r\n"
  16049. "Host: localhost\r\n"
  16050. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16051. "Content-Length: " +
  16052. std::to_string(body.size()) + "\r\n\r\n" + body;
  16053. ASSERT_TRUE(send_request(1, req));
  16054. }
  16055. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16056. auto handled = false;
  16057. Server svr;
  16058. svr.Post("/test", [&](const Request &req, Response &) {
  16059. ASSERT_EQ(2u, req.form.fields.size());
  16060. const auto &text1 = req.form.get_field("text1");
  16061. ASSERT_EQ("text1", text1);
  16062. const auto &text2 = req.form.get_field("text2");
  16063. ASSERT_EQ("text2", text2);
  16064. handled = true;
  16065. });
  16066. thread t = thread([&] { svr.listen(HOST, PORT); });
  16067. auto se = detail::scope_exit([&] {
  16068. svr.stop();
  16069. t.join();
  16070. ASSERT_FALSE(svr.is_running());
  16071. ASSERT_TRUE(handled);
  16072. });
  16073. svr.wait_until_ready();
  16074. auto req = "POST /test HTTP/1.1\r\n"
  16075. "Host: localhost\r\n"
  16076. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16077. "Content-Length: 146\r\n"
  16078. "\r\n----------\r\n"
  16079. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16080. "\r\n"
  16081. "text1"
  16082. "\r\n----------\r\n"
  16083. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16084. "\r\n"
  16085. "text2"
  16086. "\r\n------------";
  16087. std::string response;
  16088. ASSERT_TRUE(send_request(1, req, &response));
  16089. ASSERT_EQ("200", response.substr(9, 3));
  16090. }
  16091. TEST(MultipartFormDataTest, ContentLength) {
  16092. auto handled = false;
  16093. Server svr;
  16094. svr.Post("/test", [&](const Request &req, Response &) {
  16095. ASSERT_EQ(2u, req.form.fields.size());
  16096. const auto &text1 = req.form.get_field("text1");
  16097. ASSERT_EQ("text1", text1);
  16098. const auto &text2 = req.form.get_field("text2");
  16099. ASSERT_EQ("text2", text2);
  16100. handled = true;
  16101. });
  16102. thread t = thread([&] { svr.listen(HOST, PORT); });
  16103. auto se = detail::scope_exit([&] {
  16104. svr.stop();
  16105. t.join();
  16106. ASSERT_FALSE(svr.is_running());
  16107. ASSERT_TRUE(handled);
  16108. });
  16109. svr.wait_until_ready();
  16110. auto req = "POST /test HTTP/1.1\r\n"
  16111. "Host: localhost\r\n"
  16112. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16113. "Content-Length: 167\r\n"
  16114. "\r\n----------\r\n"
  16115. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16116. "Content-Length: 5\r\n"
  16117. "\r\n"
  16118. "text1"
  16119. "\r\n----------\r\n"
  16120. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16121. "\r\n"
  16122. "text2"
  16123. "\r\n------------\r\n";
  16124. std::string response;
  16125. ASSERT_TRUE(send_request(1, req, &response));
  16126. ASSERT_EQ("200", response.substr(9, 3));
  16127. }
  16128. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16129. auto handled = false;
  16130. Server svr;
  16131. svr.Post("/test", [&](const Request &req, Response &) {
  16132. ASSERT_EQ(2u, req.form.fields.size());
  16133. const auto &text1 = req.form.get_field("text1");
  16134. ASSERT_EQ("text1", text1);
  16135. // TODO: Add header access for text fields if needed
  16136. const auto &text2 = req.form.get_field("text2");
  16137. ASSERT_EQ("text2", text2);
  16138. // TODO: Header access for text fields needs to be implemented
  16139. // auto &headers = it->second.headers;
  16140. // ASSERT_EQ(3U, headers.size());
  16141. // auto custom_header = headers.find("x-whatever");
  16142. // ASSERT_TRUE(custom_header != headers.end());
  16143. // ASSERT_NE("customvalue", custom_header->second);
  16144. // ASSERT_EQ("CustomValue", custom_header->second);
  16145. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16146. handled = true;
  16147. });
  16148. thread t = thread([&] { svr.listen(HOST, PORT); });
  16149. auto se = detail::scope_exit([&] {
  16150. svr.stop();
  16151. t.join();
  16152. ASSERT_FALSE(svr.is_running());
  16153. ASSERT_TRUE(handled);
  16154. });
  16155. svr.wait_until_ready();
  16156. auto req = "POST /test HTTP/1.1\r\n"
  16157. "Host: localhost\r\n"
  16158. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16159. "Content-Length: 232\r\n"
  16160. "\r\n----------\r\n"
  16161. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16162. "Content-Length: 5\r\n"
  16163. "X-Test: 1\r\n"
  16164. "\r\n"
  16165. "text1"
  16166. "\r\n----------\r\n"
  16167. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16168. "Content-Type: text/plain\r\n"
  16169. "X-Whatever: CustomValue\r\n"
  16170. "\r\n"
  16171. "text2"
  16172. "\r\n------------\r\n"
  16173. "That should be disregarded. Not even read";
  16174. std::string response;
  16175. ASSERT_TRUE(send_request(1, req, &response));
  16176. ASSERT_EQ("200", response.substr(9, 3));
  16177. }
  16178. TEST(MultipartFormDataTest, LargeHeader) {
  16179. auto handled = false;
  16180. Server svr;
  16181. svr.Post("/test", [&](const Request &req, Response &) {
  16182. ASSERT_EQ(1u, req.form.fields.size());
  16183. const auto &text = req.form.get_field("name1");
  16184. ASSERT_EQ("text1", text);
  16185. handled = true;
  16186. });
  16187. thread t = thread([&] { svr.listen(HOST, PORT); });
  16188. auto se = detail::scope_exit([&] {
  16189. svr.stop();
  16190. t.join();
  16191. ASSERT_FALSE(svr.is_running());
  16192. ASSERT_TRUE(handled);
  16193. });
  16194. svr.wait_until_ready();
  16195. auto boundary = std::string("cpp-httplib-multipart-data");
  16196. std::string content = "--" + boundary +
  16197. "\r\n"
  16198. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16199. "\r\n"
  16200. "text1\r\n"
  16201. "--" +
  16202. boundary + "--\r\n";
  16203. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16204. "Host: localhost\r\n"
  16205. "Content-Type: multipart/form-data;boundary=" +
  16206. boundary +
  16207. "\r\n"
  16208. "Content-Length: " +
  16209. std::to_string(content.size()) +
  16210. "\r\n"
  16211. "Dummy-Header: ";
  16212. std::string header_suffix = "\r\n"
  16213. "\r\n";
  16214. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16215. size_t header_dummy_size =
  16216. read_buff_size -
  16217. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16218. auto header_dummy = std::string(header_dummy_size, '@');
  16219. auto req = header_prefix + header_dummy + header_suffix + content;
  16220. std::string response;
  16221. ASSERT_TRUE(send_request(1, req, &response));
  16222. ASSERT_EQ("200", response.substr(9, 3));
  16223. }
  16224. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16225. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16226. // (not chunked Transfer-Encoding) after the streaming refactor.
  16227. auto handled = false;
  16228. Server svr;
  16229. svr.Post("/upload", [&](const Request &req, Response &res) {
  16230. auto cl_it = req.headers.find("Content-Length");
  16231. EXPECT_TRUE(cl_it != req.headers.end());
  16232. auto te_it = req.headers.find("Transfer-Encoding");
  16233. EXPECT_TRUE(te_it == req.headers.end());
  16234. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16235. res.set_content("ok", "text/plain");
  16236. handled = true;
  16237. });
  16238. auto port = svr.bind_to_any_port(HOST);
  16239. auto t = thread([&] { svr.listen_after_bind(); });
  16240. auto se = detail::scope_exit([&] {
  16241. svr.stop();
  16242. t.join();
  16243. ASSERT_FALSE(svr.is_running());
  16244. ASSERT_TRUE(handled);
  16245. });
  16246. svr.wait_until_ready();
  16247. UploadFormDataItems items = {
  16248. {"field1", "hello", "", "text/plain"},
  16249. {"file1", "world", "test.txt", "application/octet-stream"},
  16250. };
  16251. Client cli(HOST, port);
  16252. auto res = cli.Post("/upload", {}, items);
  16253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16254. EXPECT_EQ(StatusCode::OK_200, res->status);
  16255. }
  16256. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16257. // Verify that make_multipart_content_provider coalesces many small segments
  16258. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16259. constexpr size_t kItemCount = 1000;
  16260. UploadFormDataItems items;
  16261. items.reserve(kItemCount);
  16262. for (size_t i = 0; i < kItemCount; i++) {
  16263. items.push_back(
  16264. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16265. }
  16266. const std::string boundary = "----test-boundary";
  16267. auto content_length = detail::get_multipart_content_length(items, boundary);
  16268. auto provider = detail::make_multipart_content_provider(items, boundary);
  16269. // Drive the provider the same way write_content_with_progress does
  16270. size_t write_count = 0;
  16271. size_t total_bytes = 0;
  16272. DataSink sink;
  16273. size_t offset = 0;
  16274. sink.write = [&](const char *d, size_t l) -> bool {
  16275. (void)d;
  16276. write_count++;
  16277. total_bytes += l;
  16278. offset += l;
  16279. return true;
  16280. };
  16281. sink.is_writable = []() -> bool { return true; };
  16282. while (offset < content_length) {
  16283. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16284. }
  16285. EXPECT_EQ(content_length, total_bytes);
  16286. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16287. // With buffering into 64KB blocks, write_count should be much smaller.
  16288. auto segment_count = 3 * kItemCount + 1;
  16289. EXPECT_LT(write_count, segment_count / 10);
  16290. }
  16291. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16292. // Integration test: send many UploadFormDataItems and verify the server
  16293. // receives all of them correctly (#2410).
  16294. constexpr size_t kItemCount = 500;
  16295. auto handled = false;
  16296. Server svr;
  16297. svr.Post("/upload", [&](const Request &req, Response &res) {
  16298. EXPECT_EQ(kItemCount, req.form.fields.size());
  16299. for (size_t i = 0; i < kItemCount; i++) {
  16300. auto key = "field" + std::to_string(i);
  16301. auto val = "value" + std::to_string(i);
  16302. auto it = req.form.fields.find(key);
  16303. if (it != req.form.fields.end()) {
  16304. EXPECT_EQ(val, it->second.content);
  16305. } else {
  16306. ADD_FAILURE() << "Missing field: " << key;
  16307. }
  16308. }
  16309. res.set_content("ok", "text/plain");
  16310. handled = true;
  16311. });
  16312. auto port = svr.bind_to_any_port(HOST);
  16313. auto t = thread([&] { svr.listen_after_bind(); });
  16314. auto se = detail::scope_exit([&] {
  16315. svr.stop();
  16316. t.join();
  16317. ASSERT_FALSE(svr.is_running());
  16318. ASSERT_TRUE(handled);
  16319. });
  16320. svr.wait_until_ready();
  16321. UploadFormDataItems items;
  16322. items.reserve(kItemCount);
  16323. for (size_t i = 0; i < kItemCount; i++) {
  16324. items.push_back(
  16325. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16326. }
  16327. Client cli(HOST, port);
  16328. auto res = cli.Post("/upload", items);
  16329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16330. EXPECT_EQ(StatusCode::OK_200, res->status);
  16331. }
  16332. TEST(MultipartFormDataTest, MakeFileProvider) {
  16333. // Verify make_file_provider sends a file's contents correctly.
  16334. const std::string file_content(4096, 'Z');
  16335. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16336. {
  16337. std::ofstream ofs(tmp_path, std::ios::binary);
  16338. ofs.write(file_content.data(),
  16339. static_cast<std::streamsize>(file_content.size()));
  16340. }
  16341. auto handled = false;
  16342. Server svr;
  16343. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16344. const ContentReader &content_reader) {
  16345. ASSERT_TRUE(req.is_multipart_form_data());
  16346. std::vector<FormData> items;
  16347. content_reader(
  16348. [&](const FormData &file) {
  16349. items.push_back(file);
  16350. return true;
  16351. },
  16352. [&](const char *data, size_t data_length) {
  16353. items.back().content.append(data, data_length);
  16354. return true;
  16355. });
  16356. ASSERT_EQ(1u, items.size());
  16357. EXPECT_EQ("myfile", items[0].name);
  16358. EXPECT_EQ("data.bin", items[0].filename);
  16359. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16360. EXPECT_EQ(file_content, items[0].content);
  16361. handled = true;
  16362. });
  16363. auto port = svr.bind_to_any_port(HOST);
  16364. auto t = thread([&] { svr.listen_after_bind(); });
  16365. auto se = detail::scope_exit([&] {
  16366. svr.stop();
  16367. t.join();
  16368. ASSERT_FALSE(svr.is_running());
  16369. ASSERT_TRUE(handled);
  16370. std::remove(tmp_path.c_str());
  16371. });
  16372. svr.wait_until_ready();
  16373. FormDataProviderItems providers;
  16374. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16375. "application/octet-stream"));
  16376. Client cli(HOST, port);
  16377. auto res = cli.Post("/upload", {}, {}, providers);
  16378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16379. EXPECT_EQ(StatusCode::OK_200, res->status);
  16380. }
  16381. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16382. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16383. // (100) headers is rejected with a 400 Bad Request response.
  16384. Server svr;
  16385. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16386. res.set_content("ok", "text/plain");
  16387. });
  16388. thread t = thread([&] { svr.listen(HOST, PORT); });
  16389. auto se = detail::scope_exit([&] {
  16390. svr.stop();
  16391. t.join();
  16392. ASSERT_FALSE(svr.is_running());
  16393. });
  16394. svr.wait_until_ready();
  16395. // Build a multipart part with 101 custom headers (exceeding
  16396. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16397. std::stringstream body;
  16398. body << "--simpleboundary\r\n"
  16399. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16400. for (int i = 0; i < 101; i++) {
  16401. body << "X-Custom-Header-" << i << ": value\r\n";
  16402. }
  16403. body << "\r\n"
  16404. << "value1\r\n"
  16405. << "--simpleboundary--\r\n";
  16406. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16407. Client cli(HOST, PORT);
  16408. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16410. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16411. }
  16412. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16413. // A body that never contains the declared boundary must not be accumulated
  16414. // while the parser waits for it. Buffering it would also make every read
  16415. // rescan everything seen so far, which is quadratic in the body size.
  16416. Server svr;
  16417. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16418. res.set_content("ok", "text/plain");
  16419. });
  16420. auto port = svr.bind_to_any_port(HOST);
  16421. thread t = thread([&] { svr.listen_after_bind(); });
  16422. auto se = detail::scope_exit([&] {
  16423. svr.stop();
  16424. t.join();
  16425. ASSERT_FALSE(svr.is_running());
  16426. });
  16427. svr.wait_until_ready();
  16428. Client cli(HOST, port);
  16429. cli.set_read_timeout(60, 0);
  16430. cli.set_write_timeout(60, 0);
  16431. // '-' is the worst case: it matches the first character of the boundary, so
  16432. // every position has to be checked against it.
  16433. auto post_dashes = [&](size_t size) {
  16434. const std::string body(size, '-');
  16435. auto start = std::chrono::steady_clock::now();
  16436. auto res =
  16437. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16438. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16439. std::chrono::steady_clock::now() - start)
  16440. .count();
  16441. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16442. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16443. return ms;
  16444. };
  16445. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16446. // Windows.
  16447. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16448. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16449. // Comparing the two sizes rather than checking an absolute duration keeps
  16450. // this meaningful across build types and CI load, both of which move the
  16451. // absolute numbers by more than an order of magnitude. Four times the bytes
  16452. // costs about four times the time when parsing is linear, and about sixteen
  16453. // times when the body is buffered and rescanned.
  16454. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16455. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16456. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16457. << "ms, which suggests the body is being buffered and rescanned";
  16458. }
  16459. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16460. // A boundary can only be followed by CRLF or by "--", so anything else is
  16461. // malformed no matter what comes next. The parser must say so right away
  16462. // instead of buffering the rest of the declared body.
  16463. Server svr;
  16464. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16465. res.set_content("ok", "text/plain");
  16466. });
  16467. auto port = svr.bind_to_any_port(HOST);
  16468. thread t = thread([&] { svr.listen_after_bind(); });
  16469. auto se = detail::scope_exit([&] {
  16470. svr.stop();
  16471. t.join();
  16472. ASSERT_FALSE(svr.is_running());
  16473. });
  16474. svr.wait_until_ready();
  16475. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16476. // buffers instead of failing would still be waiting for the remaining bytes.
  16477. const std::string body = "--zzzz\r\n"
  16478. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16479. "\r\n"
  16480. "text1"
  16481. "\r\n--zzzzXX";
  16482. const std::string req = "POST /post HTTP/1.1\r\n"
  16483. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16484. "Content-Length: 1048576\r\n"
  16485. "\r\n" +
  16486. body;
  16487. std::string response;
  16488. ASSERT_TRUE(send_request(3, req, &response, port));
  16489. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16490. EXPECT_EQ("400", response.substr(9, 3));
  16491. }
  16492. // Posts a multipart body split into two writes, so that the server sees the
  16493. // split at whatever offset the caller chose, and expects the single "text1"
  16494. // field to come through.
  16495. static void expect_split_multipart_ok(const std::string &body1,
  16496. const std::string &body2) {
  16497. auto handled = false;
  16498. Server svr;
  16499. svr.Post("/post", [&](const Request &req, Response &) {
  16500. EXPECT_EQ(1u, req.form.fields.size());
  16501. EXPECT_EQ("text1", req.form.get_field("text1"));
  16502. handled = true;
  16503. });
  16504. auto port = svr.bind_to_any_port(HOST);
  16505. thread t = thread([&] { svr.listen_after_bind(); });
  16506. auto se = detail::scope_exit([&] {
  16507. svr.stop();
  16508. t.join();
  16509. ASSERT_FALSE(svr.is_running());
  16510. ASSERT_TRUE(handled);
  16511. });
  16512. svr.wait_until_ready();
  16513. // "Connection: close" makes the server close once it has answered, so the
  16514. // response drain ends immediately instead of idling until the read timeout.
  16515. const std::string head =
  16516. "POST /post HTTP/1.1\r\n"
  16517. "Host: localhost\r\n"
  16518. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16519. "Connection: close\r\n"
  16520. "Content-Length: " +
  16521. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16522. std::string response;
  16523. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16524. ASSERT_GE(response.size(), 12u) << "no response";
  16525. EXPECT_EQ("200", response.substr(9, 3));
  16526. }
  16527. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16528. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16529. // ignored, including when it does not arrive in the same read as the
  16530. // close-delimiter itself.
  16531. expect_split_multipart_ok("--zzzz\r\n"
  16532. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16533. "\r\n"
  16534. "text1"
  16535. "\r\n--zzzz--",
  16536. "\r\nthis epilogue must be ignored\r\n");
  16537. }
  16538. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16539. // The initial boundary may be preceded by a preamble of any length and may
  16540. // straddle a read boundary. Discarding data while waiting for it must not
  16541. // throw away a partial boundary sitting at the end of the buffer.
  16542. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16543. "zz\r\n"
  16544. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16545. "\r\n"
  16546. "text1"
  16547. "\r\n--zzzz--\r\n");
  16548. }
  16549. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16550. // The received boundary was only checked for being non-empty, so it could be
  16551. // as long as a header is allowed to be. The parser scans the body for
  16552. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16553. // costs a nearly full comparison at nearly every position, making the
  16554. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16555. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16556. Server svr;
  16557. svr.Post("/post", [](const Request &req, Response &res) {
  16558. EXPECT_EQ(1u, req.form.fields.size());
  16559. EXPECT_EQ("text1", req.form.get_field("text1"));
  16560. res.set_content("ok", "text/plain");
  16561. });
  16562. auto port = svr.bind_to_any_port(HOST);
  16563. thread t = thread([&] { svr.listen_after_bind(); });
  16564. auto se = detail::scope_exit([&] {
  16565. svr.stop();
  16566. t.join();
  16567. ASSERT_FALSE(svr.is_running());
  16568. });
  16569. svr.wait_until_ready();
  16570. Client cli(HOST, port);
  16571. auto post_with_boundary_of_length = [&](size_t len) {
  16572. const std::string boundary(len, 'a');
  16573. const std::string body =
  16574. "--" + boundary +
  16575. "\r\n"
  16576. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16577. "\r\n"
  16578. "text1"
  16579. "\r\n--" +
  16580. boundary + "--\r\n";
  16581. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16582. };
  16583. auto res = post_with_boundary_of_length(70);
  16584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16585. EXPECT_EQ(StatusCode::OK_200, res->status);
  16586. res = post_with_boundary_of_length(71);
  16587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16588. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16589. }
  16590. TEST(MakeFileBodyTest, Basic) {
  16591. const std::string file_content(4096, 'Z');
  16592. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16593. {
  16594. std::ofstream ofs(tmp_path, std::ios::binary);
  16595. ofs.write(file_content.data(),
  16596. static_cast<std::streamsize>(file_content.size()));
  16597. }
  16598. auto handled = false;
  16599. Server svr;
  16600. svr.Post("/upload", [&](const Request &req, Response &res) {
  16601. EXPECT_EQ(file_content, req.body);
  16602. handled = true;
  16603. res.status = StatusCode::OK_200;
  16604. });
  16605. auto port = svr.bind_to_any_port(HOST);
  16606. auto t = thread([&] { svr.listen_after_bind(); });
  16607. auto se = detail::scope_exit([&] {
  16608. svr.stop();
  16609. t.join();
  16610. ASSERT_FALSE(svr.is_running());
  16611. ASSERT_TRUE(handled);
  16612. std::remove(tmp_path.c_str());
  16613. });
  16614. svr.wait_until_ready();
  16615. auto fb = make_file_body(tmp_path);
  16616. ASSERT_GT(fb.first, 0u);
  16617. Client cli(HOST, port);
  16618. auto res =
  16619. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16621. EXPECT_EQ(StatusCode::OK_200, res->status);
  16622. }
  16623. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16624. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16625. {
  16626. std::ofstream ofs(path, std::ios::binary);
  16627. const std::string content(100, 'A');
  16628. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16629. }
  16630. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16631. auto body = make_file_body(path);
  16632. ASSERT_EQ(100u, body.first);
  16633. ASSERT_TRUE(static_cast<bool>(body.second));
  16634. // Rewritten shorter after its length was measured - and, on a server, after
  16635. // that length has already gone out as Content-Length.
  16636. {
  16637. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16638. const std::string content(10, 'A');
  16639. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16640. }
  16641. std::string written;
  16642. DataSink sink;
  16643. sink.write = [&](const char *d, size_t l) {
  16644. written.append(d, l);
  16645. return true;
  16646. };
  16647. // The provider has to report failure. write_content_with_progress() advances
  16648. // its offset only by what was written, so a provider that returns true
  16649. // without completing the length it promised is called again straight away,
  16650. // and again.
  16651. EXPECT_FALSE(body.second(0, body.first, sink));
  16652. EXPECT_EQ(std::string(10, 'A'), written);
  16653. }
  16654. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16655. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16656. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16657. {
  16658. std::ofstream ofs(path, std::ios::binary);
  16659. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16660. }
  16661. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16662. auto body = make_file_body(path);
  16663. ASSERT_EQ(content.size(), body.first);
  16664. ASSERT_TRUE(static_cast<bool>(body.second));
  16665. std::string written;
  16666. DataSink sink;
  16667. sink.write = [&](const char *d, size_t l) {
  16668. written.append(d, l);
  16669. return true;
  16670. };
  16671. EXPECT_TRUE(body.second(0, body.first, sink));
  16672. EXPECT_EQ(content, written);
  16673. }
  16674. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16675. static constexpr unsigned int number_of_tasks{1000000};
  16676. std::atomic_uint count{0};
  16677. std::unique_ptr<TaskQueue> task_queue{
  16678. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16679. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16680. auto queued = task_queue->enqueue(
  16681. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16682. EXPECT_TRUE(queued);
  16683. }
  16684. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16685. task_queue->shutdown();
  16686. #else
  16687. EXPECT_NO_THROW(task_queue->shutdown());
  16688. #endif
  16689. EXPECT_EQ(number_of_tasks, count.load());
  16690. }
  16691. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16692. static constexpr unsigned int number_of_tasks{1000000};
  16693. static constexpr unsigned int qlimit{2};
  16694. unsigned int queued_count{0};
  16695. std::atomic_uint count{0};
  16696. std::unique_ptr<TaskQueue> task_queue{
  16697. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16698. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16699. if (task_queue->enqueue(
  16700. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16701. queued_count++;
  16702. }
  16703. }
  16704. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16705. task_queue->shutdown();
  16706. #else
  16707. EXPECT_NO_THROW(task_queue->shutdown());
  16708. #endif
  16709. EXPECT_EQ(queued_count, count.load());
  16710. EXPECT_TRUE(queued_count <= number_of_tasks);
  16711. EXPECT_TRUE(queued_count >= qlimit);
  16712. }
  16713. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16714. // Use a short idle timeout so a dynamic thread spawns, times out and
  16715. // exits during the test, and the pool keeps working afterwards.
  16716. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16717. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16718. /*idle_timeout_sec=*/1}};
  16719. std::atomic_uint count{0};
  16720. std::condition_variable cv;
  16721. std::mutex mtx;
  16722. bool release = false;
  16723. // Block the base thread so the second task spawns a dynamic thread.
  16724. EXPECT_TRUE(task_queue->enqueue([&] {
  16725. std::unique_lock<std::mutex> lock(mtx);
  16726. while (!release) {
  16727. cv.wait(lock);
  16728. }
  16729. count++;
  16730. }));
  16731. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16732. // Let the dynamic thread finish its task and exceed the idle timeout.
  16733. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16734. {
  16735. std::unique_lock<std::mutex> lock(mtx);
  16736. release = true;
  16737. }
  16738. cv.notify_all();
  16739. // The pool must still accept and run tasks after the dynamic thread exited.
  16740. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16741. task_queue->shutdown();
  16742. EXPECT_EQ(3u, count.load());
  16743. }
  16744. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16745. static constexpr size_t number_of_tasks{32};
  16746. std::unique_ptr<TaskQueue> task_queue{
  16747. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16748. // Let the base threads go idle so the burst below finds them waiting.
  16749. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16750. std::mutex mtx;
  16751. std::condition_variable cv;
  16752. size_t running = 0;
  16753. bool release = false;
  16754. for (size_t i = 0; i < number_of_tasks; i++) {
  16755. EXPECT_TRUE(task_queue->enqueue([&] {
  16756. std::unique_lock<std::mutex> lock(mtx);
  16757. running++;
  16758. cv.notify_all();
  16759. cv.wait(lock, [&] { return release; });
  16760. }));
  16761. }
  16762. {
  16763. std::unique_lock<std::mutex> lock(mtx);
  16764. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16765. [&] { return running == number_of_tasks; }));
  16766. release = true;
  16767. }
  16768. cv.notify_all();
  16769. task_queue->shutdown();
  16770. }
  16771. TEST(TaskQueueTest, MaxQueuedRequests) {
  16772. static constexpr unsigned int qlimit{3};
  16773. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16774. std::condition_variable sem_cv;
  16775. std::mutex sem_mtx;
  16776. int credits = 0;
  16777. bool queued;
  16778. /* Fill up the queue with tasks that will block until we give them credits to
  16779. * complete. */
  16780. for (unsigned int n = 0; n <= qlimit;) {
  16781. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16782. std::unique_lock<std::mutex> lock(sem_mtx);
  16783. while (credits <= 0) {
  16784. sem_cv.wait(lock);
  16785. }
  16786. /* Consume the credit and signal the test code if they are all gone. */
  16787. if (--credits == 0) { sem_cv.notify_one(); }
  16788. });
  16789. if (n < qlimit) {
  16790. /* The first qlimit enqueues must succeed. */
  16791. EXPECT_TRUE(queued);
  16792. } else {
  16793. /* The last one will succeed only when the worker thread
  16794. * starts and dequeues the first blocking task. Although
  16795. * not necessary for the correctness of this test, we sleep for
  16796. * a short while to avoid busy waiting. */
  16797. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16798. }
  16799. if (queued) { n++; }
  16800. }
  16801. /* Further enqueues must fail since the queue is full. */
  16802. for (auto i = 0; i < 4; i++) {
  16803. queued = task_queue->enqueue([] {});
  16804. EXPECT_FALSE(queued);
  16805. }
  16806. /* Give the credits to allow the previous tasks to complete. */
  16807. {
  16808. std::unique_lock<std::mutex> lock(sem_mtx);
  16809. credits += qlimit + 1;
  16810. }
  16811. sem_cv.notify_all();
  16812. /* Wait for all the credits to be consumed. */
  16813. {
  16814. std::unique_lock<std::mutex> lock(sem_mtx);
  16815. while (credits > 0) {
  16816. sem_cv.wait(lock);
  16817. }
  16818. }
  16819. /* Check that we are able again to enqueue at least qlimit tasks. */
  16820. for (unsigned int i = 0; i < qlimit; i++) {
  16821. queued = task_queue->enqueue([] {});
  16822. EXPECT_TRUE(queued);
  16823. }
  16824. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16825. task_queue->shutdown();
  16826. #else
  16827. EXPECT_NO_THROW(task_queue->shutdown());
  16828. #endif
  16829. }
  16830. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16831. Server svr;
  16832. std::string method;
  16833. std::string body;
  16834. auto has_content_length = false;
  16835. auto has_transfer_encoding = false;
  16836. std::atomic<int> bad_requests{0};
  16837. // Leftover body bytes get parsed as a malformed request and answered with
  16838. // 400
  16839. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16840. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16841. });
  16842. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16843. res.set_redirect("/down", StatusCode::SeeOther_303);
  16844. });
  16845. svr.Get("/down", [&](const Request &req, Response &res) {
  16846. method = req.method;
  16847. body = req.body;
  16848. has_content_length = req.has_header("Content-Length");
  16849. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16850. res.set_content("ok", "text/plain");
  16851. });
  16852. auto port = svr.bind_to_any_port(HOST);
  16853. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16854. auto se = detail::scope_exit([&] {
  16855. svr.stop();
  16856. thread.join();
  16857. ASSERT_FALSE(svr.is_running());
  16858. });
  16859. svr.wait_until_ready();
  16860. const std::string payload = "SECRET-BODY";
  16861. auto check = [&](Client &cli, const Result &res) {
  16862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16863. EXPECT_EQ(StatusCode::OK_200, res->status);
  16864. EXPECT_EQ("ok", res->body);
  16865. EXPECT_EQ("GET", method);
  16866. EXPECT_TRUE(body.empty());
  16867. EXPECT_FALSE(has_content_length);
  16868. EXPECT_FALSE(has_transfer_encoding);
  16869. // Nothing of the original body may be left on the connection
  16870. auto res2 = cli.Get("/down");
  16871. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16872. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16873. EXPECT_EQ("ok", res2->body);
  16874. EXPECT_EQ(0, bad_requests);
  16875. };
  16876. // With content length
  16877. {
  16878. Client cli(HOST, port);
  16879. cli.set_keep_alive(true);
  16880. cli.set_follow_location(true);
  16881. auto res = cli.Post(
  16882. "/up", payload.size(),
  16883. [&](size_t offset, size_t length, DataSink &sink) {
  16884. return sink.write(payload.data() + offset, length);
  16885. },
  16886. "text/plain");
  16887. check(cli, res);
  16888. }
  16889. // Without content length (chunked)
  16890. {
  16891. Client cli(HOST, port);
  16892. cli.set_keep_alive(true);
  16893. cli.set_follow_location(true);
  16894. auto res = cli.Post(
  16895. "/up",
  16896. [&](size_t /*offset*/, DataSink &sink) {
  16897. sink.write(payload.data(), payload.size());
  16898. sink.done();
  16899. return true;
  16900. },
  16901. "text/plain");
  16902. check(cli, res);
  16903. }
  16904. }
  16905. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16906. Server svr;
  16907. std::string target;
  16908. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16909. // Echo the still-encoded name back in the Location
  16910. const std::string prefix = "/start/";
  16911. res.status = StatusCode::Found_302;
  16912. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16913. });
  16914. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16915. target = req.target;
  16916. res.set_content("ok", "text/plain");
  16917. });
  16918. auto port = svr.bind_to_any_port(HOST);
  16919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16920. auto se = detail::scope_exit([&] {
  16921. svr.stop();
  16922. thread.join();
  16923. ASSERT_FALSE(svr.is_running());
  16924. });
  16925. svr.wait_until_ready();
  16926. // Decoding the Location path would turn the first four into a path
  16927. // separator, a query delimiter, a fragment delimiter and a different
  16928. // percent-encoded octet. The rest must keep reaching the server as they are.
  16929. const std::vector<std::string> names = {
  16930. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16931. };
  16932. for (auto path_encode : {true, false}) {
  16933. Client cli(HOST, port);
  16934. cli.set_follow_location(true);
  16935. cli.set_path_encode(path_encode);
  16936. for (const auto &name : names) {
  16937. target.clear();
  16938. auto res = cli.Get("/start/" + name);
  16939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16940. EXPECT_EQ(StatusCode::OK_200, res->status);
  16941. EXPECT_EQ("/dest/" + name, target);
  16942. }
  16943. }
  16944. }
  16945. TEST(RedirectTest, NotModifiedIsReturned) {
  16946. Server svr;
  16947. svr.Get("/cached", [](const Request &, Response &res) {
  16948. res.status = StatusCode::NotModified_304;
  16949. });
  16950. auto port = svr.bind_to_any_port(HOST);
  16951. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16952. auto se = detail::scope_exit([&] {
  16953. svr.stop();
  16954. thread.join();
  16955. ASSERT_FALSE(svr.is_running());
  16956. });
  16957. svr.wait_until_ready();
  16958. Client cli(HOST, port);
  16959. cli.set_follow_location(true);
  16960. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16962. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16963. }
  16964. TEST(RedirectTest, NoLocationIsReturned) {
  16965. Server svr;
  16966. svr.Get("/no-location", [](const Request &, Response &res) {
  16967. res.status = StatusCode::Found_302;
  16968. res.set_content("no location", "text/plain");
  16969. });
  16970. auto port = svr.bind_to_any_port(HOST);
  16971. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16972. auto se = detail::scope_exit([&] {
  16973. svr.stop();
  16974. thread.join();
  16975. ASSERT_FALSE(svr.is_running());
  16976. });
  16977. svr.wait_until_ready();
  16978. Client cli(HOST, port);
  16979. cli.set_follow_location(true);
  16980. auto res = cli.Get("/no-location");
  16981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16982. EXPECT_EQ(StatusCode::Found_302, res->status);
  16983. EXPECT_EQ("no location", res->body);
  16984. // The callbacks see the body of the response that is returned
  16985. auto handler_called = false;
  16986. auto progress_called = false;
  16987. std::string body;
  16988. auto res2 = cli.Get(
  16989. "/no-location",
  16990. [&](const Response &) {
  16991. handler_called = true;
  16992. return true;
  16993. },
  16994. [&](const char *data, size_t data_length) {
  16995. body.append(data, data_length);
  16996. return true;
  16997. },
  16998. [&](size_t, size_t) {
  16999. progress_called = true;
  17000. return true;
  17001. });
  17002. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17003. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17004. EXPECT_TRUE(handler_called);
  17005. EXPECT_TRUE(progress_called);
  17006. EXPECT_EQ("no location", body);
  17007. }
  17008. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17009. Server svr;
  17010. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17011. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17012. });
  17013. svr.Get("/hello", [](const Request &req, Response &res) {
  17014. res.set_content(req.get_param_value("key"), "text/plain");
  17015. });
  17016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17017. auto se = detail::scope_exit([&] {
  17018. svr.stop();
  17019. thread.join();
  17020. ASSERT_FALSE(svr.is_running());
  17021. });
  17022. svr.wait_until_ready();
  17023. {
  17024. Client cli(HOST, PORT);
  17025. cli.set_follow_location(true);
  17026. auto res = cli.Get("/");
  17027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17028. EXPECT_EQ(StatusCode::OK_200, res->status);
  17029. EXPECT_EQ("val&key2=val2", res->body);
  17030. }
  17031. }
  17032. #endif
  17033. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17034. Server svr;
  17035. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17036. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17037. });
  17038. svr.Get("/hello", [](const Request &req, Response &res) {
  17039. res.set_content(req.get_param_value("key"), "text/plain");
  17040. });
  17041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17042. auto se = detail::scope_exit([&] {
  17043. svr.stop();
  17044. thread.join();
  17045. ASSERT_FALSE(svr.is_running());
  17046. });
  17047. svr.wait_until_ready();
  17048. {
  17049. Client cli(HOST, PORT);
  17050. cli.set_follow_location(true);
  17051. auto res = cli.Get("/");
  17052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17053. EXPECT_EQ(StatusCode::OK_200, res->status);
  17054. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17055. }
  17056. }
  17057. TEST(RedirectTest, RedirectWithPlusInPath) {
  17058. Server svr;
  17059. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17060. res.set_redirect("/a+b");
  17061. });
  17062. // Route pattern uses regex; escape + as \\+
  17063. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17064. res.set_content(req.path, "text/plain");
  17065. });
  17066. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17067. auto se = detail::scope_exit([&] {
  17068. svr.stop();
  17069. thread.join();
  17070. ASSERT_FALSE(svr.is_running());
  17071. });
  17072. svr.wait_until_ready();
  17073. {
  17074. Client cli(HOST, PORT);
  17075. cli.set_follow_location(true);
  17076. auto res = cli.Get("/");
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(StatusCode::OK_200, res->status);
  17079. EXPECT_EQ("/a+b", res->body);
  17080. }
  17081. }
  17082. TEST(RedirectTest, ResolveRelativeLocation) {
  17083. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17084. const std::vector<std::pair<std::string, std::string>> cases = {
  17085. {"g", "/b/c/g"},
  17086. {"./g", "/b/c/g"},
  17087. {"g/", "/b/c/g/"},
  17088. {"?y", "/b/c/d;p?y"},
  17089. {"g?y", "/b/c/g?y"},
  17090. {"#s", "/b/c/d;p?q#s"},
  17091. {"g#s", "/b/c/g#s"},
  17092. {"g?y#s", "/b/c/g?y#s"},
  17093. {";x", "/b/c/;x"},
  17094. {"g;x", "/b/c/g;x"},
  17095. {".", "/b/c/"},
  17096. {"./", "/b/c/"},
  17097. {"..", "/b/"},
  17098. {"../", "/b/"},
  17099. {"../g", "/b/g"},
  17100. {"../..", "/"},
  17101. {"../../", "/"},
  17102. {"../../g", "/g"},
  17103. {"../../../g", "/g"},
  17104. {"g.", "/b/c/g."},
  17105. {".g", "/b/c/.g"},
  17106. {"g..", "/b/c/g.."},
  17107. {"..g", "/b/c/..g"},
  17108. {"./../g", "/b/g"},
  17109. {"./g/.", "/b/c/g/"},
  17110. {"g/./h", "/b/c/g/h"},
  17111. {"g/../h", "/b/c/h"},
  17112. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17113. {"g;x=1/../y", "/b/c/y"},
  17114. {"g?y/./x", "/b/c/g?y/./x"},
  17115. {"g#s/../x", "/b/c/g#s/../x"},
  17116. // Not relative-path references, so left for parse_url.
  17117. {"/g", "/g"},
  17118. {"//g", "//g"},
  17119. {"http://g/x", "http://g/x"},
  17120. {"g:h", "g:h"},
  17121. };
  17122. for (const auto &c : cases) {
  17123. EXPECT_EQ(c.second,
  17124. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17125. << c.first;
  17126. }
  17127. }
  17128. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17129. Server svr;
  17130. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17131. res.set_redirect(req.get_param_value("to"));
  17132. });
  17133. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17134. res.set_content(req.target, "text/plain");
  17135. });
  17136. svr.Get("/other", [](const Request &req, Response &res) {
  17137. res.set_content(req.target, "text/plain");
  17138. });
  17139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17140. auto se = detail::scope_exit([&] {
  17141. svr.stop();
  17142. thread.join();
  17143. ASSERT_FALSE(svr.is_running());
  17144. });
  17145. svr.wait_until_ready();
  17146. const std::vector<std::pair<std::string, std::string>> cases = {
  17147. {"next", "/dir/next"},
  17148. {"./next?x=1", "/dir/next?x=1"},
  17149. {"../other", "/other"},
  17150. };
  17151. for (const auto &c : cases) {
  17152. Client cli(HOST, PORT);
  17153. cli.set_follow_location(true);
  17154. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17155. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17156. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17157. EXPECT_EQ(c.second, res->body) << c.first;
  17158. }
  17159. }
  17160. #ifdef CPPHTTPLIB_SSL_ENABLED
  17161. TEST(RedirectTest, Issue2185_Online) {
  17162. SSLClient client("github.com");
  17163. client.set_follow_location(true);
  17164. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17165. "Coollab-Windows.zip");
  17166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17167. EXPECT_EQ(StatusCode::OK_200, res->status);
  17168. EXPECT_EQ(9920427U, res->body.size());
  17169. }
  17170. #endif
  17171. TEST(VulnerabilityTest, CRLFInjection) {
  17172. Server svr;
  17173. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17174. res.set_content("Hello 1", "text/plain");
  17175. });
  17176. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17177. res.set_content("Hello 2", "text/plain");
  17178. });
  17179. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17180. res.set_content("Hello 3", "text/plain");
  17181. });
  17182. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17183. res.set_content("Hello 4", "text/plain");
  17184. });
  17185. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17186. for (const auto &x : req.headers) {
  17187. auto key = x.first;
  17188. EXPECT_STRNE("evil", key.c_str());
  17189. }
  17190. });
  17191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. thread.join();
  17195. ASSERT_FALSE(svr.is_running());
  17196. });
  17197. svr.wait_until_ready();
  17198. {
  17199. Client cli(HOST, PORT);
  17200. cli.Post("/test1", "A=B",
  17201. "application/x-www-form-urlencoded\r\nevil: hello1");
  17202. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17203. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17204. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17205. }
  17206. }
  17207. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17208. auto server_thread = std::thread([] {
  17209. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17210. default_socket_options(srv);
  17211. sockaddr_in addr{};
  17212. addr.sin_family = AF_INET;
  17213. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17214. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17215. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17216. ::listen(srv, 1);
  17217. sockaddr_in cli_addr{};
  17218. socklen_t cli_len = sizeof(cli_addr);
  17219. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17220. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17221. std::string buf_all;
  17222. char buf[2048];
  17223. ssize_t n;
  17224. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17225. buf_all.append(buf, static_cast<size_t>(n));
  17226. size_t pos;
  17227. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17228. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17229. auto e = request_block.find("\r\n");
  17230. if (e != std::string::npos) {
  17231. auto request_line = request_block.substr(0, e);
  17232. std::string msg =
  17233. "CRLF injection detected in request line: '" + request_line + "'";
  17234. EXPECT_FALSE(true) << msg;
  17235. }
  17236. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17237. ::send(cli,
  17238. #ifdef _WIN32
  17239. static_cast<const char *>(resp.c_str()),
  17240. static_cast<int>(resp.size()),
  17241. #else
  17242. resp.c_str(), resp.size(),
  17243. #endif
  17244. 0);
  17245. buf_all.erase(0, pos + 4);
  17246. }
  17247. }
  17248. detail::close_socket(cli);
  17249. detail::close_socket(srv);
  17250. });
  17251. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17252. auto cli = Client("127.0.0.1", PORT + 1);
  17253. auto headers = Headers{
  17254. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17255. {"Connection", "keep-alive"}};
  17256. auto res = cli.Get("/hi", headers);
  17257. EXPECT_FALSE(res);
  17258. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17259. server_thread.join();
  17260. }
  17261. // A request rejected before any byte reaches the socket must fail right away
  17262. // instead of waiting for a response the server will never send.
  17263. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17264. // The kernel completes the TCP handshake from the listen backlog, so the
  17265. // client connects, but nothing ever reads, responds or closes.
  17266. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17267. default_socket_options(srv);
  17268. sockaddr_in addr{};
  17269. addr.sin_family = AF_INET;
  17270. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17271. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17272. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17273. ASSERT_EQ(0, ::listen(srv, 8));
  17274. auto cli = Client("127.0.0.1", PORT + 1);
  17275. cli.set_read_timeout(10, 0);
  17276. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17277. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17278. std::chrono::steady_clock::now() - start)
  17279. .count();
  17280. };
  17281. {
  17282. Request req;
  17283. req.method = "GE T";
  17284. req.path = "/";
  17285. auto start = std::chrono::steady_clock::now();
  17286. auto res = cli.send(req);
  17287. EXPECT_FALSE(res);
  17288. EXPECT_EQ(Error::Write, res.error());
  17289. EXPECT_LT(elapsed_ms(start), 1000);
  17290. }
  17291. {
  17292. auto start = std::chrono::steady_clock::now();
  17293. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17294. EXPECT_FALSE(res);
  17295. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17296. EXPECT_LT(elapsed_ms(start), 1000);
  17297. }
  17298. EXPECT_FALSE(cli.is_socket_open());
  17299. detail::close_socket(srv);
  17300. }
  17301. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17302. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17303. default_socket_options(srv);
  17304. sockaddr_in addr{};
  17305. addr.sin_family = AF_INET;
  17306. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17307. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17308. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17309. ASSERT_EQ(0, ::listen(srv, 1));
  17310. std::string received;
  17311. auto server_thread = std::thread([&] {
  17312. auto sock = ::accept(srv, nullptr, nullptr);
  17313. if (sock == INVALID_SOCKET) { return; }
  17314. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17315. char buf[2048];
  17316. ssize_t n;
  17317. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17318. received.append(buf, static_cast<size_t>(n));
  17319. }
  17320. detail::close_socket(sock);
  17321. });
  17322. {
  17323. auto cli = Client("127.0.0.1", PORT + 1);
  17324. // "Z" sorts after the default headers, so writing straight to the socket
  17325. // would have sent the request line and those headers before the rejection.
  17326. auto handle =
  17327. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17328. EXPECT_FALSE(handle.is_valid());
  17329. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17330. }
  17331. server_thread.join();
  17332. detail::close_socket(srv);
  17333. EXPECT_TRUE(received.empty()) << received;
  17334. }
  17335. TEST(PathParamsTest, StaticMatch) {
  17336. const auto pattern = "/users/all";
  17337. detail::PathParamsMatcher matcher(pattern);
  17338. Request request;
  17339. request.path = "/users/all";
  17340. ASSERT_TRUE(matcher.match(request));
  17341. std::unordered_map<std::string, std::string> expected_params = {};
  17342. EXPECT_EQ(request.path_params, expected_params);
  17343. }
  17344. TEST(PathParamsTest, StaticMismatch) {
  17345. const auto pattern = "/users/all";
  17346. detail::PathParamsMatcher matcher(pattern);
  17347. Request request;
  17348. request.path = "/users/1";
  17349. ASSERT_FALSE(matcher.match(request));
  17350. }
  17351. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17352. const auto pattern = "/users/:id/subscriptions";
  17353. detail::PathParamsMatcher matcher(pattern);
  17354. Request request;
  17355. request.path = "/users/42/subscriptions";
  17356. ASSERT_TRUE(matcher.match(request));
  17357. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17358. EXPECT_EQ(request.path_params, expected_params);
  17359. }
  17360. TEST(PathParamsTest, SingleParamInTheEnd) {
  17361. const auto pattern = "/users/:id";
  17362. detail::PathParamsMatcher matcher(pattern);
  17363. Request request;
  17364. request.path = "/users/24";
  17365. ASSERT_TRUE(matcher.match(request));
  17366. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17367. EXPECT_EQ(request.path_params, expected_params);
  17368. }
  17369. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17370. const auto pattern = "/users/:id/";
  17371. detail::PathParamsMatcher matcher(pattern);
  17372. Request request;
  17373. request.path = "/users/42/";
  17374. ASSERT_TRUE(matcher.match(request));
  17375. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17376. EXPECT_EQ(request.path_params, expected_params);
  17377. }
  17378. TEST(PathParamsTest, EmptyParam) {
  17379. const auto pattern = "/users/:id/";
  17380. detail::PathParamsMatcher matcher(pattern);
  17381. Request request;
  17382. request.path = "/users//";
  17383. ASSERT_TRUE(matcher.match(request));
  17384. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17385. EXPECT_EQ(request.path_params, expected_params);
  17386. }
  17387. TEST(PathParamsTest, FragmentMismatch) {
  17388. const auto pattern = "/users/:id/";
  17389. detail::PathParamsMatcher matcher(pattern);
  17390. Request request;
  17391. request.path = "/admins/24/";
  17392. ASSERT_FALSE(matcher.match(request));
  17393. }
  17394. TEST(PathParamsTest, ExtraFragments) {
  17395. const auto pattern = "/users/:id";
  17396. detail::PathParamsMatcher matcher(pattern);
  17397. Request request;
  17398. request.path = "/users/42/subscriptions";
  17399. ASSERT_FALSE(matcher.match(request));
  17400. }
  17401. TEST(PathParamsTest, MissingTrailingParam) {
  17402. const auto pattern = "/users/:id";
  17403. detail::PathParamsMatcher matcher(pattern);
  17404. Request request;
  17405. request.path = "/users";
  17406. ASSERT_FALSE(matcher.match(request));
  17407. }
  17408. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17409. const auto pattern = "/users/:id/subscriptions";
  17410. detail::PathParamsMatcher matcher(pattern);
  17411. Request request;
  17412. request.path = "/users/subscriptions";
  17413. ASSERT_FALSE(matcher.match(request));
  17414. }
  17415. TEST(PathParamsTest, MultipleParams) {
  17416. const auto pattern = "/users/:userid/subscriptions/:subid";
  17417. detail::PathParamsMatcher matcher(pattern);
  17418. Request request;
  17419. request.path = "/users/42/subscriptions/2";
  17420. ASSERT_TRUE(matcher.match(request));
  17421. std::unordered_map<std::string, std::string> expected_params = {
  17422. {"userid", "42"}, {"subid", "2"}};
  17423. EXPECT_EQ(request.path_params, expected_params);
  17424. }
  17425. TEST(PathParamsTest, SequenceOfParams) {
  17426. const auto pattern = "/values/:x/:y/:z";
  17427. detail::PathParamsMatcher matcher(pattern);
  17428. Request request;
  17429. request.path = "/values/1/2/3";
  17430. ASSERT_TRUE(matcher.match(request));
  17431. std::unordered_map<std::string, std::string> expected_params = {
  17432. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17433. EXPECT_EQ(request.path_params, expected_params);
  17434. }
  17435. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17436. const auto pattern = "/prefix:suffix";
  17437. detail::PathParamsMatcher matcher(pattern);
  17438. Request request;
  17439. request.path = "/prefix:suffix";
  17440. ASSERT_TRUE(matcher.match(request));
  17441. const std::unordered_map<std::string, std::string> expected_params = {};
  17442. EXPECT_EQ(request.path_params, expected_params);
  17443. }
  17444. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17445. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17446. // calling thread's stack on a long enough path for a quantified pattern;
  17447. // RegexMatcher must refuse to run regex matching on paths beyond
  17448. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17449. detail::RegexMatcher matcher("/files/(.*)");
  17450. Request within_limit;
  17451. within_limit.path = "/files/" + std::string(10, 'A');
  17452. EXPECT_TRUE(matcher.match(within_limit));
  17453. Request over_limit;
  17454. over_limit.path =
  17455. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17456. EXPECT_FALSE(matcher.match(over_limit));
  17457. }
  17458. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17459. Server svr;
  17460. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17461. res.set_content("ok", "text/plain");
  17462. });
  17463. auto port = svr.bind_to_any_port(HOST);
  17464. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17465. auto se = detail::scope_exit([&] {
  17466. svr.stop();
  17467. thread.join();
  17468. ASSERT_FALSE(svr.is_running());
  17469. });
  17470. svr.wait_until_ready();
  17471. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17472. // request URI limit; this used to be able to crash the process.
  17473. std::string path =
  17474. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17475. std::string req = "GET " + path +
  17476. " HTTP/1.1\r\n"
  17477. "Host: " +
  17478. std::string(HOST) + ":" + std::to_string(port) +
  17479. "\r\n"
  17480. "Connection: close\r\n"
  17481. "\r\n";
  17482. std::string response;
  17483. ASSERT_TRUE(send_request(5, req, &response, port));
  17484. EXPECT_NE(std::string::npos, response.find("404"));
  17485. }
  17486. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17487. Server svr;
  17488. auto handler = [](const Request & /*req*/, Response &res) {
  17489. res.set_content("hit", "text/plain");
  17490. };
  17491. // No regex metacharacter, so this one is compared literally
  17492. svr.Get("/literal/route", handler);
  17493. // '.' is a regex metacharacter, so this one must keep regex semantics
  17494. svr.Get("/a.c", handler);
  17495. auto port = svr.bind_to_any_port(HOST);
  17496. std::thread t([&]() { svr.listen_after_bind(); });
  17497. auto se = detail::scope_exit([&] {
  17498. svr.stop();
  17499. t.join();
  17500. ASSERT_FALSE(svr.is_running());
  17501. });
  17502. svr.wait_until_ready();
  17503. Client cli(HOST, port);
  17504. struct {
  17505. const char *path;
  17506. int status;
  17507. } cases[] = {
  17508. {"/literal/route", StatusCode::OK_200},
  17509. {"/literal/routes", StatusCode::NotFound_404},
  17510. {"/literal/rout", StatusCode::NotFound_404},
  17511. {"/abc", StatusCode::OK_200},
  17512. {"/a.c", StatusCode::OK_200},
  17513. };
  17514. for (const auto &x : cases) {
  17515. auto res = cli.Get(x.path);
  17516. ASSERT_TRUE(res) << x.path;
  17517. EXPECT_EQ(x.status, res->status) << x.path;
  17518. }
  17519. }
  17520. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17521. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17522. // from exhausting the stack, so it must only constrain routes that actually
  17523. // run a regular expression. A literal route is matched by comparison and
  17524. // stays usable at any length.
  17525. Server svr;
  17526. const std::string pattern =
  17527. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17528. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17529. res.set_content("hit", "text/plain");
  17530. });
  17531. auto port = svr.bind_to_any_port(HOST);
  17532. std::thread t([&]() { svr.listen_after_bind(); });
  17533. auto se = detail::scope_exit([&] {
  17534. svr.stop();
  17535. t.join();
  17536. ASSERT_FALSE(svr.is_running());
  17537. });
  17538. svr.wait_until_ready();
  17539. Client cli(HOST, port);
  17540. auto res = cli.Get(pattern);
  17541. ASSERT_TRUE(res);
  17542. EXPECT_EQ(StatusCode::OK_200, res->status);
  17543. }
  17544. TEST(ParseUrlTest, VariousPatterns) {
  17545. {
  17546. detail::UrlComponents uc;
  17547. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17548. EXPECT_EQ("http", uc.scheme);
  17549. EXPECT_EQ("example.com", uc.host);
  17550. EXPECT_EQ("8080", uc.port);
  17551. EXPECT_EQ("/path", uc.path);
  17552. EXPECT_EQ("?q=1", uc.query);
  17553. }
  17554. {
  17555. detail::UrlComponents uc;
  17556. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17557. EXPECT_EQ("https", uc.scheme);
  17558. EXPECT_EQ("example.com", uc.host);
  17559. EXPECT_TRUE(uc.port.empty());
  17560. EXPECT_EQ("/path", uc.path);
  17561. }
  17562. {
  17563. detail::UrlComponents uc;
  17564. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17565. EXPECT_EQ("::1", uc.host);
  17566. EXPECT_EQ("8080", uc.port);
  17567. EXPECT_EQ("/path", uc.path);
  17568. }
  17569. {
  17570. detail::UrlComponents uc;
  17571. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17572. }
  17573. {
  17574. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17575. // the path while the connection still targets the bracketed host.
  17576. detail::UrlComponents uc;
  17577. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17578. }
  17579. {
  17580. detail::UrlComponents uc;
  17581. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17582. }
  17583. {
  17584. detail::UrlComponents uc;
  17585. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17586. EXPECT_EQ("::1", uc.host);
  17587. EXPECT_TRUE(uc.port.empty());
  17588. EXPECT_EQ("/path", uc.path);
  17589. }
  17590. {
  17591. detail::UrlComponents uc;
  17592. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17593. EXPECT_TRUE(uc.scheme.empty());
  17594. EXPECT_EQ("example.com", uc.host);
  17595. EXPECT_EQ("/path", uc.path);
  17596. EXPECT_EQ("?q=1", uc.query);
  17597. }
  17598. {
  17599. detail::UrlComponents uc;
  17600. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17601. EXPECT_TRUE(uc.host.empty());
  17602. EXPECT_EQ("/path", uc.path);
  17603. EXPECT_EQ("?q=1", uc.query);
  17604. }
  17605. {
  17606. detail::UrlComponents uc;
  17607. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17608. EXPECT_EQ("example.com", uc.host);
  17609. EXPECT_EQ("8080", uc.port);
  17610. }
  17611. {
  17612. // Unix socket path — must not be parsed as host
  17613. detail::UrlComponents uc;
  17614. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17615. EXPECT_TRUE(uc.host.empty());
  17616. }
  17617. {
  17618. detail::UrlComponents uc;
  17619. ASSERT_TRUE(detail::parse_url("", uc));
  17620. EXPECT_TRUE(uc.host.empty());
  17621. EXPECT_TRUE(uc.path.empty());
  17622. }
  17623. {
  17624. detail::UrlComponents uc;
  17625. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17626. }
  17627. {
  17628. detail::UrlComponents uc;
  17629. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17630. }
  17631. {
  17632. // Accepted by parse_url; callers restrict to http/https
  17633. detail::UrlComponents uc;
  17634. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17635. EXPECT_EQ("ftp", uc.scheme);
  17636. }
  17637. {
  17638. detail::UrlComponents uc;
  17639. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17640. }
  17641. {
  17642. detail::UrlComponents uc;
  17643. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17644. }
  17645. }
  17646. TEST(ParseUrlTest, FragmentHandling) {
  17647. {
  17648. detail::UrlComponents uc;
  17649. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17650. EXPECT_EQ("/path", uc.path);
  17651. EXPECT_TRUE(uc.query.empty());
  17652. }
  17653. {
  17654. detail::UrlComponents uc;
  17655. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17656. EXPECT_TRUE(uc.path.empty());
  17657. EXPECT_TRUE(uc.query.empty());
  17658. }
  17659. }
  17660. TEST(ParseUrlTest, UserinfoHandling) {
  17661. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17662. // parsers would see evil.com as the host.
  17663. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17664. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17665. for (auto url : urls) {
  17666. detail::UrlComponents uc;
  17667. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17668. }
  17669. }
  17670. TEST(ParseUrlTest, IPv6EdgeCases) {
  17671. {
  17672. detail::UrlComponents uc;
  17673. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17674. EXPECT_TRUE(uc.scheme.empty());
  17675. EXPECT_EQ("::1", uc.host);
  17676. EXPECT_EQ("8080", uc.port);
  17677. }
  17678. {
  17679. // Zone ID '%25' is not in [a-fA-F0-9:]
  17680. detail::UrlComponents uc;
  17681. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17682. }
  17683. }
  17684. TEST(ParseUrlTest, SchemeEdgeCases) {
  17685. {
  17686. detail::UrlComponents uc;
  17687. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17688. }
  17689. {
  17690. detail::UrlComponents uc;
  17691. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17692. }
  17693. {
  17694. detail::UrlComponents uc;
  17695. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17696. }
  17697. }
  17698. TEST(ParseUrlTest, PortEdgeCases) {
  17699. {
  17700. detail::UrlComponents uc;
  17701. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17702. EXPECT_TRUE(uc.port.empty());
  17703. EXPECT_EQ("/path", uc.path);
  17704. }
  17705. {
  17706. // parse_url accepts any port string; validation is done by parse_port
  17707. detail::UrlComponents uc;
  17708. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17709. EXPECT_EQ("abc", uc.port);
  17710. }
  17711. }
  17712. TEST(ParseUrlTest, WebSocketPatterns) {
  17713. {
  17714. detail::UrlComponents uc;
  17715. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17716. EXPECT_EQ("ws", uc.scheme);
  17717. EXPECT_EQ("echo.example.com", uc.host);
  17718. EXPECT_EQ("8080", uc.port);
  17719. EXPECT_EQ("/ws", uc.path);
  17720. }
  17721. {
  17722. detail::UrlComponents uc;
  17723. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17724. EXPECT_EQ("wss", uc.scheme);
  17725. EXPECT_EQ("echo.example.com", uc.host);
  17726. EXPECT_TRUE(uc.port.empty());
  17727. EXPECT_EQ("/ws", uc.path);
  17728. }
  17729. }
  17730. TEST(ParseUrlTest, QueryOnly) {
  17731. detail::UrlComponents uc;
  17732. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17733. EXPECT_TRUE(uc.host.empty());
  17734. EXPECT_TRUE(uc.path.empty());
  17735. EXPECT_EQ("?q=1&r=2", uc.query);
  17736. }
  17737. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17738. detail::UrlComponents uc;
  17739. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17740. EXPECT_TRUE(uc.scheme.empty());
  17741. EXPECT_EQ("example.com", uc.host);
  17742. EXPECT_EQ("443", uc.port);
  17743. EXPECT_EQ("/path", uc.path);
  17744. }
  17745. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17746. // If ipv6 regex working, regex match codepath is taken.
  17747. // else port will default to 80 in Client impl
  17748. int clientImplMagicPort = 80;
  17749. int port = 4321;
  17750. // above ports must be different to avoid false negative
  17751. EXPECT_NE(clientImplMagicPort, port);
  17752. std::string ipV6TestURL = "http://[ff06::c3]";
  17753. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17754. CLIENT_PRIVATE_KEY_FILE);
  17755. EXPECT_EQ(cli.port(), port);
  17756. }
  17757. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17758. auto file_path = "./www/dir/index.html";
  17759. auto dir_path = "./www/dir";
  17760. detail::FileStat stat_file(file_path);
  17761. EXPECT_TRUE(stat_file.is_file());
  17762. EXPECT_FALSE(stat_file.is_dir());
  17763. detail::FileStat stat_dir(dir_path);
  17764. EXPECT_FALSE(stat_dir.is_file());
  17765. EXPECT_TRUE(stat_dir.is_dir());
  17766. }
  17767. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17768. // IPv4 with default HTTP port (80)
  17769. EXPECT_EQ("example.com",
  17770. detail::make_host_and_port_string("example.com", 80, false));
  17771. // IPv4 with default HTTPS port (443)
  17772. EXPECT_EQ("example.com",
  17773. detail::make_host_and_port_string("example.com", 443, true));
  17774. // IPv4 with non-default HTTP port
  17775. EXPECT_EQ("example.com:8080",
  17776. detail::make_host_and_port_string("example.com", 8080, false));
  17777. // IPv4 with non-default HTTPS port
  17778. EXPECT_EQ("example.com:8443",
  17779. detail::make_host_and_port_string("example.com", 8443, true));
  17780. // IPv6 with default HTTP port (80)
  17781. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17782. // IPv6 with default HTTPS port (443)
  17783. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17784. // IPv6 with non-default HTTP port
  17785. EXPECT_EQ("[::1]:8080",
  17786. detail::make_host_and_port_string("::1", 8080, false));
  17787. // IPv6 with non-default HTTPS port
  17788. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17789. // IPv6 full address with default port
  17790. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17791. detail::make_host_and_port_string(
  17792. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17793. // IPv6 full address with non-default port
  17794. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17795. detail::make_host_and_port_string(
  17796. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17797. // IPv6 localhost with non-default port
  17798. EXPECT_EQ("[::1]:3000",
  17799. detail::make_host_and_port_string("::1", 3000, false));
  17800. // IPv6 with zone ID (link-local address) with default port
  17801. EXPECT_EQ("[fe80::1%eth0]",
  17802. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17803. // IPv6 with zone ID (link-local address) with non-default port
  17804. EXPECT_EQ("[fe80::1%eth0]:8080",
  17805. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17806. // Edge case: Port 443 with is_ssl=false (should add port)
  17807. EXPECT_EQ("example.com:443",
  17808. detail::make_host_and_port_string("example.com", 443, false));
  17809. // Edge case: Port 80 with is_ssl=true (should add port)
  17810. EXPECT_EQ("example.com:80",
  17811. detail::make_host_and_port_string("example.com", 80, true));
  17812. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17813. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17814. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17815. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17816. // Security fix: Already bracketed IPv6 should not get double brackets
  17817. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17818. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17819. EXPECT_EQ("[::1]:8080",
  17820. detail::make_host_and_port_string("[::1]", 8080, false));
  17821. EXPECT_EQ("[2001:db8::1]:8080",
  17822. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17823. EXPECT_EQ("[fe80::1%eth0]",
  17824. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17825. EXPECT_EQ("[fe80::1%eth0]:8080",
  17826. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17827. // Edge case: Empty host (should return as-is)
  17828. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17829. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17830. // This is a known limitation but shouldn't crash
  17831. EXPECT_EQ("[host:name]",
  17832. detail::make_host_and_port_string("host:name", 80, false));
  17833. // Port number edge cases (no validation, but should not crash)
  17834. EXPECT_EQ("example.com:0",
  17835. detail::make_host_and_port_string("example.com", 0, false));
  17836. EXPECT_EQ("example.com:-1",
  17837. detail::make_host_and_port_string("example.com", -1, false));
  17838. EXPECT_EQ("example.com:65535",
  17839. detail::make_host_and_port_string("example.com", 65535, false));
  17840. EXPECT_EQ("example.com:65536",
  17841. detail::make_host_and_port_string("example.com", 65536, false));
  17842. }
  17843. #ifdef CPPHTTPLIB_SSL_ENABLED
  17844. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17845. httplib::SSLClient cli("roblox.com", 443);
  17846. cli.set_follow_location(true);
  17847. auto res = cli.Get("/");
  17848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17849. EXPECT_EQ(StatusCode::OK_200, res->status);
  17850. }
  17851. #endif
  17852. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17853. Server svr;
  17854. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17855. EXPECT_EQ(res.status, 400);
  17856. });
  17857. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17858. auto se = detail::scope_exit([&] {
  17859. svr.stop();
  17860. thread.join();
  17861. ASSERT_FALSE(svr.is_running());
  17862. });
  17863. svr.wait_until_ready();
  17864. Client cli(HOST, PORT);
  17865. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17866. }
  17867. TEST(InvalidHeaderCharsTest, is_field_name) {
  17868. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17869. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17870. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17871. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17872. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17873. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17874. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17875. EXPECT_FALSE(detail::fields::is_field_name(""));
  17876. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17877. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17878. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17879. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17880. }
  17881. TEST(InvalidHeaderCharsTest, is_field_value) {
  17882. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17883. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17884. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17885. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17886. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17887. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17888. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17889. EXPECT_TRUE(detail::fields::is_field_value(""));
  17890. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17891. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17892. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17893. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17894. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17895. }
  17896. TEST(InvalidHeaderCharsTest, OnServer) {
  17897. Server svr;
  17898. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17899. std::string header = "Not Set";
  17900. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17901. res.set_header(header, "value");
  17902. res.set_content("Page Content Page Content", "text/plain");
  17903. });
  17904. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17905. std::string header = "Not Set";
  17906. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17907. res.set_header("X-Test", header);
  17908. res.set_content("Page Content Page Content", "text/plain");
  17909. });
  17910. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17911. auto se = detail::scope_exit([&] {
  17912. svr.stop();
  17913. thread.join();
  17914. ASSERT_FALSE(svr.is_running());
  17915. });
  17916. svr.wait_until_ready();
  17917. Client cli(HOST, PORT);
  17918. {
  17919. auto res = cli.Get(
  17920. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17922. EXPECT_EQ("Page Content Page Content", res->body);
  17923. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17924. }
  17925. {
  17926. auto res = cli.Get(
  17927. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17929. EXPECT_EQ("Page Content Page Content", res->body);
  17930. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17931. }
  17932. }
  17933. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17934. auto handled = false;
  17935. Server svr;
  17936. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17937. thread t = thread([&] { svr.listen(HOST, PORT); });
  17938. auto se = detail::scope_exit([&] {
  17939. svr.stop();
  17940. t.join();
  17941. ASSERT_FALSE(svr.is_running());
  17942. ASSERT_FALSE(handled);
  17943. });
  17944. svr.wait_until_ready();
  17945. auto req = "POST /test HTTP/1.1\r\n"
  17946. "Content-Length: x\r\n"
  17947. "\r\n";
  17948. std::string response;
  17949. ASSERT_TRUE(send_request(1, req, &response));
  17950. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17951. response.substr(0, response.find("\r\n")));
  17952. }
  17953. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17954. // case-insensitive, and a server that receives a 100-continue expectation in
  17955. // an HTTP/1.0 request MUST ignore it.
  17956. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17957. std::string response;
  17958. ASSERT_TRUE(send_request(1, req, &response, port));
  17959. *got_100 = response.find("100 Continue") != std::string::npos;
  17960. }
  17961. class ExpectTokenTest : public ::testing::Test {
  17962. protected:
  17963. void SetUp() override {
  17964. svr_.Post("/p", [](const Request &, Response &res) {
  17965. res.set_content("ok", "text/plain");
  17966. });
  17967. port_ = svr_.bind_to_any_port(HOST);
  17968. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17969. svr_.wait_until_ready();
  17970. }
  17971. void TearDown() override {
  17972. svr_.stop();
  17973. if (thread_.joinable()) { thread_.join(); }
  17974. }
  17975. std::string request(const char *version, const char *expect_value) const {
  17976. return std::string("POST /p ") + version +
  17977. "\r\n"
  17978. "Host: localhost\r\n"
  17979. "Content-Length: 2\r\n"
  17980. "Connection: close\r\n"
  17981. "Expect: " +
  17982. expect_value +
  17983. "\r\n"
  17984. "\r\n"
  17985. "hi";
  17986. }
  17987. Server svr_;
  17988. int port_ = 0;
  17989. thread thread_;
  17990. };
  17991. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17992. bool got_100 = false;
  17993. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17994. EXPECT_TRUE(got_100);
  17995. }
  17996. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17997. bool got_100 = true;
  17998. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17999. EXPECT_FALSE(got_100);
  18000. }
  18001. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18002. bool got_100 = false;
  18003. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18004. EXPECT_TRUE(got_100);
  18005. }
  18006. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18007. bool got_100 = false;
  18008. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18009. EXPECT_TRUE(got_100);
  18010. }
  18011. // `100 Continue` is sent only when the server starts reading the body, so a
  18012. // request rejected before that never invites the client to send it. The
  18013. // requests below carry the expectation but withhold the body, as a client
  18014. // waiting for `100 Continue` would.
  18015. // A POST that expects `100 Continue` and withholds its two-byte body.
  18016. static std::string expect_headers_only(const std::string &path) {
  18017. return "POST " + path +
  18018. " HTTP/1.1\r\n"
  18019. "Host: localhost\r\n"
  18020. "Content-Length: 2\r\n"
  18021. "Expect: 100-continue\r\n"
  18022. "\r\n";
  18023. }
  18024. class ExpectLazyContinueTest : public ::testing::Test {
  18025. protected:
  18026. void SetUp() override {
  18027. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18028. if (req.path == "/pre-routing") {
  18029. res.status = StatusCode::Unauthorized_401;
  18030. return Server::HandlerResponse::Handled;
  18031. }
  18032. return Server::HandlerResponse::Unhandled;
  18033. });
  18034. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18035. if (req.matched_route == "/pre-request") {
  18036. res.status = StatusCode::Forbidden_403;
  18037. return Server::HandlerResponse::Handled;
  18038. }
  18039. return Server::HandlerResponse::Unhandled;
  18040. });
  18041. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18042. res.set_content("ok", "text/plain");
  18043. });
  18044. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18045. res.set_content("ok", "text/plain");
  18046. });
  18047. svr_.Post("/reader-used", [](const Request &, Response &res,
  18048. const ContentReader &content_reader) {
  18049. std::string body;
  18050. content_reader([&](const char *data, size_t len) {
  18051. body.append(data, len);
  18052. return true;
  18053. });
  18054. res.set_content(body, "text/plain");
  18055. });
  18056. svr_.Post("/reader-unused",
  18057. [](const Request &, Response &res, const ContentReader &) {
  18058. res.set_content("ignored", "text/plain");
  18059. });
  18060. port_ = svr_.bind_to_any_port(HOST);
  18061. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18062. svr_.wait_until_ready();
  18063. }
  18064. void TearDown() override {
  18065. svr_.stop();
  18066. if (thread_.joinable()) { thread_.join(); }
  18067. }
  18068. // Sends `req` and reads until the server closes the connection. Returns
  18069. // false if the read had to wait for the client-side timeout instead.
  18070. bool send_until_closed(const std::string &req, std::string *resp) const {
  18071. auto start = std::chrono::steady_clock::now();
  18072. if (!send_request(3, req, resp, port_)) { return false; }
  18073. auto elapsed = std::chrono::steady_clock::now() - start;
  18074. return elapsed < std::chrono::seconds(2);
  18075. }
  18076. // The final response comes without `100 Continue`, and the server closes
  18077. // the connection since the body may or may not follow.
  18078. void expect_final_without_interim(const std::string &path,
  18079. const char *status_line) const {
  18080. std::string resp;
  18081. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18082. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18083. EXPECT_EQ(0u, resp.find(status_line));
  18084. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18085. }
  18086. Server svr_;
  18087. int port_ = 0;
  18088. thread thread_;
  18089. };
  18090. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18091. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18092. }
  18093. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18094. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18095. }
  18096. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18097. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18098. }
  18099. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18100. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18101. }
  18102. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18103. // The body follows once `100 Continue` has had time to arrive.
  18104. auto req = expect_headers_only("/reader-used");
  18105. req.insert(req.size() - 2, "Connection: close\r\n");
  18106. std::string resp;
  18107. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18108. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18109. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18110. EXPECT_NE(std::string::npos, resp.find("hi"));
  18111. }
  18112. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18113. // Large enough for the client to add `Expect: 100-continue` itself.
  18114. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18115. std::atomic<bool> body_sent{false};
  18116. Client cli(HOST, port_);
  18117. auto res = cli.Post(
  18118. "/pre-request", length,
  18119. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18120. body_sent = true;
  18121. std::string chunk(len, 'x');
  18122. sink.write(chunk.data(), chunk.size());
  18123. return true;
  18124. },
  18125. "application/octet-stream");
  18126. ASSERT_TRUE(res);
  18127. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18128. EXPECT_FALSE(body_sent);
  18129. }
  18130. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18131. Server svr;
  18132. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18133. return StatusCode::ExpectationFailed_417;
  18134. });
  18135. svr.Post("/p", [](const Request &, Response &res) {
  18136. res.set_content("ok", "text/plain");
  18137. });
  18138. auto port = svr.bind_to_any_port(HOST);
  18139. thread t = thread([&] { svr.listen_after_bind(); });
  18140. auto se = detail::scope_exit([&] {
  18141. svr.stop();
  18142. t.join();
  18143. });
  18144. svr.wait_until_ready();
  18145. std::string resp;
  18146. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18147. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18148. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18149. // Exactly one response: the route handler must not run after the 417.
  18150. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18151. }
  18152. #ifndef _WIN32
  18153. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18154. static constexpr char reject[] = "Unauthorized";
  18155. static constexpr char accept[] = "Upload accepted";
  18156. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18157. Server svr;
  18158. svr.set_expect_100_continue_handler(
  18159. [](const Request & /*req*/, Response &res) {
  18160. res.status = StatusCode::Unauthorized_401;
  18161. res.set_content(reject, "text/plain");
  18162. return res.status;
  18163. });
  18164. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18165. res.set_content(accept, "text/plain");
  18166. });
  18167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18168. auto se = detail::scope_exit([&] {
  18169. svr.stop();
  18170. thread.join();
  18171. ASSERT_FALSE(svr.is_running());
  18172. });
  18173. svr.wait_until_ready();
  18174. {
  18175. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18176. curl_easy_init(), &curl_easy_cleanup};
  18177. ASSERT_NE(curl, nullptr);
  18178. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18179. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18180. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18181. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18182. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18183. &curl_slist_free_all};
  18184. ASSERT_NE(list, nullptr);
  18185. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18186. struct read_data {
  18187. uint64_t read_size;
  18188. uint64_t total_size;
  18189. } data = {0, total_size};
  18190. using read_callback_t =
  18191. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18192. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18193. void *userdata) -> size_t {
  18194. read_data *d = (read_data *)userdata;
  18195. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18196. std::fill_n(ptr, size * nmemb, 'A');
  18197. d->read_size += size * nmemb;
  18198. return size * nmemb;
  18199. };
  18200. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18201. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18202. std::vector<char> buffer;
  18203. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18204. using write_callback_t =
  18205. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18206. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18207. void *userdata) -> size_t {
  18208. std::vector<char> *buf = (std::vector<char> *)userdata;
  18209. buf->reserve(buf->size() + size * nmemb + 1);
  18210. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18211. return size * nmemb;
  18212. };
  18213. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18214. {
  18215. const auto res = curl_easy_perform(curl.get());
  18216. ASSERT_EQ(res, CURLE_OK);
  18217. }
  18218. {
  18219. auto response_code = long{};
  18220. const auto res =
  18221. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18222. ASSERT_EQ(res, CURLE_OK);
  18223. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18224. }
  18225. {
  18226. auto dl = curl_off_t{};
  18227. const auto res =
  18228. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18229. ASSERT_EQ(res, CURLE_OK);
  18230. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18231. }
  18232. {
  18233. buffer.push_back('\0');
  18234. ASSERT_STRCASEEQ(buffer.data(), reject);
  18235. }
  18236. }
  18237. }
  18238. #endif
  18239. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18240. // Regression test for #2458.
  18241. //
  18242. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18243. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18244. // ticket can make the client socket spuriously readable during the
  18245. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18246. // the client withholds the body and then blocks reading a response that never
  18247. // comes, failing with `Failed to read connection`.
  18248. //
  18249. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18250. // within the timeout. This raw OpenSSL server deliberately never sends
  18251. // `100 Continue`; the client must still deliver the body and receive 200.
  18252. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18253. signal(SIGPIPE, SIG_IGN);
  18254. const auto port = PORT + 4;
  18255. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18256. ASSERT_NE(srv, INVALID_SOCKET);
  18257. int opt = 1;
  18258. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18259. sockaddr_in addr{};
  18260. addr.sin_family = AF_INET;
  18261. addr.sin_port = htons(static_cast<uint16_t>(port));
  18262. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18263. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18264. ASSERT_EQ(0, ::listen(srv, 1));
  18265. std::atomic<size_t> server_body_bytes{0};
  18266. auto server_thread = std::thread([&] {
  18267. sockaddr_in cli_addr{};
  18268. socklen_t cli_len = sizeof(cli_addr);
  18269. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18270. if (cli == INVALID_SOCKET) { return; }
  18271. // Bound the lifetime of the server side so a buggy client (which never
  18272. // sends the body) cannot make this thread block forever on join.
  18273. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18274. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18275. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18276. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18277. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18278. SSL *ssl = SSL_new(ctx);
  18279. SSL_set_fd(ssl, static_cast<int>(cli));
  18280. if (SSL_accept(ssl) > 0) {
  18281. // Read the request headers. Reading here also flushes the TLS 1.3
  18282. // session tickets to the client. Deliberately do NOT send
  18283. // `100 Continue`.
  18284. std::string buf;
  18285. char tmp[1024];
  18286. while (buf.find("\r\n\r\n") == std::string::npos) {
  18287. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18288. if (n <= 0) { break; }
  18289. buf.append(tmp, static_cast<size_t>(n));
  18290. }
  18291. // A correct client sends the body now; count what arrives.
  18292. auto pos = buf.find("\r\n\r\n");
  18293. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18294. while (body < 4096) {
  18295. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18296. if (n <= 0) { break; }
  18297. body += static_cast<size_t>(n);
  18298. }
  18299. server_body_bytes = body;
  18300. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18301. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18302. SSL_shutdown(ssl);
  18303. }
  18304. SSL_free(ssl);
  18305. detail::close_socket(cli);
  18306. SSL_CTX_free(ctx);
  18307. });
  18308. auto se = detail::scope_exit([&] {
  18309. server_thread.join();
  18310. detail::close_socket(srv);
  18311. });
  18312. SSLClient cli("127.0.0.1", port);
  18313. cli.enable_server_certificate_verification(false);
  18314. cli.set_connection_timeout(5, 0);
  18315. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18316. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18317. std::string body(4096, 'A');
  18318. auto res = cli.Put("/api/test", body, "application/json");
  18319. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18320. EXPECT_EQ(StatusCode::OK_200, res->status);
  18321. EXPECT_EQ(body.size(), server_body_bytes.load());
  18322. }
  18323. #endif
  18324. template <typename S, typename C>
  18325. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18326. svr.Get("/stream", [&](const Request &, Response &res) {
  18327. auto data = new std::string("01234567890123456789");
  18328. res.set_content_provider(
  18329. data->size(), "text/plain",
  18330. [&, data](size_t offset, size_t length, DataSink &sink) {
  18331. const size_t DATA_CHUNK_SIZE = 4;
  18332. const auto &d = *data;
  18333. std::this_thread::sleep_for(std::chrono::seconds(1));
  18334. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18335. return true;
  18336. },
  18337. [data](bool success) {
  18338. EXPECT_FALSE(success);
  18339. delete data;
  18340. });
  18341. });
  18342. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18343. auto i = new size_t(0);
  18344. res.set_content_provider(
  18345. "text/plain",
  18346. [i](size_t, DataSink &sink) {
  18347. if (*i < 5) {
  18348. std::this_thread::sleep_for(std::chrono::seconds(1));
  18349. sink.write("abcd", 4);
  18350. (*i)++;
  18351. } else {
  18352. sink.done();
  18353. }
  18354. return true;
  18355. },
  18356. [i](bool success) {
  18357. EXPECT_FALSE(success);
  18358. delete i;
  18359. });
  18360. });
  18361. svr.Get("/chunked", [&](const Request &, Response &res) {
  18362. auto i = new size_t(0);
  18363. res.set_chunked_content_provider(
  18364. "text/plain",
  18365. [i](size_t, DataSink &sink) {
  18366. if (*i < 5) {
  18367. std::this_thread::sleep_for(std::chrono::seconds(1));
  18368. sink.os << "abcd";
  18369. (*i)++;
  18370. } else {
  18371. sink.done();
  18372. }
  18373. return true;
  18374. },
  18375. [i](bool success) {
  18376. EXPECT_FALSE(success);
  18377. delete i;
  18378. });
  18379. });
  18380. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18381. auto se = detail::scope_exit([&] {
  18382. svr.stop();
  18383. listen_thread.join();
  18384. ASSERT_FALSE(svr.is_running());
  18385. });
  18386. svr.wait_until_ready();
  18387. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18388. {
  18389. auto start = std::chrono::steady_clock::now();
  18390. auto res = cli.Get("/stream");
  18391. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18392. std::chrono::steady_clock::now() - start)
  18393. .count();
  18394. ASSERT_FALSE(res);
  18395. EXPECT_EQ(Error::Read, res.error());
  18396. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18397. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18398. }
  18399. {
  18400. auto start = std::chrono::steady_clock::now();
  18401. auto res = cli.Get("/stream_without_length");
  18402. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18403. std::chrono::steady_clock::now() - start)
  18404. .count();
  18405. ASSERT_FALSE(res);
  18406. EXPECT_EQ(Error::Read, res.error());
  18407. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18408. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18409. }
  18410. {
  18411. auto start = std::chrono::steady_clock::now();
  18412. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18413. EXPECT_EQ("abcd", string(data, data_length));
  18414. return true;
  18415. });
  18416. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18417. std::chrono::steady_clock::now() - start)
  18418. .count();
  18419. ASSERT_FALSE(res);
  18420. EXPECT_EQ(Error::Read, res.error());
  18421. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18422. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18423. }
  18424. }
  18425. TEST(MaxTimeoutTest, ContentStream) {
  18426. time_t timeout = 2000;
  18427. time_t threshold = 200;
  18428. Server svr;
  18429. Client cli("localhost", PORT);
  18430. max_timeout_test(svr, cli, timeout, threshold);
  18431. }
  18432. #ifdef CPPHTTPLIB_SSL_ENABLED
  18433. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18434. time_t timeout = 2000;
  18435. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18437. SSLClient cli("localhost", PORT);
  18438. cli.enable_server_certificate_verification(false);
  18439. max_timeout_test(svr, cli, timeout, threshold);
  18440. }
  18441. #endif
  18442. class EventDispatcher {
  18443. public:
  18444. EventDispatcher() {}
  18445. bool wait_event(DataSink *sink) {
  18446. unique_lock<mutex> lk(m_);
  18447. int id = id_;
  18448. // Wait with timeout to prevent hanging if client disconnects
  18449. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18450. [&] { return cid_ == id; })) {
  18451. return false; // Timeout occurred
  18452. }
  18453. sink->write(message_.data(), message_.size());
  18454. return true;
  18455. }
  18456. void send_event(const string &message) {
  18457. lock_guard<mutex> lk(m_);
  18458. cid_ = id_++;
  18459. message_ = message;
  18460. cv_.notify_all();
  18461. }
  18462. private:
  18463. mutex m_;
  18464. condition_variable cv_;
  18465. atomic_int id_{0};
  18466. atomic_int cid_{-1};
  18467. string message_;
  18468. };
  18469. TEST(ClientInThreadTest, Issue2068) {
  18470. EventDispatcher ed;
  18471. Server svr;
  18472. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18473. res.set_chunked_content_provider("text/event-stream",
  18474. [&](size_t /*offset*/, DataSink &sink) {
  18475. return ed.wait_event(&sink);
  18476. });
  18477. });
  18478. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18479. svr.wait_until_ready();
  18480. thread event_thread([&] {
  18481. int id = 0;
  18482. while (svr.is_running()) {
  18483. this_thread::sleep_for(chrono::milliseconds(500));
  18484. std::stringstream ss;
  18485. ss << "data: " << id << "\n\n";
  18486. ed.send_event(ss.str());
  18487. id++;
  18488. }
  18489. });
  18490. auto se = detail::scope_exit([&] {
  18491. svr.stop();
  18492. listen_thread.join();
  18493. event_thread.join();
  18494. ASSERT_FALSE(svr.is_running());
  18495. });
  18496. {
  18497. auto client = detail::make_unique<Client>(HOST, PORT);
  18498. client->set_read_timeout(std::chrono::minutes(10));
  18499. std::atomic<bool> stop{false};
  18500. std::thread t([&] {
  18501. client->Get("/event1",
  18502. [&](const char *, size_t) -> bool { return !stop; });
  18503. });
  18504. std::this_thread::sleep_for(std::chrono::seconds(2));
  18505. stop = true;
  18506. client->stop();
  18507. t.join();
  18508. // Reset client after thread has finished
  18509. client.reset();
  18510. }
  18511. }
  18512. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18513. auto handled = false;
  18514. Server svr;
  18515. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18516. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18517. auto se = detail::scope_exit([&] {
  18518. svr.stop();
  18519. t.join();
  18520. ASSERT_FALSE(svr.is_running());
  18521. ASSERT_FALSE(handled);
  18522. });
  18523. svr.wait_until_ready();
  18524. // Two Content-Length headers with different values — must be rejected
  18525. auto req = "POST /test HTTP/1.1\r\n"
  18526. "Content-Length: 5\r\n"
  18527. "Content-Length: 10\r\n"
  18528. "\r\n"
  18529. "hello";
  18530. std::string response;
  18531. ASSERT_TRUE(send_request(1, req, &response));
  18532. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18533. response.substr(0, response.find("\r\n")));
  18534. }
  18535. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18536. auto handled = false;
  18537. Server svr;
  18538. svr.Post("/test", [&](const Request &, Response &res) {
  18539. handled = true;
  18540. res.set_content("ok", "text/plain");
  18541. });
  18542. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18543. auto se = detail::scope_exit([&] {
  18544. svr.stop();
  18545. t.join();
  18546. ASSERT_FALSE(svr.is_running());
  18547. ASSERT_TRUE(handled);
  18548. });
  18549. svr.wait_until_ready();
  18550. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18551. auto req = "POST /test HTTP/1.1\r\n"
  18552. "Host: localhost\r\n"
  18553. "Content-Length: 5\r\n"
  18554. "Content-Length: 5\r\n"
  18555. "\r\n"
  18556. "hello";
  18557. std::string response;
  18558. ASSERT_TRUE(send_request(1, req, &response));
  18559. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18560. }
  18561. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18562. Server svr;
  18563. svr.Get("/test", [](const Request &, Response &res) {
  18564. res.set_content("ok", "text/plain");
  18565. });
  18566. auto port = svr.bind_to_any_port(HOST);
  18567. thread t = thread([&] { svr.listen_after_bind(); });
  18568. auto se = detail::scope_exit([&] {
  18569. svr.stop();
  18570. t.join();
  18571. ASSERT_FALSE(svr.is_running());
  18572. });
  18573. svr.wait_until_ready();
  18574. auto status_line = [&](const std::string &host_lines) {
  18575. std::string res;
  18576. send_request(
  18577. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18578. &res, port);
  18579. return res.substr(0, res.find("\r\n"));
  18580. };
  18581. const char *accepted[] = {
  18582. "Host: localhost\r\n",
  18583. "Host: a.example:8080\r\n",
  18584. "Host: my_service\r\n",
  18585. "Host: [::1]:8080\r\n",
  18586. "Host: [fe80::1%25eth0]\r\n",
  18587. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18588. };
  18589. for (auto host_lines : accepted) {
  18590. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18591. }
  18592. const char *rejected[] = {
  18593. "Host: a.example\r\nHost: b.example\r\n",
  18594. "Host: a.example\r\nHost: a.example\r\n",
  18595. "Host: a@b.example\r\n",
  18596. "Host: a.example/b\r\n",
  18597. "Host: a.example\\b\r\n",
  18598. "Host: a.example?b\r\n",
  18599. "Host: a.example#b\r\n",
  18600. "Host: a.example b.example\r\n",
  18601. };
  18602. for (auto host_lines : rejected) {
  18603. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18604. << host_lines;
  18605. }
  18606. }
  18607. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18608. Server svr;
  18609. svr.Get("/", [](const Request &req, Response &res) {
  18610. EXPECT_EQ(2U, req.trailers.size());
  18611. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18612. // Denied
  18613. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18614. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18615. // Accepted
  18616. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18617. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18618. EXPECT_TRUE(req.has_trailer("X-World"));
  18619. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18620. res.set_content("ok", "text/plain");
  18621. });
  18622. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18623. auto se = detail::scope_exit([&] {
  18624. svr.stop();
  18625. t.join();
  18626. ASSERT_FALSE(svr.is_running());
  18627. });
  18628. svr.wait_until_ready();
  18629. const std::string req = "GET / HTTP/1.1\r\n"
  18630. "Transfer-Encoding: chunked\r\n"
  18631. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18632. "\r\n"
  18633. "0\r\n"
  18634. "Content-Length: 10\r\n"
  18635. "Host: internal.local\r\n"
  18636. "Content-Type: malicious/content\r\n"
  18637. "Cookie: any\r\n"
  18638. "Set-Cookie: any\r\n"
  18639. "X-Forwarded-For: attacker.com\r\n"
  18640. "X-Real-Ip: 1.1.1.1\r\n"
  18641. "X-Hello: hello\r\n"
  18642. "X-World: world\r\n"
  18643. "\r\n";
  18644. std::string res;
  18645. ASSERT_TRUE(send_request(1, req, &res));
  18646. }
  18647. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18648. // several field lines, and the combined value is what has to be parsed. A
  18649. // Trailer field split across lines therefore declares every name it lists;
  18650. // reading only the first line silently drops the trailers the later lines
  18651. // declare. The prohibited-trailer filter still applies to every line.
  18652. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18653. Server svr;
  18654. size_t observed_trailer_count = 0;
  18655. std::string observed_hello;
  18656. std::string observed_world;
  18657. bool observed_content_length = true;
  18658. svr.Get("/", [&](const Request &req, Response &res) {
  18659. observed_trailer_count = req.trailers.size();
  18660. observed_hello = req.get_trailer_value("X-Hello");
  18661. observed_world = req.get_trailer_value("X-World");
  18662. observed_content_length = req.has_trailer("Content-Length");
  18663. res.set_content("ok", "text/plain");
  18664. });
  18665. auto port = svr.bind_to_any_port(HOST);
  18666. thread t = thread([&]() { svr.listen_after_bind(); });
  18667. auto se = detail::scope_exit([&] {
  18668. svr.stop();
  18669. t.join();
  18670. ASSERT_FALSE(svr.is_running());
  18671. });
  18672. svr.wait_until_ready();
  18673. const std::string req = "GET / HTTP/1.1\r\n"
  18674. "Host: localhost\r\n"
  18675. "Transfer-Encoding: chunked\r\n"
  18676. "Trailer: X-Hello\r\n"
  18677. "Trailer: X-World, Content-Length\r\n"
  18678. "\r\n"
  18679. "0\r\n"
  18680. "X-Hello: hello\r\n"
  18681. "X-World: world\r\n"
  18682. "Content-Length: 10\r\n"
  18683. "\r\n";
  18684. std::string res;
  18685. ASSERT_TRUE(send_request(1, req, &res, port));
  18686. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18687. // Accepted: both field lines contribute to the declared set
  18688. EXPECT_EQ(2U, observed_trailer_count);
  18689. EXPECT_EQ(observed_hello, "hello");
  18690. EXPECT_EQ(observed_world, "world");
  18691. // Denied: a prohibited name stays prohibited on a later field line
  18692. EXPECT_FALSE(observed_content_length);
  18693. }
  18694. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18695. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18696. // unbounded run of fields that are never declared, because the counter would
  18697. // only advance for declared fields.
  18698. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18699. Server svr;
  18700. bool handler_called = false;
  18701. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18702. handler_called = true;
  18703. res.set_content("ok", "text/plain");
  18704. });
  18705. auto port = svr.bind_to_any_port(HOST);
  18706. thread t = thread([&]() { svr.listen_after_bind(); });
  18707. auto se = detail::scope_exit([&] {
  18708. svr.stop();
  18709. t.join();
  18710. ASSERT_FALSE(svr.is_running());
  18711. });
  18712. svr.wait_until_ready();
  18713. // Declare nothing, then send far more undeclared trailer fields than the
  18714. // header-count limit. Parsing must stop and reject the request rather than
  18715. // read every line.
  18716. std::string req = "GET / HTTP/1.1\r\n"
  18717. "Transfer-Encoding: chunked\r\n"
  18718. "\r\n"
  18719. "0\r\n";
  18720. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18721. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18722. }
  18723. req += "\r\n";
  18724. std::string res;
  18725. ASSERT_TRUE(send_request(1, req, &res, port));
  18726. // The request is rejected before the handler runs.
  18727. EXPECT_FALSE(handler_called);
  18728. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18729. }
  18730. // The set of declared trailer names is capped so a peer cannot grow it without
  18731. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18732. // declared past the cap is not honored, even if the field is actually sent.
  18733. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18734. Server svr;
  18735. // One name inside the cap and one past it, so the test tracks the cap rather
  18736. // than a fixed count.
  18737. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18738. const std::string within_cap_name = "X-T-0";
  18739. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18740. bool observed_within_cap = false;
  18741. bool observed_past_cap = false;
  18742. svr.Get("/", [&](const Request &req, Response &res) {
  18743. observed_within_cap = req.has_trailer(within_cap_name);
  18744. observed_past_cap = req.has_trailer(past_cap_name);
  18745. res.set_content("ok", "text/plain");
  18746. });
  18747. auto port = svr.bind_to_any_port(HOST);
  18748. thread t = thread([&]() { svr.listen_after_bind(); });
  18749. auto se = detail::scope_exit([&] {
  18750. svr.stop();
  18751. t.join();
  18752. ASSERT_FALSE(svr.is_running());
  18753. });
  18754. svr.wait_until_ready();
  18755. // Declare more trailer names than the cap in a single Trailer field, then
  18756. // actually send the first (within the cap) and the last (past it).
  18757. std::string trailer_decl = "Trailer: ";
  18758. for (int i = 0; i < declared_count; i++) {
  18759. if (i != 0) { trailer_decl += ", "; }
  18760. trailer_decl += "X-T-" + std::to_string(i);
  18761. }
  18762. trailer_decl += "\r\n";
  18763. const std::string req = "GET / HTTP/1.1\r\n"
  18764. "Host: localhost\r\n"
  18765. "Transfer-Encoding: chunked\r\n" +
  18766. trailer_decl +
  18767. "\r\n"
  18768. "0\r\n" +
  18769. within_cap_name + ": a\r\n" + past_cap_name +
  18770. ": b\r\n"
  18771. "\r\n";
  18772. std::string res;
  18773. ASSERT_TRUE(send_request(1, req, &res, port));
  18774. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18775. // A name within the cap is honored; one declared past the cap is dropped.
  18776. EXPECT_TRUE(observed_within_cap);
  18777. EXPECT_FALSE(observed_past_cap);
  18778. }
  18779. // A direct client that is not listed in trusted_proxies must not be able to
  18780. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18781. // the peer address on the actual TCP connection determines whether the
  18782. // header is honored.
  18783. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18784. Server svr;
  18785. // Deliberately does NOT include the loopback address the test client
  18786. // actually connects from, so the direct connection is not a trusted proxy.
  18787. svr.set_trusted_proxies({"203.0.113.66"});
  18788. std::string observed_remote_addr;
  18789. svr.Get("/ip", [&](const Request &req, Response &res) {
  18790. observed_remote_addr = req.remote_addr;
  18791. res.set_content("ok", "text/plain");
  18792. });
  18793. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18794. auto se = detail::scope_exit([&] {
  18795. svr.stop();
  18796. t.join();
  18797. ASSERT_FALSE(svr.is_running());
  18798. });
  18799. svr.wait_until_ready();
  18800. Client cli(HOST, PORT);
  18801. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18803. EXPECT_EQ(StatusCode::OK_200, res->status);
  18804. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18805. // ignored entirely and the real connection-level address retained.
  18806. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18807. observed_remote_addr == "127.0.0.1");
  18808. }
  18809. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18810. Server svr;
  18811. std::string observed_remote_addr;
  18812. std::string observed_xff;
  18813. svr.Get("/ip", [&](const Request &req, Response &res) {
  18814. observed_remote_addr = req.remote_addr;
  18815. observed_xff = req.get_header_value("X-Forwarded-For");
  18816. res.set_content("ok", "text/plain");
  18817. });
  18818. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18819. auto se = detail::scope_exit([&] {
  18820. svr.stop();
  18821. t.join();
  18822. ASSERT_FALSE(svr.is_running());
  18823. });
  18824. svr.wait_until_ready();
  18825. Client cli(HOST, PORT);
  18826. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18828. EXPECT_EQ(StatusCode::OK_200, res->status);
  18829. EXPECT_EQ(observed_xff, "203.0.113.66");
  18830. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18831. observed_remote_addr == "127.0.0.1");
  18832. }
  18833. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18834. Server svr;
  18835. svr.set_trusted_proxies({"203.0.113.66"});
  18836. std::string observed_remote_addr;
  18837. std::string observed_xff;
  18838. svr.Get("/ip", [&](const Request &req, Response &res) {
  18839. observed_remote_addr = req.remote_addr;
  18840. observed_xff = req.get_header_value("X-Forwarded-For");
  18841. res.set_content("ok", "text/plain");
  18842. });
  18843. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18844. auto se = detail::scope_exit([&] {
  18845. svr.stop();
  18846. t.join();
  18847. ASSERT_FALSE(svr.is_running());
  18848. });
  18849. svr.wait_until_ready();
  18850. Client cli(HOST, PORT);
  18851. auto res = cli.Get("/ip");
  18852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18853. EXPECT_EQ(StatusCode::OK_200, res->status);
  18854. EXPECT_EQ(observed_xff, "");
  18855. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18856. observed_remote_addr == "127.0.0.1");
  18857. }
  18858. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18859. Server svr;
  18860. // Include the loopback address the test client actually connects from, so
  18861. // the direct connection itself is recognized as the trusted proxy hop.
  18862. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18863. std::string observed_remote_addr;
  18864. std::string observed_xff;
  18865. svr.Get("/ip", [&](const Request &req, Response &res) {
  18866. observed_remote_addr = req.remote_addr;
  18867. observed_xff = req.get_header_value("X-Forwarded-For");
  18868. res.set_content("ok", "text/plain");
  18869. });
  18870. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18871. auto se = detail::scope_exit([&] {
  18872. svr.stop();
  18873. t.join();
  18874. ASSERT_FALSE(svr.is_running());
  18875. });
  18876. svr.wait_until_ready();
  18877. Client cli(HOST, PORT);
  18878. auto res = cli.Get(
  18879. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18881. EXPECT_EQ(StatusCode::OK_200, res->status);
  18882. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18883. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18884. }
  18885. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18886. Server svr;
  18887. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18888. std::string observed_remote_addr;
  18889. std::string observed_xff;
  18890. svr.Get("/ip", [&](const Request &req, Response &res) {
  18891. observed_remote_addr = req.remote_addr;
  18892. observed_xff = req.get_header_value("X-Forwarded-For");
  18893. res.set_content("ok", "text/plain");
  18894. });
  18895. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18896. auto se = detail::scope_exit([&] {
  18897. svr.stop();
  18898. t.join();
  18899. ASSERT_FALSE(svr.is_running());
  18900. });
  18901. svr.wait_until_ready();
  18902. Client cli(HOST, PORT);
  18903. auto res = cli.Get(
  18904. "/ip",
  18905. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18907. EXPECT_EQ(StatusCode::OK_200, res->status);
  18908. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18909. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18910. }
  18911. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18912. Server svr;
  18913. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18914. std::string observed_remote_addr;
  18915. std::string observed_xff;
  18916. svr.Get("/ip", [&](const Request &req, Response &res) {
  18917. observed_remote_addr = req.remote_addr;
  18918. observed_xff = req.get_header_value("X-Forwarded-For");
  18919. res.set_content("ok", "text/plain");
  18920. });
  18921. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18922. auto se = detail::scope_exit([&] {
  18923. svr.stop();
  18924. t.join();
  18925. ASSERT_FALSE(svr.is_running());
  18926. });
  18927. svr.wait_until_ready();
  18928. Client cli(HOST, PORT);
  18929. auto res = cli.Get(
  18930. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18932. EXPECT_EQ(StatusCode::OK_200, res->status);
  18933. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18934. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18935. // and must not be selected.
  18936. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18937. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18938. }
  18939. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18940. Server svr;
  18941. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18942. std::string observed_remote_addr;
  18943. svr.Get("/ip", [&](const Request &req, Response &res) {
  18944. observed_remote_addr = req.remote_addr;
  18945. res.set_content("ok", "text/plain");
  18946. });
  18947. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18948. auto se = detail::scope_exit([&] {
  18949. svr.stop();
  18950. t.join();
  18951. ASSERT_FALSE(svr.is_running());
  18952. });
  18953. svr.wait_until_ready();
  18954. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18955. // a forged address and the trusted proxy's own address; the forged value must
  18956. // not win over the address the trusted proxy actually recorded.
  18957. Client cli(HOST, PORT);
  18958. auto res = cli.Get(
  18959. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18961. EXPECT_EQ(StatusCode::OK_200, res->status);
  18962. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18963. }
  18964. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18965. Server svr;
  18966. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18967. std::string observed_remote_addr;
  18968. std::string observed_xff;
  18969. svr.Get("/ip", [&](const Request &req, Response &res) {
  18970. observed_remote_addr = req.remote_addr;
  18971. observed_xff = req.get_header_value("X-Forwarded-For");
  18972. res.set_content("ok", "text/plain");
  18973. });
  18974. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18975. auto se = detail::scope_exit([&] {
  18976. svr.stop();
  18977. t.join();
  18978. ASSERT_FALSE(svr.is_running());
  18979. });
  18980. svr.wait_until_ready();
  18981. Client cli(HOST, PORT);
  18982. auto res = cli.Get(
  18983. "/ip",
  18984. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18986. EXPECT_EQ(StatusCode::OK_200, res->status);
  18987. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18988. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18989. }
  18990. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18991. Server svr;
  18992. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18993. std::string observed_remote_addr;
  18994. std::string observed_xff;
  18995. svr.Get("/ip", [&](const Request &req, Response &res) {
  18996. observed_remote_addr = req.remote_addr;
  18997. observed_xff = req.get_header_value("X-Forwarded-For");
  18998. res.set_content("ok", "text/plain");
  18999. });
  19000. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19001. auto se = detail::scope_exit([&] {
  19002. svr.stop();
  19003. t.join();
  19004. ASSERT_FALSE(svr.is_running());
  19005. });
  19006. svr.wait_until_ready();
  19007. std::string raw_req =
  19008. "GET /ip HTTP/1.1\r\n"
  19009. "Host: localhost\r\n"
  19010. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19011. "Connection: close\r\n"
  19012. "\r\n";
  19013. std::string out;
  19014. ASSERT_TRUE(send_request(5, raw_req, &out));
  19015. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19016. // Header parser trims surrounding whitespace of the header value
  19017. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19018. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19019. }
  19020. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19021. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19022. // their own X-Forwarded-For as a separate field line rather than extending the
  19023. // one the client sent, so every occurrence has to be taken into account.
  19024. // Reading only the first one hands back the address the client chose.
  19025. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19026. Server svr;
  19027. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19028. std::string observed_remote_addr;
  19029. size_t observed_xff_count = 0;
  19030. svr.Get("/ip", [&](const Request &req, Response &res) {
  19031. observed_remote_addr = req.remote_addr;
  19032. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19033. res.set_content("ok", "text/plain");
  19034. });
  19035. auto port = svr.bind_to_any_port(HOST);
  19036. thread t = thread([&]() { svr.listen_after_bind(); });
  19037. auto se = detail::scope_exit([&] {
  19038. svr.stop();
  19039. t.join();
  19040. ASSERT_FALSE(svr.is_running());
  19041. });
  19042. svr.wait_until_ready();
  19043. // The client supplies the first field line; the trusted proxy appends the
  19044. // address it observed as a second one.
  19045. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19046. "Host: localhost\r\n"
  19047. "X-Forwarded-For: 1.2.3.4\r\n"
  19048. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19049. "Connection: close\r\n"
  19050. "\r\n";
  19051. std::string out;
  19052. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19053. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19054. EXPECT_EQ(observed_xff_count, 2U);
  19055. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19056. // The same chain spread over one field line per hop derives the same client
  19057. // address, i.e. the split and the comma-joined representations agree.
  19058. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19059. "Host: localhost\r\n"
  19060. "X-Forwarded-For: 1.2.3.4\r\n"
  19061. "X-Forwarded-For: 198.51.100.23\r\n"
  19062. "X-Forwarded-For: 192.0.2.45\r\n"
  19063. "Connection: close\r\n"
  19064. "\r\n";
  19065. out.clear();
  19066. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19067. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19068. EXPECT_EQ(observed_xff_count, 3U);
  19069. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19070. }
  19071. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19072. // crash the server (it used to call front() on an empty vector inside
  19073. // get_client_ip). The connection-level remote address must be retained instead.
  19074. static void run_malformed_xff_test(const std::string &xff_value) {
  19075. Server svr;
  19076. svr.set_trusted_proxies({"192.0.2.45"});
  19077. std::string observed_remote_addr;
  19078. svr.Get("/ip", [&](const Request &req, Response &res) {
  19079. observed_remote_addr = req.remote_addr;
  19080. res.set_content("ok", "text/plain");
  19081. });
  19082. int port = 0;
  19083. thread t = thread([&]() {
  19084. port = svr.bind_to_any_port(HOST);
  19085. svr.listen_after_bind();
  19086. });
  19087. auto se = detail::scope_exit([&] {
  19088. svr.stop();
  19089. t.join();
  19090. ASSERT_FALSE(svr.is_running());
  19091. });
  19092. svr.wait_until_ready();
  19093. Client cli(HOST, port);
  19094. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19096. EXPECT_EQ(StatusCode::OK_200, res->status);
  19097. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19098. observed_remote_addr == "127.0.0.1");
  19099. }
  19100. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19101. run_malformed_xff_test("");
  19102. }
  19103. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19104. run_malformed_xff_test(",");
  19105. }
  19106. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19107. run_malformed_xff_test(", , ,");
  19108. }
  19109. // The same rule applies to Accept: a request whose acceptable types are spread
  19110. // over several field lines must be negotiated against all of them.
  19111. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19112. // case-insensitive connection options. Comparing the whole field value against
  19113. // one option misses a client that sends several of them, and misses every
  19114. // casing but the one written in the comparison.
  19115. //
  19116. // Sends req, reads the response, then reuses the same socket for a second
  19117. // request to find out whether the server kept the connection.
  19118. static void probe_connection_reuse(int port, const std::string &req,
  19119. bool *announced_close, bool *reusable) {
  19120. auto error = Error::Success;
  19121. auto sock = detail::create_client_socket(
  19122. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19123. /*connection_timeout_sec=*/5, 0,
  19124. /*read_timeout_sec=*/1, 0,
  19125. /*write_timeout_sec=*/5, 0, std::string(), error);
  19126. ASSERT_NE(sock, INVALID_SOCKET);
  19127. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19128. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19129. "Host: localhost\r\n"
  19130. "Connection: close\r\n"
  19131. "\r\n";
  19132. std::string first_response;
  19133. std::string second_response;
  19134. detail::process_client_socket(
  19135. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19136. [&](Stream &strm) {
  19137. if (strm.write(req.data(), req.size()) !=
  19138. static_cast<ssize_t>(req.size())) {
  19139. return false;
  19140. }
  19141. char buf[512];
  19142. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19143. // Headers plus the two-byte body of the handler below
  19144. while (reader.getline()) {
  19145. first_response += reader.ptr();
  19146. if (first_response.find("ok") != std::string::npos) { break; }
  19147. }
  19148. if (strm.write(second.data(), second.size()) !=
  19149. static_cast<ssize_t>(second.size())) {
  19150. return true;
  19151. }
  19152. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19153. while (reader2.getline()) {
  19154. second_response += reader2.ptr();
  19155. if (second_response.find("ok") != std::string::npos) { break; }
  19156. }
  19157. return true;
  19158. });
  19159. *announced_close =
  19160. first_response.find("Connection: close") != std::string::npos;
  19161. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19162. }
  19163. class ConnectionTokenTest : public ::testing::Test {
  19164. protected:
  19165. void SetUp() override {
  19166. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19167. res.set_content("ok", "text/plain");
  19168. });
  19169. port_ = svr_.bind_to_any_port(HOST);
  19170. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19171. svr_.wait_until_ready();
  19172. }
  19173. void TearDown() override {
  19174. svr_.stop();
  19175. if (thread_.joinable()) { thread_.join(); }
  19176. }
  19177. Server svr_;
  19178. int port_ = 0;
  19179. thread thread_;
  19180. };
  19181. // "close" alongside another option still closes the connection, and the
  19182. // response says so rather than leaving the peer to discover it.
  19183. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19184. bool announced_close = false;
  19185. bool reusable = true;
  19186. probe_connection_reuse(port_,
  19187. "GET /keepalive HTTP/1.1\r\n"
  19188. "Host: localhost\r\n"
  19189. "Connection: keep-alive, close\r\n"
  19190. "\r\n",
  19191. &announced_close, &reusable);
  19192. EXPECT_TRUE(announced_close);
  19193. EXPECT_FALSE(reusable);
  19194. }
  19195. // "close" split over two field lines is the same list, so it is honored too.
  19196. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19197. bool announced_close = false;
  19198. bool reusable = true;
  19199. probe_connection_reuse(port_,
  19200. "GET /keepalive HTTP/1.1\r\n"
  19201. "Host: localhost\r\n"
  19202. "Connection: keep-alive\r\n"
  19203. "Connection: close\r\n"
  19204. "\r\n",
  19205. &announced_close, &reusable);
  19206. EXPECT_TRUE(announced_close);
  19207. EXPECT_FALSE(reusable);
  19208. }
  19209. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19210. // keep-alive in the spelling everyone actually sends keeps its connection.
  19211. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19212. bool announced_close = false;
  19213. bool reusable = false;
  19214. probe_connection_reuse(port_,
  19215. "GET /keepalive HTTP/1.0\r\n"
  19216. "Host: localhost\r\n"
  19217. "Connection: keep-alive\r\n"
  19218. "\r\n",
  19219. &announced_close, &reusable);
  19220. EXPECT_FALSE(announced_close);
  19221. EXPECT_TRUE(reusable);
  19222. }
  19223. // A token the value merely contains is not the token itself.
  19224. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19225. bool announced_close = false;
  19226. bool reusable = false;
  19227. probe_connection_reuse(port_,
  19228. "GET /keepalive HTTP/1.1\r\n"
  19229. "Host: localhost\r\n"
  19230. "Connection: notclose\r\n"
  19231. "\r\n",
  19232. &announced_close, &reusable);
  19233. EXPECT_FALSE(announced_close);
  19234. EXPECT_TRUE(reusable);
  19235. }
  19236. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19237. Server svr;
  19238. std::vector<std::string> observed_types;
  19239. svr.Get("/", [&](const Request &req, Response &res) {
  19240. observed_types = req.accept_content_types;
  19241. res.set_content("ok", "text/plain");
  19242. });
  19243. auto port = svr.bind_to_any_port(HOST);
  19244. thread t = thread([&]() { svr.listen_after_bind(); });
  19245. auto se = detail::scope_exit([&] {
  19246. svr.stop();
  19247. t.join();
  19248. ASSERT_FALSE(svr.is_running());
  19249. });
  19250. svr.wait_until_ready();
  19251. Client cli(HOST, port);
  19252. Headers headers;
  19253. headers.emplace("Accept", "text/plain;q=0.5");
  19254. headers.emplace("Accept", "application/json");
  19255. auto res = cli.Get("/", headers);
  19256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19257. EXPECT_EQ(StatusCode::OK_200, res->status);
  19258. // Sorted by q-value, so the second field line's type comes first
  19259. ASSERT_EQ(2U, observed_types.size());
  19260. EXPECT_EQ("application/json", observed_types[0]);
  19261. EXPECT_EQ("text/plain", observed_types[1]);
  19262. }
  19263. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19264. // empty field line must not contribute a bare comma to the combined value.
  19265. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19266. Server svr;
  19267. std::vector<std::string> observed_types;
  19268. svr.Get("/", [&](const Request &req, Response &res) {
  19269. observed_types = req.accept_content_types;
  19270. res.set_content("ok", "text/plain");
  19271. });
  19272. auto port = svr.bind_to_any_port(HOST);
  19273. thread t = thread([&]() { svr.listen_after_bind(); });
  19274. auto se = detail::scope_exit([&] {
  19275. svr.stop();
  19276. t.join();
  19277. ASSERT_FALSE(svr.is_running());
  19278. });
  19279. svr.wait_until_ready();
  19280. // Empty first field line, then a real one
  19281. std::string raw_req = "GET / HTTP/1.1\r\n"
  19282. "Host: localhost\r\n"
  19283. "Accept:\r\n"
  19284. "Accept: application/json\r\n"
  19285. "Connection: close\r\n"
  19286. "\r\n";
  19287. std::string out;
  19288. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19289. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19290. ASSERT_EQ(1U, observed_types.size());
  19291. EXPECT_EQ("application/json", observed_types[0]);
  19292. }
  19293. // The skip in get_combined_header_value() is what keeps an empty field line
  19294. // from contributing a bare comma. Only a trailing empty field line exercises
  19295. // it: a leading one is already covered by the "combined is still empty" check,
  19296. // and parse_accept_header() now ignores the empty element either way, so the
  19297. // request-level test above can no longer tell the two apart.
  19298. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19299. Headers headers;
  19300. headers.emplace("Accept", "text/html");
  19301. headers.emplace("Accept", "");
  19302. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19303. headers.clear();
  19304. headers.emplace("Accept", "");
  19305. headers.emplace("Accept", "application/json");
  19306. EXPECT_EQ("application/json",
  19307. detail::get_combined_header_value(headers, "Accept"));
  19308. }
  19309. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19310. // An encoding offered on a later Accept-Encoding field line is still offered.
  19311. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19312. Server svr;
  19313. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19314. res.set_content(std::string(1024, 'x'), "text/plain");
  19315. });
  19316. auto port = svr.bind_to_any_port(HOST);
  19317. thread t = thread([&]() { svr.listen_after_bind(); });
  19318. auto se = detail::scope_exit([&] {
  19319. svr.stop();
  19320. t.join();
  19321. ASSERT_FALSE(svr.is_running());
  19322. });
  19323. svr.wait_until_ready();
  19324. Client cli(HOST, port);
  19325. cli.set_decompress(false);
  19326. Headers headers;
  19327. headers.emplace("Accept-Encoding", "identity");
  19328. headers.emplace("Accept-Encoding", "gzip");
  19329. auto res = cli.Get("/", headers);
  19330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19331. EXPECT_EQ(StatusCode::OK_200, res->status);
  19332. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19333. }
  19334. #endif
  19335. #ifndef _WIN32
  19336. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19337. Server svr;
  19338. svr.Post("/post", [&](const Request &req, Response &res) {
  19339. res.set_content(req.body, "text/plain");
  19340. });
  19341. svr.Put("/put", [&](const Request &req, Response &res) {
  19342. res.set_content(req.body, "text/plain");
  19343. });
  19344. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19345. res.set_content(req.body, "text/plain");
  19346. });
  19347. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19348. res.set_content(req.body, "text/plain");
  19349. });
  19350. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19351. auto se = detail::scope_exit([&] {
  19352. svr.stop();
  19353. t.join();
  19354. ASSERT_FALSE(svr.is_running());
  19355. });
  19356. svr.wait_until_ready();
  19357. std::string resp;
  19358. // POST without Content-Length
  19359. ASSERT_TRUE(send_request(5,
  19360. "POST /post HTTP/1.1\r\n"
  19361. "Host: localhost\r\n"
  19362. "Connection: close\r\n"
  19363. "\r\n",
  19364. &resp));
  19365. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19366. // PUT without Content-Length
  19367. resp.clear();
  19368. ASSERT_TRUE(send_request(5,
  19369. "PUT /put HTTP/1.1\r\n"
  19370. "Host: localhost\r\n"
  19371. "Connection: close\r\n"
  19372. "\r\n",
  19373. &resp));
  19374. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19375. // PATCH without Content-Length
  19376. resp.clear();
  19377. ASSERT_TRUE(send_request(5,
  19378. "PATCH /patch HTTP/1.1\r\n"
  19379. "Host: localhost\r\n"
  19380. "Connection: close\r\n"
  19381. "\r\n",
  19382. &resp));
  19383. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19384. // DELETE without Content-Length
  19385. resp.clear();
  19386. ASSERT_TRUE(send_request(5,
  19387. "DELETE /delete HTTP/1.1\r\n"
  19388. "Host: localhost\r\n"
  19389. "Connection: close\r\n"
  19390. "\r\n",
  19391. &resp));
  19392. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19393. }
  19394. #endif
  19395. //==============================================================================
  19396. // open_stream() Tests
  19397. //==============================================================================
  19398. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19399. std::string result;
  19400. char buf[8192];
  19401. ssize_t n;
  19402. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19403. result.append(buf, static_cast<size_t>(n));
  19404. }
  19405. return result;
  19406. }
  19407. // Mock stream for unit tests
  19408. class MockStream : public Stream {
  19409. public:
  19410. std::string data;
  19411. size_t pos = 0;
  19412. ssize_t error_after = -1; // -1 = no error
  19413. explicit MockStream(const std::string &d, ssize_t err = -1)
  19414. : data(d), error_after(err) {}
  19415. bool is_readable() const override { return true; }
  19416. bool wait_readable() const override { return true; }
  19417. bool wait_writable() const override { return true; }
  19418. ssize_t read(char *ptr, size_t size) override {
  19419. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19420. if (pos >= data.size()) return 0;
  19421. size_t limit =
  19422. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19423. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19424. std::memcpy(ptr, data.data() + pos, to_read);
  19425. pos += to_read;
  19426. return static_cast<ssize_t>(to_read);
  19427. }
  19428. ssize_t write(const char *, size_t) override { return -1; }
  19429. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19430. ip = "127.0.0.1";
  19431. port = 0;
  19432. }
  19433. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19434. ip = "127.0.0.1";
  19435. port = 0;
  19436. }
  19437. socket_t socket() const override { return INVALID_SOCKET; }
  19438. time_t duration() const override { return 0; }
  19439. };
  19440. TEST(StreamHandleTest, Basic) {
  19441. ClientImpl::StreamHandle handle;
  19442. EXPECT_FALSE(handle.is_valid());
  19443. handle.response = detail::make_unique<Response>();
  19444. handle.error = Error::Connection;
  19445. EXPECT_FALSE(handle.is_valid());
  19446. handle.error = Error::Success;
  19447. EXPECT_TRUE(handle.is_valid());
  19448. }
  19449. TEST(BodyReaderTest, Basic) {
  19450. MockStream stream("Hello, World!");
  19451. detail::BodyReader reader;
  19452. reader.stream = &stream;
  19453. reader.content_length = 13;
  19454. char buf[32];
  19455. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19456. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19457. EXPECT_TRUE(reader.eof);
  19458. }
  19459. TEST(BodyReaderTest, NoStream) {
  19460. detail::BodyReader reader;
  19461. char buf[32];
  19462. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19463. EXPECT_EQ(Error::Connection, reader.last_error);
  19464. }
  19465. TEST(BodyReaderTest, Error) {
  19466. MockStream stream("Hello, World!", 5);
  19467. detail::BodyReader reader;
  19468. reader.stream = &stream;
  19469. reader.content_length = 13;
  19470. char buf[32];
  19471. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19472. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19473. EXPECT_EQ(Error::Read, reader.last_error);
  19474. }
  19475. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19476. // Mock-based StreamHandle tests relying on private internals are removed.
  19477. class OpenStreamTest : public ::testing::Test {
  19478. protected:
  19479. void SetUp() override {
  19480. svr_.Get("/hello", [](const Request &, Response &res) {
  19481. res.set_content("Hello World!", "text/plain");
  19482. });
  19483. svr_.Get("/large", [](const Request &, Response &res) {
  19484. res.set_content(std::string(10000, 'X'), "text/plain");
  19485. });
  19486. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19487. res.set_content("Hello World!", "image/jpeg");
  19488. res.set_header("Content-Encoding", "UTF-8");
  19489. });
  19490. svr_.Get("/chunked", [](const Request &, Response &res) {
  19491. res.set_chunked_content_provider("text/plain",
  19492. [](size_t offset, DataSink &sink) {
  19493. if (offset < 15) {
  19494. sink.write("chunk", 5);
  19495. return true;
  19496. }
  19497. sink.done();
  19498. return true;
  19499. });
  19500. });
  19501. svr_.Get("/compressible", [](const Request &, Response &res) {
  19502. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19503. DataSink &sink) {
  19504. if (offset < 100 * 1024) {
  19505. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19506. sink.write(chunk.data(), chunk.size());
  19507. return true;
  19508. }
  19509. sink.done();
  19510. return true;
  19511. });
  19512. });
  19513. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19514. [](const Request & /*req*/, Response &res) {
  19515. auto i = new int(0);
  19516. res.set_header("Trailer", "Content-Length, X-Allowed");
  19517. res.set_chunked_content_provider(
  19518. "text/plain",
  19519. [i](size_t /*offset*/, DataSink &sink) {
  19520. switch (*i) {
  19521. case 0: sink.os << "123"; break;
  19522. case 1: sink.os << "456"; break;
  19523. case 2: sink.os << "789"; break;
  19524. case 3: {
  19525. sink.done_with_trailer(
  19526. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19527. } break;
  19528. }
  19529. (*i)++;
  19530. return true;
  19531. },
  19532. [i](bool success) {
  19533. EXPECT_TRUE(success);
  19534. delete i;
  19535. });
  19536. });
  19537. // Echo headers endpoint for header-related tests
  19538. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19539. std::string body;
  19540. for (const auto &h : req.headers) {
  19541. body.append(h.first);
  19542. body.push_back(':');
  19543. body.append(h.second);
  19544. body.push_back('\n');
  19545. }
  19546. res.set_content(body, "text/plain");
  19547. });
  19548. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19549. std::string body;
  19550. for (const auto &h : req.headers) {
  19551. body.append(h.first);
  19552. body.push_back(':');
  19553. body.append(h.second);
  19554. body.push_back('\n');
  19555. }
  19556. res.set_content(body, "text/plain");
  19557. });
  19558. port_ = svr_.bind_to_any_port("127.0.0.1");
  19559. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19560. svr_.wait_until_ready();
  19561. }
  19562. void TearDown() override {
  19563. svr_.stop();
  19564. if (thread_.joinable()) thread_.join();
  19565. }
  19566. Server svr_;
  19567. std::thread thread_;
  19568. int port_ = 0;
  19569. };
  19570. TEST_F(OpenStreamTest, Basic) {
  19571. Client cli("127.0.0.1", port_);
  19572. auto handle = cli.open_stream("GET", "/hello");
  19573. EXPECT_TRUE(handle.is_valid());
  19574. EXPECT_EQ("Hello World!", read_all(handle));
  19575. }
  19576. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19577. Client cli("127.0.0.1", port_);
  19578. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19579. ASSERT_TRUE(handle.is_valid());
  19580. EXPECT_EQ("Hello World!", read_all(handle));
  19581. }
  19582. TEST_F(OpenStreamTest, SmallBuffer) {
  19583. Client cli("127.0.0.1", port_);
  19584. auto handle = cli.open_stream("GET", "/hello");
  19585. std::string result;
  19586. char buf[4];
  19587. ssize_t n;
  19588. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19589. result.append(buf, static_cast<size_t>(n));
  19590. EXPECT_EQ("Hello World!", result);
  19591. }
  19592. TEST_F(OpenStreamTest, DefaultHeaders) {
  19593. Client cli("127.0.0.1", port_);
  19594. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19595. {
  19596. auto handle = cli.open_stream("GET", "/echo-headers");
  19597. ASSERT_TRUE(handle.is_valid());
  19598. auto body = read_all(handle);
  19599. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19600. std::string::npos);
  19601. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19602. std::string::npos);
  19603. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19604. }
  19605. // open_stream POST with body and no explicit content_type should NOT add
  19606. // text/plain Content-Type (behavior differs from non-streaming path), but
  19607. // should include Content-Length
  19608. {
  19609. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19610. ASSERT_TRUE(handle.is_valid());
  19611. auto body = read_all(handle);
  19612. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19613. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19614. }
  19615. // open_stream POST with explicit Content-Type should preserve it
  19616. {
  19617. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19618. {{"Content-Type", "application/custom"}},
  19619. "{}", "application/custom");
  19620. ASSERT_TRUE(handle.is_valid());
  19621. auto body = read_all(handle);
  19622. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19623. }
  19624. // User-specified User-Agent must not be overwritten for stream API
  19625. {
  19626. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19627. {{"User-Agent", "MyAgent/1.2"}});
  19628. ASSERT_TRUE(handle.is_valid());
  19629. auto body = read_all(handle);
  19630. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19631. }
  19632. }
  19633. TEST_F(OpenStreamTest, Large) {
  19634. Client cli("127.0.0.1", port_);
  19635. auto handle = cli.open_stream("GET", "/large");
  19636. EXPECT_EQ(10000u, read_all(handle).size());
  19637. }
  19638. TEST_F(OpenStreamTest, ConnectionError) {
  19639. Client cli("127.0.0.1", 9999);
  19640. auto handle = cli.open_stream("GET", "/hello");
  19641. EXPECT_FALSE(handle.is_valid());
  19642. }
  19643. TEST_F(OpenStreamTest, Chunked) {
  19644. Client cli("127.0.0.1", port_);
  19645. auto handle = cli.open_stream("GET", "/chunked");
  19646. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19647. "Transfer-Encoding") == "chunked");
  19648. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19649. }
  19650. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19651. Client cli("127.0.0.1", port_);
  19652. auto handle =
  19653. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19654. ASSERT_TRUE(handle.is_valid());
  19655. // Consume body to allow trailers to be received/parsed
  19656. auto body = read_all(handle);
  19657. // Explicitly parse trailers (ensure trailers are available for assertion)
  19658. handle.parse_trailers_if_needed();
  19659. EXPECT_EQ(std::string("123456789"), body);
  19660. // The response should include a Trailer header declaring both names
  19661. ASSERT_TRUE(handle.response);
  19662. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19663. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19664. handle.response->get_header_value("Trailer"));
  19665. // Prohibited trailer must not be present
  19666. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19667. // Allowed trailer should be present
  19668. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19669. EXPECT_EQ(std::string("yes"),
  19670. handle.response->get_trailer_value("X-Allowed"));
  19671. // Verify trailers are NOT present as regular headers
  19672. EXPECT_EQ(std::string(""),
  19673. handle.response->get_header_value("Content-Length"));
  19674. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19675. }
  19676. // Accepts one connection on an OS-assigned port, which it hands over through
  19677. // port_promise, reads the request head and sends back response. after_send,
  19678. // if given, runs on the connection before it is closed.
  19679. static std::thread
  19680. serve_single_response(std::promise<int> &port_promise,
  19681. const std::string &response,
  19682. std::function<void(socket_t)> after_send = nullptr) {
  19683. return std::thread([&port_promise, response, after_send] {
  19684. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19685. default_socket_options(srv);
  19686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19687. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19688. sockaddr_in addr{};
  19689. addr.sin_family = AF_INET;
  19690. addr.sin_port = htons(0); // Let OS assign a free port
  19691. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19692. int opt = 1;
  19693. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19694. #ifdef _WIN32
  19695. reinterpret_cast<const char *>(&opt),
  19696. #else
  19697. &opt,
  19698. #endif
  19699. sizeof(opt));
  19700. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19701. ::listen(srv, 1) != 0) {
  19702. port_promise.set_value(-1);
  19703. detail::close_socket(srv);
  19704. return;
  19705. }
  19706. socklen_t addr_len = sizeof(addr);
  19707. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19708. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19709. sockaddr_in cli_addr{};
  19710. socklen_t cli_len = sizeof(cli_addr);
  19711. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19712. if (cli != INVALID_SOCKET) {
  19713. // Read the complete HTTP request (until the blank line that terminates
  19714. // headers) before sending the response. If the server closes the socket
  19715. // while the client's request data is still unread in the kernel receive
  19716. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19717. // connection on both sides: it discards the client's receive buffer
  19718. // (which already holds our response) and causes any in-progress write on
  19719. // the client to fail with ECONNRESET. Reading all request data first
  19720. // ensures close() emits a graceful FIN.
  19721. {
  19722. char rbuf[256];
  19723. std::string req;
  19724. while (req.find("\r\n\r\n") == std::string::npos) {
  19725. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19726. if (n <= 0) { break; }
  19727. req.append(rbuf, static_cast<size_t>(n));
  19728. }
  19729. }
  19730. ::send(cli,
  19731. #ifdef _WIN32
  19732. static_cast<const char *>(response.c_str()),
  19733. static_cast<int>(response.size()),
  19734. #else
  19735. response.c_str(), response.size(),
  19736. #endif
  19737. 0);
  19738. if (after_send) { after_send(cli); }
  19739. detail::close_socket(cli);
  19740. }
  19741. detail::close_socket(srv);
  19742. });
  19743. }
  19744. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19745. #ifndef _WIN32
  19746. signal(SIGPIPE, SIG_IGN);
  19747. #endif
  19748. std::promise<int> port_promise;
  19749. auto port_future = port_promise.get_future();
  19750. auto server_thread =
  19751. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19752. "Content-Type: text/plain\r\n"
  19753. "Content-Length: not-a-number\r\n"
  19754. "Connection: close\r\n"
  19755. "\r\n"
  19756. "hello");
  19757. auto port = port_future.get();
  19758. ASSERT_GT(port, 0);
  19759. Client cli("127.0.0.1", port);
  19760. auto handle = cli.open_stream("GET", "/");
  19761. EXPECT_FALSE(handle.is_valid());
  19762. server_thread.join();
  19763. }
  19764. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19765. #ifndef _WIN32
  19766. signal(SIGPIPE, SIG_IGN);
  19767. #endif
  19768. std::promise<int> port_promise;
  19769. auto port_future = port_promise.get_future();
  19770. auto server_thread = serve_single_response(
  19771. port_promise, "HTTP/1.1 200 OK\r\n"
  19772. "Content-Type: text/plain\r\n"
  19773. "Content-Length: 99999999999999999999999999\r\n"
  19774. "Connection: close\r\n"
  19775. "\r\n"
  19776. "hello");
  19777. auto port = port_future.get();
  19778. ASSERT_GT(port, 0);
  19779. // Historically std::stoull would throw std::out_of_range here and crash
  19780. // the process, then parsing silently clamped to a bogus framing length and
  19781. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19782. // so the stream fails to open, matching the not-a-number case above. The
  19783. // process still must NOT terminate.
  19784. Client cli("127.0.0.1", port);
  19785. auto handle = cli.open_stream("GET", "/");
  19786. EXPECT_FALSE(handle.is_valid());
  19787. server_thread.join();
  19788. }
  19789. // Serves `response` to the single request `fn` makes with a fresh client.
  19790. template <typename Fn>
  19791. static void with_single_response(const std::string &response, Fn fn) {
  19792. #ifndef _WIN32
  19793. signal(SIGPIPE, SIG_IGN);
  19794. #endif
  19795. std::promise<int> port_promise;
  19796. auto port_future = port_promise.get_future();
  19797. auto server_thread = serve_single_response(port_promise, response);
  19798. auto se = detail::scope_exit([&] { server_thread.join(); });
  19799. auto port = port_future.get();
  19800. ASSERT_GT(port, 0);
  19801. Client cli("127.0.0.1", port);
  19802. fn(cli);
  19803. }
  19804. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19805. // Neither Content-Length nor chunked: the body ends at the close
  19806. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19807. "Connection: close\r\n"
  19808. "\r\n"
  19809. "hello";
  19810. with_single_response(close_delimited, [](Client &cli) {
  19811. auto handle = cli.open_stream("GET", "/");
  19812. ASSERT_TRUE(handle.is_valid());
  19813. EXPECT_EQ("hello", read_all(handle));
  19814. EXPECT_FALSE(handle.has_read_error());
  19815. });
  19816. // A close before the end of the Content-Length is still an error
  19817. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19818. "Content-Length: 10\r\n"
  19819. "\r\n"
  19820. "hello";
  19821. with_single_response(short_content_length, [](Client &cli) {
  19822. auto handle = cli.open_stream("GET", "/");
  19823. ASSERT_TRUE(handle.is_valid());
  19824. read_all(handle);
  19825. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19826. });
  19827. // So is a close before the last chunk
  19828. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19829. "Transfer-Encoding: chunked\r\n"
  19830. "\r\n"
  19831. "5\r\nhello\r\n";
  19832. with_single_response(short_chunked, [](Client &cli) {
  19833. auto handle = cli.open_stream("GET", "/");
  19834. ASSERT_TRUE(handle.is_valid());
  19835. read_all(handle);
  19836. EXPECT_TRUE(handle.has_read_error());
  19837. });
  19838. }
  19839. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19840. const char *responses[] = {
  19841. "HTTP/1.1 103 Early Hints\r\n"
  19842. "Link: </style.css>; rel=preload\r\n"
  19843. "\r\n"
  19844. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19845. "HTTP/1.1 100 Continue\r\n"
  19846. "X-Note: interim\r\n"
  19847. "\r\n"
  19848. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19849. };
  19850. for (auto response : responses) {
  19851. with_single_response(response, [](Client &cli) {
  19852. auto res = cli.Get("/");
  19853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19854. EXPECT_EQ(StatusCode::OK_200, res->status);
  19855. EXPECT_EQ("ok", res->body);
  19856. });
  19857. }
  19858. }
  19859. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19860. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19861. const std::string final_response =
  19862. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19863. std::string interims;
  19864. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19865. interims += interim;
  19866. }
  19867. with_single_response(interims + final_response, [](Client &cli) {
  19868. auto res = cli.Get("/");
  19869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19870. EXPECT_EQ("ok", res->body);
  19871. });
  19872. with_single_response(interims + interim + final_response, [](Client &cli) {
  19873. auto res = cli.Get("/");
  19874. ASSERT_FALSE(res);
  19875. EXPECT_EQ(Error::Read, res.error());
  19876. });
  19877. }
  19878. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19879. #ifndef _WIN32
  19880. signal(SIGPIPE, SIG_IGN);
  19881. #endif
  19882. // The server answers the head without asking for the body. Bytes it then
  19883. // reads on the connection would be taken for the body the request declared.
  19884. auto closed_by_client = false;
  19885. std::promise<int> port_promise;
  19886. auto server_thread = serve_single_response(
  19887. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19888. [&](socket_t sock) {
  19889. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19890. char buf[256];
  19891. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19892. });
  19893. Client cli("127.0.0.1", port_promise.get_future().get());
  19894. cli.set_keep_alive(true);
  19895. cli.set_read_timeout(1, 0);
  19896. // Long enough for the client to send Expect: 100-continue.
  19897. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19900. cli.Get("/second");
  19901. server_thread.join();
  19902. EXPECT_TRUE(closed_by_client);
  19903. }
  19904. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19905. // Long enough for the client to send Expect: 100-continue
  19906. with_single_response(
  19907. "HTTP/1.1 103 Early Hints\r\n"
  19908. "Link: </style.css>; rel=preload\r\n"
  19909. "\r\n"
  19910. "HTTP/1.1 401 Unauthorized\r\n"
  19911. "Content-Length: 0\r\n\r\n",
  19912. [](Client &cli) {
  19913. cli.set_read_timeout(2, 0);
  19914. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19916. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19917. });
  19918. }
  19919. #ifdef CPPHTTPLIB_SSL_ENABLED
  19920. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19921. #ifndef _WIN32
  19922. signal(SIGPIPE, SIG_IGN);
  19923. #endif
  19924. auto reused = false;
  19925. std::promise<int> port_promise;
  19926. auto server_thread = serve_single_response(
  19927. port_promise,
  19928. "HTTP/1.1 401 Unauthorized\r\n"
  19929. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19930. "Content-Length: 0\r\n\r\n",
  19931. [&](socket_t sock) {
  19932. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19933. char buf[256];
  19934. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19935. });
  19936. Client cli("127.0.0.1", port_promise.get_future().get());
  19937. cli.set_keep_alive(true);
  19938. cli.set_digest_auth("user", "pass");
  19939. cli.set_read_timeout(1, 0);
  19940. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19941. server_thread.join();
  19942. EXPECT_FALSE(reused);
  19943. }
  19944. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19945. // Any other answer to CONNECT would read as the origin's response.
  19946. struct {
  19947. const char *response;
  19948. bool passed_on;
  19949. } cases[] = {
  19950. {"HTTP/1.1 201 Created\r\n"
  19951. "Set-Cookie: session=from-proxy\r\n"
  19952. "Content-Length: 0\r\n\r\n",
  19953. false},
  19954. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19955. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19956. "Content-Length: 0\r\n\r\n",
  19957. true},
  19958. };
  19959. for (const auto &c : cases) {
  19960. std::promise<int> port_promise;
  19961. auto server_thread = serve_single_response(port_promise, c.response);
  19962. SSLClient cli("example.com", 443);
  19963. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19964. auto res = cli.Get("/");
  19965. server_thread.join();
  19966. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19967. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19968. if (res) {
  19969. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19970. }
  19971. }
  19972. }
  19973. #endif
  19974. // Records the client's error logger calls as "error METHOD path", or
  19975. // "error null" for a call without a request
  19976. static ErrorLogger record_errors(std::vector<std::string> &log) {
  19977. return [&log](const Error &err, const Request *req) {
  19978. log.push_back(to_string(err) + " " +
  19979. (req ? req->method + " " + req->path : "null"));
  19980. };
  19981. }
  19982. // A failed request is reported once, with the request the caller made
  19983. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  19984. Server svr;
  19985. svr.Get("/big", [](const Request &, Response &res) {
  19986. res.set_content(std::string(100000, 'b'), "text/plain");
  19987. });
  19988. auto port = svr.bind_to_any_port(HOST);
  19989. std::thread t([&]() { svr.listen_after_bind(); });
  19990. auto se = detail::scope_exit([&] {
  19991. svr.stop();
  19992. t.join();
  19993. });
  19994. svr.wait_until_ready();
  19995. Client cli(HOST, port);
  19996. std::vector<std::string> log;
  19997. cli.set_error_logger(record_errors(log));
  19998. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  19999. cli.Get("/big", [](const char *, size_t) { return false; });
  20000. EXPECT_EQ(expected, log);
  20001. log.clear();
  20002. cli.Get("/big", [](size_t, size_t) { return false; });
  20003. EXPECT_EQ(expected, log);
  20004. }
  20005. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20006. // Fails while the body is read
  20007. auto broken = [](const Request &, Response &res) {
  20008. res.set_content_provider(10, "text/plain",
  20009. [](size_t, size_t, DataSink &) { return false; });
  20010. };
  20011. Server other;
  20012. other.Get("/broken", broken);
  20013. auto other_port = other.bind_to_any_port(HOST);
  20014. std::thread other_t([&]() { other.listen_after_bind(); });
  20015. auto other_se = detail::scope_exit([&] {
  20016. other.stop();
  20017. other_t.join();
  20018. });
  20019. other.wait_until_ready();
  20020. Server svr;
  20021. svr.Get("/broken", broken);
  20022. svr.Get("/same-origin",
  20023. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20024. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20025. res.set_redirect("http://" + std::string(HOST) + ":" +
  20026. std::to_string(other_port) + "/broken");
  20027. });
  20028. auto port = svr.bind_to_any_port(HOST);
  20029. std::thread t([&]() { svr.listen_after_bind(); });
  20030. auto se = detail::scope_exit([&] {
  20031. svr.stop();
  20032. t.join();
  20033. });
  20034. svr.wait_until_ready();
  20035. Client cli(HOST, port);
  20036. cli.set_follow_location(true);
  20037. std::vector<std::string> log;
  20038. cli.set_error_logger(record_errors(log));
  20039. for (auto path : {"/same-origin", "/cross-origin"}) {
  20040. log.clear();
  20041. auto res = cli.Get(path);
  20042. ASSERT_FALSE(res);
  20043. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20044. log);
  20045. }
  20046. }
  20047. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20048. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20049. std::vector<std::string> log;
  20050. cli.set_error_logger(record_errors(log));
  20051. auto handle = cli.open_stream("GET", "/x");
  20052. EXPECT_FALSE(handle.is_valid());
  20053. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20054. log);
  20055. });
  20056. }
  20057. #ifdef CPPHTTPLIB_SSL_ENABLED
  20058. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20059. // Not a TLS server, so the handshake fails. It waits for a request line in
  20060. // the handshake bytes, so a short read timeout lets it close quickly.
  20061. Server svr;
  20062. svr.set_read_timeout(0, 100000);
  20063. svr.Get("/x", [](const Request &, Response &res) {
  20064. res.set_content("x", "text/plain");
  20065. });
  20066. auto port = svr.bind_to_any_port(HOST);
  20067. std::thread t([&]() { svr.listen_after_bind(); });
  20068. auto se = detail::scope_exit([&] {
  20069. svr.stop();
  20070. t.join();
  20071. });
  20072. svr.wait_until_ready();
  20073. std::vector<std::string> log;
  20074. SSLClient cli(HOST, port);
  20075. cli.enable_server_certificate_verification(false);
  20076. cli.set_error_logger(record_errors(log));
  20077. auto res = cli.Get("/x");
  20078. ASSERT_FALSE(res);
  20079. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20080. log.clear();
  20081. auto handle = cli.open_stream("GET", "/x");
  20082. EXPECT_FALSE(handle.is_valid());
  20083. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20084. log.clear();
  20085. SSLClient no_ca(HOST, port);
  20086. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20087. no_ca.set_error_logger(record_errors(log));
  20088. res = no_ca.Get("/x");
  20089. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20090. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20091. }
  20092. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20093. #ifndef _WIN32
  20094. signal(SIGPIPE, SIG_IGN);
  20095. #endif
  20096. // Refused, answered with a challenge, or closed without an answer
  20097. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20098. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20099. "Content-Length: 0\r\n\r\n",
  20100. ""}) {
  20101. std::promise<int> port_promise;
  20102. auto server_thread = serve_single_response(port_promise, response);
  20103. SSLClient cli("example.com", 443);
  20104. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20105. std::vector<std::string> log;
  20106. cli.set_error_logger(record_errors(log));
  20107. auto res = cli.Get("/");
  20108. server_thread.join();
  20109. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20110. << response;
  20111. }
  20112. }
  20113. #endif
  20114. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20115. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20116. // the chunked coding and drop Content-Length, so a front-end that trusts
  20117. // Content-Length would disagree about where the body ends (response
  20118. // smuggling). The client must reject such a response.
  20119. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20120. for (const char *te : {"chunked", "gzip, chunked"}) {
  20121. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20122. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20123. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20124. "5\r\nhello\r\n0\r\n\r\n";
  20125. with_single_response(response, [&](Client &cli) {
  20126. auto res = cli.Get("/");
  20127. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20128. EXPECT_EQ(Error::Read, res.error()) << te;
  20129. });
  20130. with_single_response(response, [&](Client &cli) {
  20131. auto handle = cli.open_stream("GET", "/");
  20132. EXPECT_FALSE(handle.is_valid()) << te;
  20133. EXPECT_EQ(Error::Read, handle.error) << te;
  20134. });
  20135. }
  20136. }
  20137. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20138. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20139. // closing the connection (unlike a request, which must be rejected).
  20140. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20141. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20142. "Transfer-Encoding: chunked\r\n"
  20143. "Connection: close\r\n"
  20144. "\r\n"
  20145. "5\r\nhello\r\n0\r\n\r\n",
  20146. "HTTP/1.1 200 OK\r\n"
  20147. "Transfer-Encoding: gzip\r\n"
  20148. "Connection: close\r\n"
  20149. "\r\n"
  20150. "hello"}) {
  20151. with_single_response(response, [&](Client &cli) {
  20152. auto res = cli.Get("/");
  20153. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20154. EXPECT_EQ("hello", res->body);
  20155. });
  20156. with_single_response(response, [&](Client &cli) {
  20157. auto handle = cli.open_stream("GET", "/");
  20158. ASSERT_TRUE(handle.is_valid()) << response;
  20159. EXPECT_EQ("hello", read_all(handle));
  20160. });
  20161. }
  20162. }
  20163. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20164. // framing headers describe nothing to read and must not be rejected.
  20165. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20166. const std::string framing = "Content-Length: 5\r\n"
  20167. "Transfer-Encoding: chunked\r\n"
  20168. "Connection: close\r\n"
  20169. "\r\n";
  20170. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20171. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20172. });
  20173. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20174. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20175. });
  20176. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20177. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20178. with_single_response(response, [&](Client &cli) {
  20179. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20180. });
  20181. with_single_response(response, [&](Client &cli) {
  20182. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20183. });
  20184. }
  20185. }
  20186. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20187. // header section, so a stream opened on one has nothing to read, whatever
  20188. // framing or coding headers it carries.
  20189. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20190. struct Case {
  20191. const char *method;
  20192. const char *status;
  20193. };
  20194. // A reader of the declared body reports an early close when nothing
  20195. // follows, and hands back what does.
  20196. struct Framing {
  20197. const char *headers;
  20198. const char *after;
  20199. };
  20200. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20201. Case{"GET", "304 Not Modified"}}) {
  20202. for (const auto &f :
  20203. {Framing{"Content-Length: 5\r\n", ""},
  20204. Framing{"Content-Length: 5\r\n", "hello"},
  20205. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20206. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20207. // Not decoded, so a build without Brotli opens it too
  20208. Framing{"Content-Encoding: br\r\n", ""}}) {
  20209. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20210. "Connection: close\r\n"
  20211. "\r\n" +
  20212. f.after;
  20213. with_single_response(response, [&](Client &cli) {
  20214. auto handle = cli.open_stream(c.method, "/");
  20215. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20216. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20217. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20218. });
  20219. }
  20220. }
  20221. }
  20222. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20223. // response, is faulty framing, so the connection is not reused after it.
  20224. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20225. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20226. "Content-Length: 0\r\n"
  20227. "Transfer-Encoding: chunked\r\n"
  20228. "\r\n"
  20229. "5\r\nhello\r\n0\r\n\r\n",
  20230. "HTTP/1.0 200 Connection established\r\n"
  20231. "Connection: keep-alive\r\n"
  20232. "Transfer-Encoding: chunked\r\n"
  20233. "\r\n"
  20234. "5\r\nhello\r\n0\r\n\r\n"}) {
  20235. with_single_response(response, [&](Client &cli) {
  20236. cli.set_keep_alive(true);
  20237. auto res = cli.Get("/");
  20238. ASSERT_TRUE(res) << response;
  20239. EXPECT_EQ("hello", res->body);
  20240. EXPECT_FALSE(cli.is_socket_open()) << response;
  20241. });
  20242. }
  20243. }
  20244. // A payload max length of 0 means no limit, however the body is framed.
  20245. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20246. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20247. "Transfer-Encoding: chunked\r\n"
  20248. "\r\n"
  20249. "5\r\nhello\r\n0\r\n\r\n",
  20250. "HTTP/1.1 200 OK\r\n"
  20251. "Connection: close\r\n"
  20252. "\r\n"
  20253. "hello"}) {
  20254. with_single_response(response, [&](Client &cli) {
  20255. cli.set_payload_max_length(0);
  20256. auto res = cli.Get("/");
  20257. ASSERT_TRUE(res) << response;
  20258. EXPECT_EQ("hello", res->body) << response;
  20259. });
  20260. }
  20261. }
  20262. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20263. Server svr;
  20264. svr.set_payload_max_length(0);
  20265. svr.Post("/echo", [](const Request &req, Response &res) {
  20266. res.set_content(req.body, "text/plain");
  20267. });
  20268. auto port = svr.bind_to_any_port(HOST);
  20269. thread t = thread([&] { svr.listen_after_bind(); });
  20270. auto se = detail::scope_exit([&] {
  20271. svr.stop();
  20272. t.join();
  20273. ASSERT_FALSE(svr.is_running());
  20274. });
  20275. svr.wait_until_ready();
  20276. Client cli(HOST, port);
  20277. auto res = cli.Post(
  20278. "/echo",
  20279. [](size_t /*offset*/, DataSink &sink) {
  20280. sink.write("hello", 5);
  20281. sink.done();
  20282. return true;
  20283. },
  20284. "text/plain");
  20285. ASSERT_TRUE(res);
  20286. EXPECT_EQ(StatusCode::OK_200, res->status);
  20287. EXPECT_EQ("hello", res->body);
  20288. }
  20289. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20290. TEST_F(OpenStreamTest, Gzip) {
  20291. Client cli("127.0.0.1", port_);
  20292. auto handle = cli.open_stream("GET", "/compressible", {},
  20293. {{"Accept-Encoding", "gzip"}});
  20294. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20295. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20296. }
  20297. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20298. Client cli("127.0.0.1", port_);
  20299. auto handle =
  20300. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20301. {{"Accept-Encoding", "gzip"}});
  20302. ASSERT_TRUE(handle.is_valid());
  20303. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20304. EXPECT_EQ("123456789", read_all(handle));
  20305. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20306. }
  20307. #endif
  20308. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20309. TEST_F(OpenStreamTest, Brotli) {
  20310. Client cli("127.0.0.1", port_);
  20311. auto handle =
  20312. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20313. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20314. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20315. }
  20316. #endif
  20317. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20318. TEST_F(OpenStreamTest, Zstd) {
  20319. Client cli("127.0.0.1", port_);
  20320. auto handle = cli.open_stream("GET", "/compressible", {},
  20321. {{"Accept-Encoding", "zstd"}});
  20322. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20323. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20324. }
  20325. #endif
  20326. #ifdef CPPHTTPLIB_SSL_ENABLED
  20327. class SSLOpenStreamTest : public ::testing::Test {
  20328. protected:
  20329. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20330. void SetUp() override {
  20331. svr_.Get("/hello", [](const Request &, Response &res) {
  20332. res.set_content("Hello SSL World!", "text/plain");
  20333. });
  20334. svr_.Get("/chunked", [](const Request &, Response &res) {
  20335. res.set_chunked_content_provider("text/plain",
  20336. [](size_t offset, DataSink &sink) {
  20337. if (offset < 15) {
  20338. sink.write("chunk", 5);
  20339. return true;
  20340. }
  20341. sink.done();
  20342. return true;
  20343. });
  20344. });
  20345. svr_.Post("/echo", [](const Request &req, Response &res) {
  20346. res.set_content(req.body, req.get_header_value("Content-Type"));
  20347. });
  20348. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20349. std::string body = req.body;
  20350. res.set_chunked_content_provider(
  20351. "text/plain", [body](size_t offset, DataSink &sink) {
  20352. if (offset < body.size()) {
  20353. sink.write(body.data() + offset, body.size() - offset);
  20354. }
  20355. sink.done();
  20356. return true;
  20357. });
  20358. });
  20359. port_ = svr_.bind_to_any_port("127.0.0.1");
  20360. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20361. svr_.wait_until_ready();
  20362. }
  20363. void TearDown() override {
  20364. svr_.stop();
  20365. if (thread_.joinable()) thread_.join();
  20366. }
  20367. SSLServer svr_;
  20368. std::thread thread_;
  20369. int port_ = 0;
  20370. };
  20371. TEST_F(SSLOpenStreamTest, Basic) {
  20372. SSLClient cli("127.0.0.1", port_);
  20373. cli.enable_server_certificate_verification(false);
  20374. auto handle = cli.open_stream("GET", "/hello");
  20375. ASSERT_TRUE(handle.is_valid());
  20376. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20377. }
  20378. TEST_F(SSLOpenStreamTest, Chunked) {
  20379. SSLClient cli("127.0.0.1", port_);
  20380. cli.enable_server_certificate_verification(false);
  20381. auto handle = cli.open_stream("GET", "/chunked");
  20382. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20383. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20384. "Transfer-Encoding") == "chunked");
  20385. auto body = read_all(handle);
  20386. EXPECT_EQ("chunkchunkchunk", body);
  20387. }
  20388. TEST_F(SSLOpenStreamTest, Post) {
  20389. SSLClient cli("127.0.0.1", port_);
  20390. cli.enable_server_certificate_verification(false);
  20391. auto handle =
  20392. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20393. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20394. EXPECT_EQ(200, handle.response->status);
  20395. auto body = read_all(handle);
  20396. EXPECT_EQ("Hello SSL POST", body);
  20397. }
  20398. TEST_F(SSLOpenStreamTest, PostChunked) {
  20399. SSLClient cli("127.0.0.1", port_);
  20400. cli.enable_server_certificate_verification(false);
  20401. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20402. "Chunked SSL Data", "text/plain");
  20403. ASSERT_TRUE(handle.is_valid());
  20404. EXPECT_EQ(200, handle.response->status);
  20405. auto body = read_all(handle);
  20406. EXPECT_EQ("Chunked SSL Data", body);
  20407. }
  20408. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20409. // Content-Length is terminated by the server closing the connection. When the
  20410. // SSL peer sends a close_notify after the body, the client must treat it as a
  20411. // clean EOF and return a successful response rather than an error.
  20412. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20414. ASSERT_TRUE(svr.is_valid());
  20415. svr.set_keep_alive_max_count(1);
  20416. const std::string expected_body = "Hello from connection-close response!";
  20417. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20418. res.set_content_provider("text/plain",
  20419. [&](size_t offset, DataSink &sink) -> bool {
  20420. if (offset < expected_body.size()) {
  20421. sink.write(expected_body.data() + offset,
  20422. expected_body.size() - offset);
  20423. }
  20424. sink.done();
  20425. return true;
  20426. });
  20427. });
  20428. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20429. auto se = detail::scope_exit([&] {
  20430. svr.stop();
  20431. listen_thread.join();
  20432. ASSERT_FALSE(svr.is_running());
  20433. });
  20434. svr.wait_until_ready();
  20435. SSLClient cli(HOST, PORT);
  20436. cli.enable_server_certificate_verification(false);
  20437. auto res = cli.Get("/no-content-length");
  20438. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20439. EXPECT_EQ(StatusCode::OK_200, res->status);
  20440. EXPECT_EQ(expected_body, res->body);
  20441. }
  20442. #endif // CPPHTTPLIB_SSL_ENABLED
  20443. //==============================================================================
  20444. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20445. // results for various scenarios.
  20446. //==============================================================================
  20447. TEST(ParityTest, GetVsOpenStream) {
  20448. Server svr;
  20449. const std::string path = "/parity";
  20450. const std::string content = "Parity test content: hello world";
  20451. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20452. res.set_content(content, "text/plain");
  20453. });
  20454. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20455. auto se = detail::scope_exit([&] {
  20456. svr.stop();
  20457. t.join();
  20458. ASSERT_FALSE(svr.is_running());
  20459. });
  20460. svr.wait_until_ready();
  20461. Client cli(HOST, PORT);
  20462. // Non-stream path
  20463. auto r1 = cli.Get(path);
  20464. ASSERT_TRUE(r1);
  20465. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20466. // Stream path
  20467. auto h = cli.open_stream("GET", path);
  20468. ASSERT_TRUE(h.is_valid());
  20469. EXPECT_EQ(r1->body, read_all(h));
  20470. }
  20471. // Helper to compress data with provided compressor type T
  20472. template <typename Compressor>
  20473. static std::string compress_payload_for_parity(const std::string &in) {
  20474. std::string out;
  20475. Compressor compressor;
  20476. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20477. [&](const char *data, size_t n) {
  20478. out.append(data, n);
  20479. return true;
  20480. });
  20481. EXPECT_TRUE(ok);
  20482. return out;
  20483. }
  20484. // Helper function for compression parity tests
  20485. template <typename Compressor>
  20486. static void test_compression_parity(const std::string &original,
  20487. const std::string &path,
  20488. const std::string &encoding) {
  20489. const std::string compressed =
  20490. compress_payload_for_parity<Compressor>(original);
  20491. Server svr;
  20492. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20493. res.set_content(compressed, "application/octet-stream");
  20494. res.set_header("Content-Encoding", encoding);
  20495. });
  20496. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20497. auto se = detail::scope_exit([&] {
  20498. svr.stop();
  20499. t.join();
  20500. ASSERT_FALSE(svr.is_running());
  20501. });
  20502. svr.wait_until_ready();
  20503. Client cli(HOST, PORT);
  20504. // Non-streaming
  20505. {
  20506. auto res = cli.Get(path);
  20507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20508. EXPECT_EQ(StatusCode::OK_200, res->status);
  20509. EXPECT_EQ(original, res->body);
  20510. }
  20511. // Streaming
  20512. {
  20513. auto h = cli.open_stream("GET", path);
  20514. ASSERT_TRUE(h.is_valid());
  20515. EXPECT_EQ(original, read_all(h));
  20516. }
  20517. }
  20518. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20519. TEST(ParityTest, Gzip) {
  20520. test_compression_parity<detail::gzip_compressor>(
  20521. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20522. }
  20523. #endif
  20524. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20525. TEST(ParityTest, Brotli) {
  20526. test_compression_parity<detail::brotli_compressor>(
  20527. "Hello, brotli parity test payload", "/parity-br", "br");
  20528. }
  20529. #endif
  20530. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20531. TEST(ParityTest, Zstd) {
  20532. test_compression_parity<detail::zstd_compressor>(
  20533. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20534. }
  20535. #endif
  20536. //==============================================================================
  20537. // New Stream API Tests
  20538. //==============================================================================
  20539. inline std::string read_body(httplib::stream::Result &result) {
  20540. std::string body;
  20541. while (result.next()) {
  20542. body.append(result.data(), result.size());
  20543. }
  20544. return body;
  20545. }
  20546. TEST(ClientConnectionTest, Basic) {
  20547. httplib::ClientConnection conn;
  20548. EXPECT_FALSE(conn.is_open());
  20549. conn.sock = 1;
  20550. EXPECT_TRUE(conn.is_open());
  20551. httplib::ClientConnection conn2(std::move(conn));
  20552. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20553. conn2.sock = INVALID_SOCKET;
  20554. }
  20555. // Unified test server for all stream::* tests
  20556. class StreamApiTest : public ::testing::Test {
  20557. protected:
  20558. void SetUp() override {
  20559. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20560. res.set_content("Hello World!", "text/plain");
  20561. });
  20562. svr_.Get("/echo-params",
  20563. [](const httplib::Request &req, httplib::Response &res) {
  20564. std::string r;
  20565. for (const auto &p : req.params) {
  20566. if (!r.empty()) r += "&";
  20567. r += p.first + "=" + p.second;
  20568. }
  20569. res.set_content(r, "text/plain");
  20570. });
  20571. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20572. res.set_content(req.body, req.get_header_value("Content-Type"));
  20573. });
  20574. svr_.Post("/echo-headers",
  20575. [](const httplib::Request &req, httplib::Response &res) {
  20576. std::string r;
  20577. for (const auto &h : req.headers)
  20578. r += h.first + ": " + h.second + "\n";
  20579. res.set_content(r, "text/plain");
  20580. });
  20581. svr_.Post("/echo-params",
  20582. [](const httplib::Request &req, httplib::Response &res) {
  20583. std::string r = "params:";
  20584. for (const auto &p : req.params)
  20585. r += p.first + "=" + p.second + ";";
  20586. res.set_content(r + " body:" + req.body, "text/plain");
  20587. });
  20588. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20589. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20590. });
  20591. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20592. res.set_content("PUT:" + req.body, "text/plain");
  20593. });
  20594. svr_.Patch("/echo",
  20595. [](const httplib::Request &req, httplib::Response &res) {
  20596. res.set_content("PATCH:" + req.body, "text/plain");
  20597. });
  20598. svr_.Delete(
  20599. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20600. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20601. "text/plain");
  20602. });
  20603. svr_.Get("/head-test",
  20604. [](const httplib::Request &, httplib::Response &res) {
  20605. res.set_content("body for HEAD", "text/plain");
  20606. });
  20607. svr_.Options("/options",
  20608. [](const httplib::Request &, httplib::Response &res) {
  20609. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20610. });
  20611. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20612. svr_.wait_until_ready();
  20613. }
  20614. void TearDown() override {
  20615. svr_.stop();
  20616. if (thread_.joinable()) thread_.join();
  20617. }
  20618. httplib::Server svr_;
  20619. std::thread thread_;
  20620. };
  20621. // stream::Get tests
  20622. TEST_F(StreamApiTest, GetBasic) {
  20623. httplib::Client cli(HOST, PORT);
  20624. auto result = httplib::stream::Get(cli, "/hello");
  20625. ASSERT_TRUE(result.is_valid());
  20626. EXPECT_EQ(200, result.status());
  20627. EXPECT_EQ("Hello World!", read_body(result));
  20628. }
  20629. TEST_F(StreamApiTest, GetWithParams) {
  20630. httplib::Client cli(HOST, PORT);
  20631. httplib::Params params{{"foo", "bar"}};
  20632. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20633. ASSERT_TRUE(result.is_valid());
  20634. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20635. }
  20636. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20637. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20638. httplib::Client cli(HOST, PORT);
  20639. cli.set_payload_max_length(0);
  20640. auto result = httplib::stream::Get(cli, "/hello");
  20641. ASSERT_TRUE(result.is_valid());
  20642. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20643. EXPECT_EQ("Hello World!", read_body(result));
  20644. }
  20645. #endif
  20646. TEST_F(StreamApiTest, GetConnectionError) {
  20647. httplib::Client cli(HOST, 9999);
  20648. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20649. }
  20650. TEST_F(StreamApiTest, Get404) {
  20651. httplib::Client cli(HOST, PORT);
  20652. auto result = httplib::stream::Get(cli, "/nonexistent");
  20653. EXPECT_TRUE(result.is_valid());
  20654. EXPECT_EQ(404, result.status());
  20655. }
  20656. // stream::Post tests
  20657. TEST_F(StreamApiTest, PostBasic) {
  20658. httplib::Client cli(HOST, PORT);
  20659. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20660. "application/json");
  20661. ASSERT_TRUE(result.is_valid());
  20662. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20663. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20664. }
  20665. TEST_F(StreamApiTest, PostWithHeaders) {
  20666. httplib::Client cli(HOST, PORT);
  20667. httplib::Headers headers{{"X-Custom", "value"}};
  20668. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20669. "text/plain");
  20670. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20671. }
  20672. TEST_F(StreamApiTest, PostWithParams) {
  20673. httplib::Client cli(HOST, PORT);
  20674. httplib::Params params{{"k", "v"}};
  20675. auto result =
  20676. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20677. auto body = read_body(result);
  20678. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20679. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20680. }
  20681. TEST_F(StreamApiTest, PostLarge) {
  20682. httplib::Client cli(HOST, PORT);
  20683. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20684. size_t total = 0;
  20685. while (result.next()) {
  20686. total += result.size();
  20687. }
  20688. EXPECT_EQ(100u * 1024u, total);
  20689. }
  20690. // stream::Put/Patch tests
  20691. TEST_F(StreamApiTest, PutAndPatch) {
  20692. httplib::Client cli(HOST, PORT);
  20693. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20694. EXPECT_EQ("PUT:test", read_body(put));
  20695. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20696. EXPECT_EQ("PATCH:test", read_body(patch));
  20697. }
  20698. // stream::Delete tests
  20699. TEST_F(StreamApiTest, Delete) {
  20700. httplib::Client cli(HOST, PORT);
  20701. auto del1 = httplib::stream::Delete(cli, "/resource");
  20702. EXPECT_EQ("Deleted", read_body(del1));
  20703. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20704. EXPECT_EQ("Deleted:data", read_body(del2));
  20705. }
  20706. // stream::Head/Options tests
  20707. TEST_F(StreamApiTest, HeadAndOptions) {
  20708. httplib::Client cli(HOST, PORT);
  20709. auto head = httplib::stream::Head(cli, "/head-test");
  20710. EXPECT_TRUE(head.is_valid());
  20711. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20712. auto opts = httplib::stream::Options(cli, "/options");
  20713. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20714. }
  20715. // SSL stream::* tests
  20716. #ifdef CPPHTTPLIB_SSL_ENABLED
  20717. class SSLStreamApiTest : public ::testing::Test {
  20718. protected:
  20719. void SetUp() override {
  20720. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20721. res.set_content("Hello SSL!", "text/plain");
  20722. });
  20723. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20724. res.set_content(req.body, "text/plain");
  20725. });
  20726. port_ = svr_.bind_to_any_port("127.0.0.1");
  20727. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20728. svr_.wait_until_ready();
  20729. }
  20730. void TearDown() override {
  20731. svr_.stop();
  20732. if (thread_.joinable()) thread_.join();
  20733. }
  20734. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20735. std::thread thread_;
  20736. int port_ = 0;
  20737. };
  20738. TEST_F(SSLStreamApiTest, GetAndPost) {
  20739. httplib::SSLClient cli("127.0.0.1", port_);
  20740. cli.enable_server_certificate_verification(false);
  20741. auto get = httplib::stream::Get(cli, "/hello");
  20742. EXPECT_EQ("Hello SSL!", read_body(get));
  20743. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20744. EXPECT_EQ("test", read_body(post));
  20745. }
  20746. #endif
  20747. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20748. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20749. // BodyReader
  20750. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20751. // Test that read timeout during streaming is detected
  20752. // Use a large content-length response where server delays mid-stream
  20753. Server svr;
  20754. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20755. // Send a large response with delay in the middle
  20756. res.set_content_provider(
  20757. 1000, // content_length
  20758. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20759. if (offset < 100) {
  20760. // Send first 100 bytes immediately
  20761. std::string data(100, 'A');
  20762. sink.write(data.c_str(), data.size());
  20763. return true;
  20764. }
  20765. // Then delay longer than client timeout
  20766. std::this_thread::sleep_for(std::chrono::seconds(3));
  20767. std::string data(900, 'B');
  20768. sink.write(data.c_str(), data.size());
  20769. return true;
  20770. });
  20771. });
  20772. auto port = 8091;
  20773. std::thread t([&]() { svr.listen("localhost", port); });
  20774. svr.wait_until_ready();
  20775. Client cli("localhost", port);
  20776. cli.set_read_timeout(1, 0); // 1 second timeout
  20777. auto handle = cli.open_stream("GET", "/slow-stream");
  20778. ASSERT_TRUE(handle.is_valid());
  20779. char buf[256];
  20780. ssize_t total = 0;
  20781. ssize_t n;
  20782. bool got_error = false;
  20783. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20784. total += n;
  20785. }
  20786. if (n < 0) {
  20787. got_error = true;
  20788. // Should be timeout or read error
  20789. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20790. handle.get_read_error() == Error::Read)
  20791. << "Actual error: " << to_string(handle.get_read_error());
  20792. }
  20793. // Either we got an error, or we got less data than expected
  20794. EXPECT_TRUE(got_error || total < 1000)
  20795. << "Expected timeout but got all " << total << " bytes";
  20796. svr.stop();
  20797. t.join();
  20798. }
  20799. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20800. // Test connection closed detection via BodyReader
  20801. Server svr;
  20802. std::atomic<bool> close_now{false};
  20803. svr.Get("/will-close", [&](const Request &, Response &res) {
  20804. res.set_content_provider(
  20805. 10000, // Large content_length that we won't fully send
  20806. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20807. if (offset < 100) {
  20808. std::string data(100, 'X');
  20809. sink.write(data.c_str(), data.size());
  20810. return true;
  20811. }
  20812. // Wait for signal then abort
  20813. while (!close_now) {
  20814. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20815. }
  20816. return false; // Abort - server will close connection
  20817. });
  20818. });
  20819. auto port = 8092;
  20820. std::thread t([&]() { svr.listen("localhost", port); });
  20821. svr.wait_until_ready();
  20822. Client cli("localhost", port);
  20823. auto handle = cli.open_stream("GET", "/will-close");
  20824. ASSERT_TRUE(handle.is_valid());
  20825. char buf[256];
  20826. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20827. EXPECT_GT(n, 0) << "First read should succeed";
  20828. // Signal server to close
  20829. close_now = true;
  20830. // Keep reading until error or EOF
  20831. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20832. // Keep reading
  20833. }
  20834. // Should get an error since content_length wasn't satisfied
  20835. if (n < 0) {
  20836. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20837. handle.get_read_error() == Error::Read)
  20838. << "Actual error: " << to_string(handle.get_read_error());
  20839. }
  20840. svr.stop();
  20841. t.join();
  20842. }
  20843. #ifdef CPPHTTPLIB_SSL_ENABLED
  20844. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20845. // Test that read timeout during SSL streaming is detected
  20846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20847. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20848. res.set_content_provider(
  20849. 1000, "text/plain",
  20850. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20851. if (offset < 100) {
  20852. std::string data(100, 'A');
  20853. sink.write(data.c_str(), data.size());
  20854. return true;
  20855. }
  20856. std::this_thread::sleep_for(std::chrono::seconds(3));
  20857. std::string data(900, 'B');
  20858. sink.write(data.c_str(), data.size());
  20859. return true;
  20860. });
  20861. });
  20862. auto port = 8093;
  20863. std::thread t([&]() { svr.listen("localhost", port); });
  20864. svr.wait_until_ready();
  20865. SSLClient cli("localhost", port);
  20866. cli.enable_server_certificate_verification(false);
  20867. cli.set_read_timeout(1, 0); // 1 second timeout
  20868. auto handle = cli.open_stream("GET", "/slow-stream");
  20869. ASSERT_TRUE(handle.is_valid());
  20870. char buf[256];
  20871. ssize_t total = 0;
  20872. ssize_t n;
  20873. bool got_error = false;
  20874. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20875. total += n;
  20876. }
  20877. if (n < 0) {
  20878. got_error = true;
  20879. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20880. handle.get_read_error() == Error::Read)
  20881. << "Actual error: " << to_string(handle.get_read_error());
  20882. }
  20883. EXPECT_TRUE(got_error || total < 1000)
  20884. << "Expected timeout but got all " << total << " bytes";
  20885. svr.stop();
  20886. t.join();
  20887. }
  20888. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20889. // Test SSL connection closed detection
  20890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20891. std::atomic<bool> close_now{false};
  20892. svr.Get("/will-close", [&](const Request &, Response &res) {
  20893. res.set_content_provider(
  20894. 10000, "text/plain",
  20895. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20896. if (offset < 100) {
  20897. std::string data(100, 'X');
  20898. sink.write(data.c_str(), data.size());
  20899. return true;
  20900. }
  20901. while (!close_now) {
  20902. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20903. }
  20904. return false;
  20905. });
  20906. });
  20907. auto port = 8094;
  20908. std::thread t([&]() { svr.listen("localhost", port); });
  20909. svr.wait_until_ready();
  20910. SSLClient cli("localhost", port);
  20911. cli.enable_server_certificate_verification(false);
  20912. auto handle = cli.open_stream("GET", "/will-close");
  20913. ASSERT_TRUE(handle.is_valid());
  20914. char buf[256];
  20915. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20916. EXPECT_GT(n, 0);
  20917. // Signal server to close
  20918. close_now = true;
  20919. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20920. // Keep reading
  20921. }
  20922. if (n < 0) {
  20923. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20924. handle.get_read_error() == Error::Read)
  20925. << "Actual error: " << to_string(handle.get_read_error());
  20926. }
  20927. svr.stop();
  20928. t.join();
  20929. }
  20930. #endif
  20931. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20932. using namespace httplib;
  20933. // Create a test file
  20934. const char *fname = "etag_testfile.txt";
  20935. const char *content = "etag-content";
  20936. {
  20937. std::ofstream ofs(fname);
  20938. ofs << content;
  20939. ASSERT_TRUE(ofs.good());
  20940. }
  20941. Server svr;
  20942. svr.set_mount_point("/static", ".");
  20943. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20944. svr.wait_until_ready();
  20945. Client cli(HOST, PORT);
  20946. // First request: should get 200 with ETag header
  20947. auto res1 = cli.Get("/static/etag_testfile.txt");
  20948. ASSERT_TRUE(res1);
  20949. ASSERT_EQ(200, res1->status);
  20950. ASSERT_TRUE(res1->has_header("ETag"));
  20951. std::string etag = res1->get_header_value("ETag");
  20952. EXPECT_FALSE(etag.empty());
  20953. // Verify ETag format: W/"hex-hex"
  20954. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20955. EXPECT_EQ('W', etag[0]);
  20956. EXPECT_EQ('/', etag[1]);
  20957. EXPECT_EQ('"', etag[2]);
  20958. EXPECT_EQ('"', etag.back());
  20959. // Exact match: expect 304 Not Modified
  20960. Headers h2 = {{"If-None-Match", etag}};
  20961. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20962. ASSERT_TRUE(res2);
  20963. EXPECT_EQ(304, res2->status);
  20964. // Wildcard match: expect 304 Not Modified
  20965. Headers h3 = {{"If-None-Match", "*"}};
  20966. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20967. ASSERT_TRUE(res3);
  20968. EXPECT_EQ(304, res3->status);
  20969. // Non-matching ETag: expect 200
  20970. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20971. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20972. ASSERT_TRUE(res4);
  20973. EXPECT_EQ(200, res4->status);
  20974. // Multiple ETags with one matching: expect 304
  20975. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20976. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20977. ASSERT_TRUE(res5);
  20978. EXPECT_EQ(304, res5->status);
  20979. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20980. // that equivalent to the single comma-separated list above, so the match on
  20981. // the second line must still be found.
  20982. Headers h6;
  20983. h6.emplace("If-None-Match", "W/\"other\"");
  20984. h6.emplace("If-None-Match", etag);
  20985. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20986. ASSERT_TRUE(res6);
  20987. EXPECT_EQ(304, res6->status);
  20988. svr.stop();
  20989. t.join();
  20990. std::remove(fname);
  20991. }
  20992. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20993. using namespace httplib;
  20994. Server svr;
  20995. svr.set_mount_point("/static", ".");
  20996. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20997. svr.wait_until_ready();
  20998. Client cli(HOST, PORT);
  20999. // Send If-None-Match: * to a non-existent file
  21000. Headers h = {{"If-None-Match", "*"}};
  21001. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21003. EXPECT_EQ(404, res->status);
  21004. svr.stop();
  21005. t.join();
  21006. }
  21007. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21008. using namespace httplib;
  21009. // Create a test file
  21010. const char *fname = "etag_boundary_testfile.txt";
  21011. const char *content = "boundary-test";
  21012. {
  21013. std::ofstream ofs(fname);
  21014. ofs << content;
  21015. ASSERT_TRUE(ofs.good());
  21016. }
  21017. Server svr;
  21018. svr.set_mount_point("/static", ".");
  21019. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21020. svr.wait_until_ready();
  21021. Client cli(HOST, PORT);
  21022. // Get the actual ETag
  21023. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21024. ASSERT_TRUE(res1);
  21025. ASSERT_EQ(200, res1->status);
  21026. ASSERT_TRUE(res1->has_header("ETag"));
  21027. std::string etag = res1->get_header_value("ETag");
  21028. // Test 1: Very long ETag value (longer than actual ETag)
  21029. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21030. Headers h1 = {{"If-None-Match", "W/"
  21031. "\"very-long-etag-value-that-is-much-longer-"
  21032. "than-the-actual-etag-value\""}};
  21033. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21034. ASSERT_TRUE(res2);
  21035. EXPECT_EQ(200, res2->status); // Should not match
  21036. // Test 2: Long string followed by wildcard
  21037. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21038. // string)
  21039. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21040. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21041. ASSERT_TRUE(res3);
  21042. EXPECT_EQ(304, res3->status); // Should match on "*"
  21043. // Test 3: Wildcard followed by long string
  21044. // Should match on "*" immediately and return 304
  21045. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21046. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21047. ASSERT_TRUE(res4);
  21048. EXPECT_EQ(304, res4->status); // Should match on "*"
  21049. // Test 4: Multiple long non-matching values
  21050. // Should NOT match and return 200 (test that all comparisons are safe)
  21051. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21052. "W/\"second-long-non-matching-value\", "
  21053. "W/\"third-long-non-matching-value\""}};
  21054. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21055. ASSERT_TRUE(res5);
  21056. EXPECT_EQ(200, res5->status); // Should not match
  21057. // Test 5: Single character that is not "*" (edge case)
  21058. Headers h5 = {{"If-None-Match", "X"}};
  21059. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21060. ASSERT_TRUE(res6);
  21061. EXPECT_EQ(200, res6->status); // Should not match
  21062. svr.stop();
  21063. t.join();
  21064. std::remove(fname);
  21065. }
  21066. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21067. using namespace httplib;
  21068. // Create a test file
  21069. const char *fname = "ims_testfile.txt";
  21070. const char *content = "if-modified-since-test";
  21071. {
  21072. std::ofstream ofs(fname);
  21073. ofs << content;
  21074. ASSERT_TRUE(ofs.good());
  21075. }
  21076. Server svr;
  21077. svr.set_mount_point("/static", ".");
  21078. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21079. svr.wait_until_ready();
  21080. Client cli(HOST, PORT);
  21081. // First request: should get 200 with Last-Modified header
  21082. auto res1 = cli.Get("/static/ims_testfile.txt");
  21083. ASSERT_TRUE(res1);
  21084. ASSERT_EQ(200, res1->status);
  21085. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21086. std::string last_modified = res1->get_header_value("Last-Modified");
  21087. EXPECT_FALSE(last_modified.empty());
  21088. // If-Modified-Since with same time: expect 304
  21089. Headers h2 = {{"If-Modified-Since", last_modified}};
  21090. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21091. ASSERT_TRUE(res2);
  21092. EXPECT_EQ(304, res2->status);
  21093. // If-Modified-Since with future time: expect 304
  21094. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21095. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21096. ASSERT_TRUE(res3);
  21097. EXPECT_EQ(304, res3->status);
  21098. // If-Modified-Since with past time: expect 200
  21099. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21100. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21101. ASSERT_TRUE(res4);
  21102. EXPECT_EQ(200, res4->status);
  21103. // If-None-Match takes precedence over If-Modified-Since
  21104. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21105. ASSERT_TRUE(res1->has_header("ETag"));
  21106. std::string etag = res1->get_header_value("ETag");
  21107. Headers h5 = {{"If-None-Match", etag},
  21108. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21109. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21110. ASSERT_TRUE(res5);
  21111. EXPECT_EQ(304, res5->status);
  21112. svr.stop();
  21113. t.join();
  21114. std::remove(fname);
  21115. }
  21116. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21117. using namespace httplib;
  21118. Server svr;
  21119. // Endpoint that returns compressible content
  21120. svr.Get("/compressible", [](const Request &, Response &res) {
  21121. // Return a large enough body to trigger compression
  21122. std::string body(1000, 'a');
  21123. res.set_content(body, "text/plain");
  21124. });
  21125. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21126. svr.wait_until_ready();
  21127. Client cli(HOST, PORT);
  21128. // Request with gzip support: should get Vary header when compressed
  21129. cli.set_compress(true);
  21130. auto res1 = cli.Get("/compressible");
  21131. ASSERT_TRUE(res1);
  21132. EXPECT_EQ(200, res1->status);
  21133. // If Content-Encoding is set, Vary should also be set
  21134. if (res1->has_header("Content-Encoding")) {
  21135. EXPECT_TRUE(res1->has_header("Vary"));
  21136. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21137. }
  21138. // Request without Accept-Encoding header: should not have compression
  21139. Headers h_no_compress;
  21140. auto res2 = cli.Get("/compressible", h_no_compress);
  21141. ASSERT_TRUE(res2);
  21142. EXPECT_EQ(200, res2->status);
  21143. // Verify Vary header is present when compression is applied
  21144. // (the exact behavior depends on server configuration)
  21145. svr.stop();
  21146. t.join();
  21147. }
  21148. TEST(ETagTest, IfRangeWithETag) {
  21149. using namespace httplib;
  21150. // Create a test file with known content
  21151. const char *fname = "if_range_testfile.txt";
  21152. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21153. {
  21154. std::ofstream ofs(fname);
  21155. ofs << content;
  21156. ASSERT_TRUE(ofs.good());
  21157. }
  21158. Server svr;
  21159. svr.set_mount_point("/static", ".");
  21160. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21161. svr.wait_until_ready();
  21162. Client cli(HOST, PORT);
  21163. // First request: get ETag
  21164. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21165. ASSERT_TRUE(res1);
  21166. ASSERT_EQ(200, res1->status);
  21167. ASSERT_TRUE(res1->has_header("ETag"));
  21168. std::string etag = res1->get_header_value("ETag");
  21169. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21170. // Since our server generates weak ETags (W/"..."), If-Range with our
  21171. // ETag should NOT result in partial content - it should return full content.
  21172. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21173. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21174. ASSERT_TRUE(res2);
  21175. // Weak ETag in If-Range -> full content (200), not partial (206)
  21176. EXPECT_EQ(200, res2->status);
  21177. EXPECT_EQ(content, res2->body);
  21178. EXPECT_FALSE(res2->has_header("Content-Range"));
  21179. // Range request with non-matching If-Range (ETag): should get 200 (full
  21180. // content)
  21181. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21182. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21183. ASSERT_TRUE(res3);
  21184. EXPECT_EQ(200, res3->status);
  21185. EXPECT_EQ(content, res3->body);
  21186. EXPECT_FALSE(res3->has_header("Content-Range"));
  21187. // Range request with strong ETag (hypothetical - our server doesn't generate
  21188. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21189. // should return full content)
  21190. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21191. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21192. ASSERT_TRUE(res4);
  21193. EXPECT_EQ(200, res4->status);
  21194. EXPECT_EQ(content, res4->body);
  21195. EXPECT_FALSE(res4->has_header("Content-Range"));
  21196. svr.stop();
  21197. t.join();
  21198. std::remove(fname);
  21199. }
  21200. TEST(ETagTest, IfRangeWithDate) {
  21201. using namespace httplib;
  21202. // Create a test file
  21203. const char *fname = "if_range_date_testfile.txt";
  21204. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21205. {
  21206. std::ofstream ofs(fname);
  21207. ofs << content;
  21208. ASSERT_TRUE(ofs.good());
  21209. }
  21210. Server svr;
  21211. svr.set_mount_point("/static", ".");
  21212. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21213. svr.wait_until_ready();
  21214. Client cli(HOST, PORT);
  21215. // First request: get Last-Modified
  21216. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21217. ASSERT_TRUE(res1);
  21218. ASSERT_EQ(200, res1->status);
  21219. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21220. std::string last_modified = res1->get_header_value("Last-Modified");
  21221. // Range request with matching If-Range (date): should get 206
  21222. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21223. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21224. ASSERT_TRUE(res2);
  21225. EXPECT_EQ(206, res2->status);
  21226. EXPECT_EQ("FGHIJ", res2->body);
  21227. // Range request with old If-Range date: should get 200 (full content)
  21228. Headers h3 = {{"Range", "bytes=5-9"},
  21229. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21230. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21231. ASSERT_TRUE(res3);
  21232. EXPECT_EQ(200, res3->status);
  21233. EXPECT_EQ(content, res3->body);
  21234. // Range request with future If-Range date: should get 206
  21235. Headers h4 = {{"Range", "bytes=0-4"},
  21236. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21237. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21238. ASSERT_TRUE(res4);
  21239. EXPECT_EQ(206, res4->status);
  21240. EXPECT_EQ("ABCDE", res4->body);
  21241. svr.stop();
  21242. t.join();
  21243. std::remove(fname);
  21244. }
  21245. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21246. using namespace httplib;
  21247. const char *fname = "etag_malformed.txt";
  21248. const char *content = "malformed-etag";
  21249. {
  21250. std::ofstream ofs(fname);
  21251. ofs << content;
  21252. ASSERT_TRUE(ofs.good());
  21253. }
  21254. Server svr;
  21255. svr.set_mount_point("/static", ".");
  21256. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21257. svr.wait_until_ready();
  21258. Client cli(HOST, PORT);
  21259. // baseline: should get 200 and an ETag
  21260. auto res1 = cli.Get("/static/etag_malformed.txt");
  21261. ASSERT_TRUE(res1);
  21262. ASSERT_EQ(200, res1->status);
  21263. ASSERT_TRUE(res1->has_header("ETag"));
  21264. // Malformed ETag value (missing quotes) should be treated as non-matching
  21265. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21266. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21267. ASSERT_TRUE(res_bad);
  21268. EXPECT_EQ(200, res_bad->status);
  21269. // Whitespace-only header value should be considered invalid / non-matching
  21270. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21271. "Host: localhost\r\n"
  21272. "If-None-Match: \r\n"
  21273. "Connection: close\r\n"
  21274. "\r\n";
  21275. std::string out;
  21276. ASSERT_TRUE(send_request(5, raw_req, &out));
  21277. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21278. svr.stop();
  21279. t.join();
  21280. std::remove(fname);
  21281. }
  21282. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21283. using namespace httplib;
  21284. const char *fname = "ims_invalid_format.txt";
  21285. const char *content = "ims-bad-format";
  21286. {
  21287. std::ofstream ofs(fname);
  21288. ofs << content;
  21289. ASSERT_TRUE(ofs.good());
  21290. }
  21291. Server svr;
  21292. svr.set_mount_point("/static", ".");
  21293. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21294. svr.wait_until_ready();
  21295. Client cli(HOST, PORT);
  21296. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21297. ASSERT_TRUE(res1);
  21298. ASSERT_EQ(200, res1->status);
  21299. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21300. // If-Modified-Since with invalid format should not result in 304
  21301. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21302. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21303. ASSERT_TRUE(res_bad);
  21304. EXPECT_EQ(200, res_bad->status);
  21305. // If-Range with invalid date format should be treated as mismatch -> full
  21306. // content (200)
  21307. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21308. {"If-Range", "invalid-date"}};
  21309. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21310. ASSERT_TRUE(res_ifrange);
  21311. EXPECT_EQ(200, res_ifrange->status);
  21312. svr.stop();
  21313. t.join();
  21314. std::remove(fname);
  21315. }
  21316. TEST(ETagTest, IfRangeWithMalformedETag) {
  21317. using namespace httplib;
  21318. const char *fname = "ifrange_malformed.txt";
  21319. const std::string content = "0123456789";
  21320. {
  21321. std::ofstream ofs(fname);
  21322. ofs << content;
  21323. ASSERT_TRUE(ofs.good());
  21324. }
  21325. Server svr;
  21326. svr.set_mount_point("/static", ".");
  21327. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21328. svr.wait_until_ready();
  21329. Client cli(HOST, PORT);
  21330. // First request: get ETag
  21331. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21332. ASSERT_TRUE(res1);
  21333. ASSERT_EQ(200, res1->status);
  21334. ASSERT_TRUE(res1->has_header("ETag"));
  21335. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21336. // full content (200)
  21337. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21338. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21339. ASSERT_TRUE(res2);
  21340. EXPECT_EQ(200, res2->status);
  21341. EXPECT_EQ(content, res2->body);
  21342. svr.stop();
  21343. t.join();
  21344. std::remove(fname);
  21345. }
  21346. TEST(ETagTest, ExtremeLargeDateValues) {
  21347. using namespace httplib;
  21348. const char *fname = "ims_extreme_date.txt";
  21349. const char *content = "ims-extreme-date";
  21350. {
  21351. std::ofstream ofs(fname);
  21352. ofs << content;
  21353. ASSERT_TRUE(ofs.good());
  21354. }
  21355. Server svr;
  21356. svr.set_mount_point("/static", ".");
  21357. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21358. svr.wait_until_ready();
  21359. Client cli(HOST, PORT);
  21360. auto res1 = cli.Get(std::string("/static/") + fname);
  21361. ASSERT_TRUE(res1);
  21362. ASSERT_EQ(200, res1->status);
  21363. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21364. // Extremely large year that may overflow date parsing routines.
  21365. Headers h_large_date = {
  21366. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21367. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21368. ASSERT_TRUE(res_bad);
  21369. // Expect server to treat this as invalid/mismatch and return full content
  21370. EXPECT_EQ(200, res_bad->status);
  21371. // If-Range with extremely large date should be treated as mismatch -> full
  21372. // content (200)
  21373. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21374. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21375. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21376. ASSERT_TRUE(res_ifrange);
  21377. EXPECT_EQ(200, res_ifrange->status);
  21378. svr.stop();
  21379. t.join();
  21380. std::remove(fname);
  21381. }
  21382. TEST(ETagTest, NegativeFileModificationTime) {
  21383. using namespace httplib;
  21384. const char *fname = "ims_negative_mtime.txt";
  21385. const std::string content = "negative-mtime";
  21386. {
  21387. std::ofstream ofs(fname);
  21388. ofs << content;
  21389. ASSERT_TRUE(ofs.good());
  21390. }
  21391. // Try to set file mtime to a negative value. This may fail on some
  21392. // platforms/filesystems; if it fails, the test will still verify server
  21393. // behaves safely by performing a regular conditional request.
  21394. #if defined(__APPLE__) || defined(__linux__)
  21395. bool set_negative = false;
  21396. do {
  21397. struct timeval times[2];
  21398. // access time: now
  21399. times[0].tv_sec = time(nullptr);
  21400. times[0].tv_usec = 0;
  21401. // modification time: negative (e.g., -1)
  21402. times[1].tv_sec = -1;
  21403. times[1].tv_usec = 0;
  21404. if (utimes(fname, times) == 0) { set_negative = true; }
  21405. } while (0);
  21406. #else
  21407. bool set_negative = false;
  21408. #endif
  21409. Server svr;
  21410. svr.set_mount_point("/static", ".");
  21411. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21412. svr.wait_until_ready();
  21413. Client cli(HOST, PORT);
  21414. auto res1 = cli.Get(std::string("/static/") + fname);
  21415. ASSERT_TRUE(res1);
  21416. ASSERT_EQ(200, res1->status);
  21417. bool has_last_modified = res1->has_header("Last-Modified");
  21418. std::string last_modified;
  21419. if (has_last_modified) {
  21420. last_modified = res1->get_header_value("Last-Modified");
  21421. }
  21422. if (set_negative) {
  21423. // If we successfully set a negative mtime, ensure server returns a
  21424. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21425. // with an old date and ensure server handles it without crash.
  21426. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21427. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21428. ASSERT_TRUE(res2);
  21429. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21430. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21431. } else {
  21432. // Could not set negative mtime on this platform; fall back to verifying
  21433. // that normal invalid/malformed dates are treated safely (non-304).
  21434. Headers h_bad_date = {
  21435. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21436. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21437. ASSERT_TRUE(res_bad);
  21438. EXPECT_EQ(200, res_bad->status);
  21439. }
  21440. svr.stop();
  21441. t.join();
  21442. std::remove(fname);
  21443. }
  21444. //==============================================================================
  21445. // Integration Tests with Server
  21446. //==============================================================================
  21447. class SSEIntegrationTest : public ::testing::Test {
  21448. protected:
  21449. void SetUp() override {
  21450. stop_server_.store(false);
  21451. events_.clear();
  21452. server_ = httplib::detail::make_unique<Server>();
  21453. setup_server();
  21454. start_server();
  21455. }
  21456. void TearDown() override {
  21457. stop_server_.store(true);
  21458. event_cv_.notify_all();
  21459. server_->stop();
  21460. if (server_thread_.joinable()) { server_thread_.join(); }
  21461. }
  21462. void setup_server() {
  21463. // Simple SSE endpoint
  21464. server_->Get("/events", [this](const Request &req, Response &res) {
  21465. auto last_id = req.get_header_value("Last-Event-ID");
  21466. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21467. res.set_chunked_content_provider(
  21468. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21469. std::unique_lock<std::mutex> lock(event_mutex_);
  21470. if (event_cv_.wait_for(
  21471. lock, std::chrono::milliseconds(200), [this] {
  21472. return !events_.empty() || stop_server_.load();
  21473. })) {
  21474. if (stop_server_.load()) { return false; }
  21475. if (!events_.empty()) {
  21476. std::string event = events_.front();
  21477. events_.erase(events_.begin());
  21478. sink.write(event.data(), event.size());
  21479. return true;
  21480. }
  21481. }
  21482. return !stop_server_.load();
  21483. });
  21484. });
  21485. // Endpoint that returns error
  21486. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21487. res.status = 500;
  21488. res.set_content("Internal Server Error", "text/plain");
  21489. });
  21490. // Endpoint for custom event types
  21491. server_->Get("/custom-events", [](const Request &, Response &res) {
  21492. res.set_chunked_content_provider(
  21493. "text/event-stream", [](size_t offset, DataSink &sink) {
  21494. if (offset == 0) {
  21495. std::string event = "event: update\ndata: updated\n\n"
  21496. "event: delete\ndata: deleted\n\n";
  21497. sink.write(event.data(), event.size());
  21498. }
  21499. return false; // End stream after sending
  21500. });
  21501. });
  21502. }
  21503. void start_server() {
  21504. port_ = server_->bind_to_any_port(HOST);
  21505. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21506. // Wait for server to start
  21507. while (!server_->is_running()) {
  21508. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21509. }
  21510. }
  21511. int get_port() const { return port_; }
  21512. void send_event(const std::string &event) {
  21513. std::lock_guard<std::mutex> lock(event_mutex_);
  21514. events_.push_back(event);
  21515. event_cv_.notify_all();
  21516. }
  21517. std::unique_ptr<Server> server_;
  21518. std::thread server_thread_;
  21519. std::mutex event_mutex_;
  21520. std::condition_variable event_cv_;
  21521. std::vector<std::string> events_;
  21522. std::atomic<bool> stop_server_{false};
  21523. std::string last_received_event_id_;
  21524. int port_ = 0;
  21525. };
  21526. //==============================================================================
  21527. // SSE Parsing Tests
  21528. //==============================================================================
  21529. class SSEParsingTest : public SSEIntegrationTest {
  21530. protected:
  21531. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21532. // A trailing sentinel event tells when the whole stream has been parsed.
  21533. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21534. auto body = stream + "event: end\ndata: end\n\n";
  21535. server_->Get("/parse", [body](const Request &, Response &res) {
  21536. res.set_content(body, "text/event-stream");
  21537. });
  21538. return collect("/parse");
  21539. }
  21540. // Runs SSEClient against path until an "end" event arrives and returns the
  21541. // messages dispatched before it
  21542. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21543. Client client(HOST, get_port());
  21544. sse::SSEClient sse(client, path);
  21545. std::mutex mutex;
  21546. std::condition_variable cv;
  21547. std::vector<sse::SSEMessage> messages;
  21548. auto done = false;
  21549. sse.on_message([&](const sse::SSEMessage &msg) {
  21550. std::lock_guard<std::mutex> lock(mutex);
  21551. // Ignore a replay from a reconnect that races with stop()
  21552. if (!done) { messages.push_back(msg); }
  21553. });
  21554. sse.on_event("end", [&](const sse::SSEMessage &) {
  21555. std::lock_guard<std::mutex> lock(mutex);
  21556. done = true;
  21557. cv.notify_all();
  21558. });
  21559. sse.set_reconnect_interval(100);
  21560. sse.start_async();
  21561. {
  21562. std::unique_lock<std::mutex> lock(mutex);
  21563. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21564. }
  21565. sse.stop();
  21566. EXPECT_TRUE(done);
  21567. return messages;
  21568. }
  21569. };
  21570. TEST_F(SSEParsingTest, SingleLineData) {
  21571. auto msgs = parse("data: hello\n\n");
  21572. ASSERT_EQ(msgs.size(), 1u);
  21573. EXPECT_EQ(msgs[0].data, "hello");
  21574. EXPECT_EQ(msgs[0].event, "message");
  21575. }
  21576. TEST_F(SSEParsingTest, MultiLineData) {
  21577. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21578. ASSERT_EQ(msgs.size(), 1u);
  21579. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21580. }
  21581. TEST_F(SSEParsingTest, CustomEventType) {
  21582. auto msgs = parse("event: update\ndata: payload\n\n");
  21583. ASSERT_EQ(msgs.size(), 1u);
  21584. EXPECT_EQ(msgs[0].event, "update");
  21585. EXPECT_EQ(msgs[0].data, "payload");
  21586. }
  21587. TEST_F(SSEParsingTest, EventIdHandling) {
  21588. auto msgs = parse("id: 12345\ndata: test\n\n");
  21589. ASSERT_EQ(msgs.size(), 1u);
  21590. EXPECT_EQ(msgs[0].id, "12345");
  21591. }
  21592. TEST_F(SSEParsingTest, EmptyEventId) {
  21593. auto msgs = parse("id:\ndata: test\n\n");
  21594. ASSERT_EQ(msgs.size(), 1u);
  21595. EXPECT_EQ(msgs[0].id, "");
  21596. }
  21597. TEST_F(SSEParsingTest, CommentsIgnored) {
  21598. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21599. ASSERT_EQ(msgs.size(), 1u);
  21600. EXPECT_EQ(msgs[0].data, "hello");
  21601. EXPECT_EQ(msgs[0].event, "message");
  21602. }
  21603. TEST_F(SSEParsingTest, ColonInValue) {
  21604. auto msgs = parse("data: hello:world:test\n\n");
  21605. ASSERT_EQ(msgs.size(), 1u);
  21606. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21607. }
  21608. TEST_F(SSEParsingTest, FieldNameOnly) {
  21609. // A line without a colon is a field name with an empty value
  21610. auto msgs = parse("data\n\n");
  21611. ASSERT_EQ(msgs.size(), 1u);
  21612. EXPECT_EQ(msgs[0].data, "");
  21613. }
  21614. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21615. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21616. ASSERT_EQ(msgs.size(), 1u);
  21617. EXPECT_EQ(msgs[0].event, "update");
  21618. EXPECT_EQ(msgs[0].data, "hello");
  21619. }
  21620. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21621. auto msgs = parse("data\r\n\r\n");
  21622. ASSERT_EQ(msgs.size(), 1u);
  21623. EXPECT_EQ(msgs[0].data, "");
  21624. }
  21625. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21626. auto msgs = parse("event: update\rdata: hello\r\r");
  21627. ASSERT_EQ(msgs.size(), 1u);
  21628. EXPECT_EQ(msgs[0].event, "update");
  21629. EXPECT_EQ(msgs[0].data, "hello");
  21630. }
  21631. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21632. // Chunk boundaries fall inside every \r\n and right before the first one
  21633. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21634. "\n\r", "\nevent: end\ndata: end\n\n"};
  21635. server_->Get("/split", [chunks](const Request &, Response &res) {
  21636. auto i = std::make_shared<size_t>(0);
  21637. res.set_chunked_content_provider(
  21638. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21639. if (*i == chunks.size()) {
  21640. sink.done();
  21641. } else {
  21642. sink.write(chunks[*i].data(), chunks[*i].size());
  21643. (*i)++;
  21644. }
  21645. return true;
  21646. });
  21647. });
  21648. auto msgs = collect("/split");
  21649. ASSERT_EQ(msgs.size(), 1u);
  21650. EXPECT_EQ(msgs[0].event, "update");
  21651. EXPECT_EQ(msgs[0].data, "hello");
  21652. }
  21653. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21654. // Only a BOM at the start of the stream is ignored
  21655. auto msgs = parse("\xEF\xBB\xBF"
  21656. "data: first\n\n"
  21657. "\xEF\xBB\xBF"
  21658. "data: second\n\n");
  21659. ASSERT_EQ(msgs.size(), 1u);
  21660. EXPECT_EQ(msgs[0].data, "first");
  21661. }
  21662. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21663. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21664. ASSERT_EQ(msgs.size(), 1u);
  21665. EXPECT_EQ(msgs[0].data, "hello");
  21666. EXPECT_EQ(msgs[0].event, "message");
  21667. }
  21668. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21669. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21670. ASSERT_EQ(msgs.size(), 2u);
  21671. EXPECT_EQ(msgs[0].data, "hello");
  21672. EXPECT_EQ(msgs[1].data, "hello");
  21673. }
  21674. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21675. // An event without data is not dispatched, and its type must not leak
  21676. // into the next event
  21677. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21678. ASSERT_EQ(msgs.size(), 1u);
  21679. EXPECT_EQ(msgs[0].event, "message");
  21680. EXPECT_EQ(msgs[0].data, "hello");
  21681. }
  21682. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21683. // Also when the empty field replaces an earlier type
  21684. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21685. ASSERT_EQ(msgs.size(), 2u);
  21686. EXPECT_EQ(msgs[0].event, "message");
  21687. EXPECT_EQ(msgs[1].event, "message");
  21688. }
  21689. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21690. // The first connection sends only an id; the second echoes back the
  21691. // Last-Event-ID it was reconnected with
  21692. std::atomic<int> connection_count{0};
  21693. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21694. if (connection_count++ == 0) {
  21695. res.set_content("id: 42\n\n", "text/event-stream");
  21696. } else {
  21697. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21698. "\n\nevent: end\ndata: end\n\n",
  21699. "text/event-stream");
  21700. }
  21701. });
  21702. auto msgs = collect("/id-only");
  21703. ASSERT_EQ(msgs.size(), 1u);
  21704. EXPECT_EQ(msgs[0].data, "42");
  21705. }
  21706. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21707. // The first connection sets an id and then clears it with an empty one; the
  21708. // second reports whether it was reconnected with a Last-Event-ID
  21709. std::atomic<int> connection_count{0};
  21710. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21711. if (connection_count++ == 0) {
  21712. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21713. "text/event-stream");
  21714. } else {
  21715. res.set_content(
  21716. std::string("data: ") +
  21717. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21718. "\n\nevent: end\ndata: end\n\n",
  21719. "text/event-stream");
  21720. }
  21721. });
  21722. auto msgs = collect("/id-clear");
  21723. ASSERT_EQ(msgs.size(), 3u);
  21724. EXPECT_EQ(msgs[0].id, "1");
  21725. EXPECT_EQ(msgs[1].id, "");
  21726. EXPECT_EQ(msgs[2].data, "not sent");
  21727. }
  21728. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21729. // The first connection sets an id and then sends ids that cannot be carried
  21730. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21731. // with
  21732. std::atomic<int> connection_count{0};
  21733. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21734. if (connection_count++ == 0) {
  21735. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21736. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21737. "text/event-stream");
  21738. } else {
  21739. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21740. "\n\nevent: end\ndata: end\n\n",
  21741. "text/event-stream");
  21742. }
  21743. });
  21744. auto msgs = collect("/id-unsendable");
  21745. ASSERT_EQ(msgs.size(), 1u);
  21746. EXPECT_EQ(msgs[0].data, "42");
  21747. }
  21748. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21749. auto msgs = parse("event: notification\nid: evt-42\n"
  21750. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21751. ASSERT_EQ(msgs.size(), 1u);
  21752. EXPECT_EQ(msgs[0].event, "notification");
  21753. EXPECT_EQ(msgs[0].id, "evt-42");
  21754. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21755. }
  21756. TEST(SSEMessageTest, Clear) {
  21757. sse::SSEMessage msg;
  21758. msg.event = "custom";
  21759. msg.data = "some data";
  21760. msg.id = "123";
  21761. msg.clear();
  21762. EXPECT_EQ(msg.event, "message");
  21763. EXPECT_EQ(msg.data, "");
  21764. EXPECT_EQ(msg.id, "");
  21765. }
  21766. //==============================================================================
  21767. // SSE Integration Tests
  21768. //==============================================================================
  21769. // Test: Successful connection and on_open callback
  21770. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21771. // Add a simple endpoint that sends one event and closes
  21772. server_->Get("/simple-event", [](const Request &, Response &res) {
  21773. res.set_chunked_content_provider(
  21774. "text/event-stream", [](size_t offset, DataSink &sink) {
  21775. if (offset == 0) {
  21776. std::string event = "data: hello\n\n";
  21777. sink.write(event.data(), event.size());
  21778. }
  21779. return false; // Close stream after sending
  21780. });
  21781. });
  21782. Client client("localhost", get_port());
  21783. sse::SSEClient sse(client, "/simple-event");
  21784. std::atomic<bool> open_called{false};
  21785. std::atomic<bool> message_received{false};
  21786. sse.on_open([&open_called]() { open_called.store(true); });
  21787. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21788. if (msg.data == "hello") { message_received.store(true); }
  21789. });
  21790. sse.set_reconnect_interval(100);
  21791. sse.set_max_reconnect_attempts(1);
  21792. // Start async
  21793. sse.start_async();
  21794. // Wait for message to be processed
  21795. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21796. sse.stop();
  21797. EXPECT_TRUE(open_called.load());
  21798. EXPECT_TRUE(message_received.load());
  21799. }
  21800. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21801. // A data line that never ends.
  21802. server_->Get("/endless-line", [](const Request &, Response &res) {
  21803. res.set_chunked_content_provider(
  21804. "text/event-stream", [](size_t offset, DataSink &sink) {
  21805. if (offset == 0) { sink.write("data: ", 6); }
  21806. std::string chunk(64 * 1024, 'A');
  21807. return sink.write(chunk.data(), chunk.size());
  21808. });
  21809. });
  21810. Client client("localhost", get_port());
  21811. sse::SSEClient sse(client, "/endless-line");
  21812. std::atomic<bool> too_long{false};
  21813. sse.on_error([&](Error err) {
  21814. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21815. });
  21816. sse.set_max_reconnect_attempts(1);
  21817. sse.start_async();
  21818. for (int i = 0; i < 500 && !too_long; i++) {
  21819. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21820. }
  21821. sse.stop();
  21822. EXPECT_TRUE(too_long);
  21823. }
  21824. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21825. // Far more in all than the client's payload limit below.
  21826. server_->Get("/many-events", [](const Request &, Response &res) {
  21827. res.set_chunked_content_provider(
  21828. "text/event-stream", [](size_t offset, DataSink &sink) {
  21829. if (offset == 0) {
  21830. std::string events;
  21831. for (int i = 0; i < 1000; i++) {
  21832. events += "data: message\n\n";
  21833. }
  21834. sink.write(events.data(), events.size());
  21835. }
  21836. return false;
  21837. });
  21838. });
  21839. Client client("localhost", get_port());
  21840. client.set_payload_max_length(1024);
  21841. sse::SSEClient sse(client, "/many-events");
  21842. std::atomic<int> messages{0};
  21843. std::atomic<bool> too_large{false};
  21844. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21845. sse.on_error([&](Error err) {
  21846. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21847. });
  21848. sse.set_max_reconnect_attempts(1);
  21849. sse.start_async();
  21850. for (int i = 0; i < 500 && messages < 1000; i++) {
  21851. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21852. }
  21853. sse.stop();
  21854. EXPECT_GE(messages.load(), 1000);
  21855. EXPECT_FALSE(too_large);
  21856. }
  21857. // Test: on_message callback
  21858. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21859. // Endpoint that sends multiple events then closes
  21860. server_->Get("/multi-event", [](const Request &, Response &res) {
  21861. res.set_chunked_content_provider(
  21862. "text/event-stream", [](size_t offset, DataSink &sink) {
  21863. if (offset == 0) {
  21864. std::string events = "data: message1\n\ndata: message2\n\n";
  21865. sink.write(events.data(), events.size());
  21866. }
  21867. return false;
  21868. });
  21869. });
  21870. Client client("localhost", get_port());
  21871. sse::SSEClient sse(client, "/multi-event");
  21872. std::vector<std::string> received_messages;
  21873. std::mutex messages_mutex;
  21874. sse.on_message([&](const sse::SSEMessage &msg) {
  21875. std::lock_guard<std::mutex> lock(messages_mutex);
  21876. received_messages.push_back(msg.data);
  21877. });
  21878. sse.set_reconnect_interval(100);
  21879. sse.set_max_reconnect_attempts(1);
  21880. sse.start_async();
  21881. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21882. sse.stop();
  21883. std::lock_guard<std::mutex> lock(messages_mutex);
  21884. EXPECT_GE(received_messages.size(), 2u);
  21885. if (received_messages.size() >= 2) {
  21886. EXPECT_EQ(received_messages[0], "message1");
  21887. EXPECT_EQ(received_messages[1], "message2");
  21888. }
  21889. }
  21890. // Test: on_event for specific types
  21891. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21892. Client client("localhost", get_port());
  21893. sse::SSEClient sse(client, "/custom-events");
  21894. std::atomic<bool> update_received{false};
  21895. std::atomic<bool> delete_received{false};
  21896. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21897. if (msg.data == "updated") { update_received.store(true); }
  21898. });
  21899. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21900. if (msg.data == "deleted") { delete_received.store(true); }
  21901. });
  21902. sse.set_max_reconnect_attempts(1);
  21903. sse.start_async();
  21904. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21905. sse.stop();
  21906. EXPECT_TRUE(update_received.load());
  21907. EXPECT_TRUE(delete_received.load());
  21908. }
  21909. // Test: on_error callback on connection failure
  21910. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21911. // Connect to a non-existent port
  21912. Client client("localhost", 59999);
  21913. sse::SSEClient sse(client, "/events");
  21914. std::atomic<bool> error_called{false};
  21915. Error received_error = Error::Success;
  21916. sse.on_error([&](Error err) {
  21917. error_called.store(true);
  21918. received_error = err;
  21919. });
  21920. sse.set_reconnect_interval(50);
  21921. sse.set_max_reconnect_attempts(1);
  21922. sse.start_async();
  21923. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21924. sse.stop();
  21925. EXPECT_TRUE(error_called.load());
  21926. EXPECT_NE(received_error, Error::Success);
  21927. }
  21928. // Test: Last-Event-ID header sent on reconnect
  21929. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21930. // Endpoint that sends event with ID
  21931. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21932. res.set_chunked_content_provider(
  21933. "text/event-stream", [](size_t offset, DataSink &sink) {
  21934. if (offset == 0) {
  21935. std::string event = "id: evt-123\ndata: test\n\n";
  21936. sink.write(event.data(), event.size());
  21937. }
  21938. return false;
  21939. });
  21940. });
  21941. Client client("localhost", get_port());
  21942. sse::SSEClient sse(client, "/event-with-id");
  21943. std::atomic<bool> id_received{false};
  21944. sse.on_message([&](const sse::SSEMessage &msg) {
  21945. if (!msg.id.empty()) { id_received.store(true); }
  21946. });
  21947. sse.set_reconnect_interval(100);
  21948. sse.set_max_reconnect_attempts(1);
  21949. sse.start_async();
  21950. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21951. sse.stop();
  21952. EXPECT_TRUE(id_received.load());
  21953. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21954. }
  21955. // Test: Manual stop
  21956. TEST_F(SSEIntegrationTest, ManualStop) {
  21957. // Endpoint that sends one event and stays open briefly. The server outlives
  21958. // this test body, so the provider uses the fixture's flag, not a local.
  21959. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21960. res.set_chunked_content_provider(
  21961. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21962. if (offset == 0) {
  21963. std::string event = "data: connected\n\n";
  21964. sink.write(event.data(), event.size());
  21965. }
  21966. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21967. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21968. }
  21969. return false;
  21970. });
  21971. });
  21972. Client client("localhost", get_port());
  21973. sse::SSEClient sse(client, "/stay-open");
  21974. std::atomic<bool> connected{false};
  21975. sse.on_open([&connected]() { connected.store(true); });
  21976. sse.set_reconnect_interval(100);
  21977. sse.set_max_reconnect_attempts(1);
  21978. sse.start_async();
  21979. // Wait for connection to establish
  21980. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21981. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21982. }
  21983. EXPECT_TRUE(connected.load());
  21984. EXPECT_TRUE(sse.is_connected());
  21985. // Signal handler to stop
  21986. stop_server_.store(true);
  21987. // Stop SSE client
  21988. sse.stop();
  21989. EXPECT_FALSE(sse.is_connected());
  21990. }
  21991. // Sends one event, then nothing until stop is set
  21992. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21993. return [&stop](const Request &, Response &res) {
  21994. res.set_chunked_content_provider(
  21995. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21996. if (offset == 0) {
  21997. std::string event = "data: hello\n\n";
  21998. sink.write(event.data(), event.size());
  21999. }
  22000. while (!stop.load()) {
  22001. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22002. }
  22003. return false;
  22004. });
  22005. };
  22006. }
  22007. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22008. static void check_stop_interrupts_blocked_read(Client &client) {
  22009. client.set_read_timeout(30, 0);
  22010. for (auto by_destructor : {false, true}) {
  22011. std::atomic<bool> received{false};
  22012. std::chrono::steady_clock::time_point start;
  22013. {
  22014. sse::SSEClient sse(client, "/idle-stream");
  22015. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22016. sse.start_async();
  22017. for (int i = 0; i < 500 && !received.load(); ++i) {
  22018. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22019. }
  22020. ASSERT_TRUE(received.load());
  22021. // Let the client block in the next read
  22022. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22023. start = std::chrono::steady_clock::now();
  22024. if (!by_destructor) { sse.stop(); }
  22025. }
  22026. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22027. std::chrono::seconds(2));
  22028. }
  22029. }
  22030. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22031. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22032. Client client("localhost", get_port());
  22033. check_stop_interrupts_blocked_read(client);
  22034. }
  22035. #ifdef CPPHTTPLIB_SSL_ENABLED
  22036. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22037. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22038. std::atomic<bool> done{false};
  22039. svr.Get("/idle-stream", idle_event_stream(done));
  22040. auto port = svr.bind_to_any_port(HOST);
  22041. std::thread t([&] { svr.listen_after_bind(); });
  22042. auto se = detail::scope_exit([&] {
  22043. done.store(true);
  22044. svr.stop();
  22045. t.join();
  22046. });
  22047. svr.wait_until_ready();
  22048. Client client("https://localhost:" + std::to_string(port));
  22049. client.enable_server_certificate_verification(false);
  22050. check_stop_interrupts_blocked_read(client);
  22051. }
  22052. #endif
  22053. // Test: SSEClient with custom headers
  22054. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22055. // Setup a server endpoint that checks for custom header
  22056. std::atomic<bool> header_received{false};
  22057. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22058. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22059. header_received.store(true);
  22060. }
  22061. res.set_chunked_content_provider("text/event-stream",
  22062. [](size_t, DataSink &) { return false; });
  22063. });
  22064. Client client("localhost", get_port());
  22065. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22066. sse::SSEClient sse(client, "/header-check", headers);
  22067. sse.set_max_reconnect_attempts(1);
  22068. sse.start_async();
  22069. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22070. sse.stop();
  22071. EXPECT_TRUE(header_received.load());
  22072. }
  22073. // Test: Reconnect interval configuration
  22074. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22075. Client client("localhost", get_port());
  22076. sse::SSEClient sse(client, "/events");
  22077. auto &result = sse.set_reconnect_interval(500);
  22078. // Builder pattern should return reference to self
  22079. EXPECT_EQ(&result, &sse);
  22080. }
  22081. // Test: Max reconnect attempts
  22082. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22083. // Connect to non-existent port to force reconnects
  22084. Client client("localhost", 59998);
  22085. sse::SSEClient sse(client, "/events");
  22086. std::atomic<int> error_count{0};
  22087. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22088. sse.set_reconnect_interval(50);
  22089. sse.set_max_reconnect_attempts(2);
  22090. auto start = std::chrono::steady_clock::now();
  22091. sse.start(); // Blocking call
  22092. auto end = std::chrono::steady_clock::now();
  22093. // Should have stopped after 2 failed attempts
  22094. EXPECT_GE(error_count.load(), 2);
  22095. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22096. auto duration =
  22097. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22098. #ifdef _WIN32
  22099. // Windows is much slower for socket connection failures
  22100. EXPECT_LT(duration.count(), 7000);
  22101. #else
  22102. EXPECT_LT(duration.count(), 1000);
  22103. #endif
  22104. }
  22105. // Test: Multi-line data in integration
  22106. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22107. // Endpoint with multi-line data
  22108. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22109. res.set_chunked_content_provider(
  22110. "text/event-stream", [](size_t offset, DataSink &sink) {
  22111. if (offset == 0) {
  22112. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22113. sink.write(event.data(), event.size());
  22114. }
  22115. return false;
  22116. });
  22117. });
  22118. Client client("localhost", get_port());
  22119. sse::SSEClient sse(client, "/multiline-data");
  22120. std::string received_data;
  22121. std::mutex data_mutex;
  22122. sse.on_message([&](const sse::SSEMessage &msg) {
  22123. std::lock_guard<std::mutex> lock(data_mutex);
  22124. received_data = msg.data;
  22125. });
  22126. sse.set_reconnect_interval(100);
  22127. sse.set_max_reconnect_attempts(1);
  22128. sse.start_async();
  22129. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22130. sse.stop();
  22131. std::lock_guard<std::mutex> lock(data_mutex);
  22132. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22133. }
  22134. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22135. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22136. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22137. DataSink &sink) {
  22138. if (offset == 0) {
  22139. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22140. sink.write(events.data(), events.size());
  22141. }
  22142. return false;
  22143. });
  22144. });
  22145. Client client("localhost", get_port());
  22146. sse::SSEClient sse(client, "/empty-data-lines");
  22147. std::mutex mutex;
  22148. std::condition_variable cv;
  22149. std::vector<std::string> received;
  22150. sse.on_message([&](const sse::SSEMessage &msg) {
  22151. std::lock_guard<std::mutex> lock(mutex);
  22152. received.push_back(msg.data);
  22153. cv.notify_all();
  22154. });
  22155. sse.set_max_reconnect_attempts(1);
  22156. sse.start_async();
  22157. {
  22158. std::unique_lock<std::mutex> lock(mutex);
  22159. cv.wait_for(lock, std::chrono::seconds(2),
  22160. [&] { return received.size() >= 3; });
  22161. }
  22162. sse.stop();
  22163. ASSERT_GE(received.size(), 3u);
  22164. EXPECT_EQ(received[0], "");
  22165. EXPECT_EQ(received[1], "\nhello");
  22166. EXPECT_EQ(received[2], "");
  22167. }
  22168. // Test: Auto-reconnect after server disconnection
  22169. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22170. std::atomic<int> connection_count{0};
  22171. std::atomic<int> message_count{0};
  22172. // Endpoint that sends one event and closes, forcing reconnect
  22173. server_->Get("/reconnect-test",
  22174. [&connection_count](const Request &, Response &res) {
  22175. connection_count.fetch_add(1);
  22176. res.set_chunked_content_provider(
  22177. "text/event-stream", [](size_t offset, DataSink &sink) {
  22178. if (offset == 0) {
  22179. std::string event = "data: hello\n\n";
  22180. sink.write(event.data(), event.size());
  22181. }
  22182. return false; // Close connection after sending
  22183. });
  22184. });
  22185. Client client("localhost", get_port());
  22186. sse::SSEClient sse(client, "/reconnect-test");
  22187. sse.on_message([&message_count](const sse::SSEMessage &) {
  22188. message_count.fetch_add(1);
  22189. });
  22190. sse.set_reconnect_interval(100);
  22191. sse.set_max_reconnect_attempts(3);
  22192. sse.start_async();
  22193. // Wait long enough for multiple reconnects
  22194. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22195. sse.stop();
  22196. // Should have connected multiple times (initial + reconnects)
  22197. EXPECT_GE(connection_count.load(), 2);
  22198. // Should have received messages from multiple connections
  22199. EXPECT_GE(message_count.load(), 2);
  22200. }
  22201. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22202. std::atomic<int> connection_count{0};
  22203. // Neither Content-Length nor chunked: the close ends the stream
  22204. server_->Get("/close-delimited",
  22205. [&connection_count](const Request &, Response &res) {
  22206. connection_count.fetch_add(1);
  22207. res.set_content_provider(
  22208. "text/event-stream", [](size_t offset, DataSink &sink) {
  22209. if (offset == 0) {
  22210. std::string event = "data: hello\n\n";
  22211. sink.write(event.data(), event.size());
  22212. } else {
  22213. sink.done();
  22214. }
  22215. return true;
  22216. });
  22217. });
  22218. Client client("localhost", get_port());
  22219. sse::SSEClient sse(client, "/close-delimited");
  22220. std::atomic<int> error_count{0};
  22221. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22222. sse.set_reconnect_interval(100);
  22223. sse.start_async();
  22224. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22225. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22226. }
  22227. sse.stop();
  22228. // Reconnects as after any end of the stream, but reports no error
  22229. EXPECT_GE(connection_count.load(), 2);
  22230. EXPECT_EQ(0, error_count.load());
  22231. }
  22232. // Test: A retry field that is not all ASCII digits is ignored
  22233. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22234. std::atomic<int> connection_count{0};
  22235. server_->Get("/bad-retry",
  22236. [&connection_count](const Request &, Response &res) {
  22237. connection_count.fetch_add(1);
  22238. res.set_chunked_content_provider(
  22239. "text/event-stream", [](size_t offset, DataSink &sink) {
  22240. if (offset == 0) {
  22241. std::string event = "retry: -1\ndata: hello\n\n";
  22242. sink.write(event.data(), event.size());
  22243. }
  22244. return false;
  22245. });
  22246. });
  22247. Client client("localhost", get_port());
  22248. sse::SSEClient sse(client, "/bad-retry");
  22249. sse.set_reconnect_interval(10000);
  22250. sse.start_async();
  22251. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22252. sse.stop();
  22253. EXPECT_EQ(connection_count.load(), 1);
  22254. }
  22255. // Test: A retry field of all ASCII digits sets the reconnection time
  22256. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22257. std::mutex mutex;
  22258. std::condition_variable cv;
  22259. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22260. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22261. {
  22262. std::lock_guard<std::mutex> lock(mutex);
  22263. connected_at.push_back(std::chrono::steady_clock::now());
  22264. cv.notify_all();
  22265. }
  22266. res.set_chunked_content_provider(
  22267. "text/event-stream", [](size_t offset, DataSink &sink) {
  22268. if (offset == 0) {
  22269. std::string event = "retry: 0\ndata: hello\n\n";
  22270. sink.write(event.data(), event.size());
  22271. }
  22272. return false;
  22273. });
  22274. });
  22275. Client client("localhost", get_port());
  22276. sse::SSEClient sse(client, "/zero-retry");
  22277. sse.set_reconnect_interval(10000);
  22278. sse.start_async();
  22279. {
  22280. std::unique_lock<std::mutex> lock(mutex);
  22281. cv.wait_for(lock, std::chrono::seconds(5),
  22282. [&] { return connected_at.size() >= 2; });
  22283. }
  22284. sse.stop();
  22285. // The server-supplied interval is applied, but never below 100ms, so
  22286. // "retry: 0" does not cause a busy reconnect loop
  22287. std::lock_guard<std::mutex> lock(mutex);
  22288. ASSERT_GE(connected_at.size(), 2u);
  22289. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22290. connected_at[1] - connected_at[0])
  22291. .count();
  22292. EXPECT_GE(interval_ms, 100);
  22293. }
  22294. // Test: Last-Event-ID sent on reconnect
  22295. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22296. std::atomic<int> connection_count{0};
  22297. std::vector<std::string> received_last_event_ids;
  22298. std::mutex id_mutex;
  22299. // Endpoint that checks Last-Event-ID header and sends event with ID
  22300. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22301. int conn = connection_count.fetch_add(1);
  22302. // Capture the Last-Event-ID header from each connection
  22303. {
  22304. std::lock_guard<std::mutex> lock(id_mutex);
  22305. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22306. }
  22307. res.set_chunked_content_provider(
  22308. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22309. if (offset == 0) {
  22310. std::string event =
  22311. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22312. sink.write(event.data(), event.size());
  22313. }
  22314. return false;
  22315. });
  22316. });
  22317. Client client("localhost", get_port());
  22318. sse::SSEClient sse(client, "/reconnect-with-id");
  22319. sse.set_reconnect_interval(100);
  22320. sse.set_max_reconnect_attempts(3);
  22321. sse.start_async();
  22322. // Wait for at least 2 connections
  22323. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22324. sse.stop();
  22325. // Verify behavior
  22326. std::lock_guard<std::mutex> lock(id_mutex);
  22327. EXPECT_GE(received_last_event_ids.size(), 2u);
  22328. // First connection should have no Last-Event-ID
  22329. if (!received_last_event_ids.empty()) {
  22330. EXPECT_EQ(received_last_event_ids[0], "");
  22331. }
  22332. // Second connection should have Last-Event-ID from first connection
  22333. if (received_last_event_ids.size() >= 2) {
  22334. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22335. }
  22336. }
  22337. // Test: set_headers updates headers used on reconnect
  22338. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22339. std::vector<std::string> received_tokens;
  22340. std::mutex token_mutex;
  22341. // Endpoint that captures Authorization header
  22342. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22343. {
  22344. std::lock_guard<std::mutex> lock(token_mutex);
  22345. received_tokens.push_back(req.get_header_value("Authorization"));
  22346. }
  22347. res.set_chunked_content_provider(
  22348. "text/event-stream", [](size_t offset, DataSink &sink) {
  22349. if (offset == 0) {
  22350. std::string event = "data: hello\n\n";
  22351. sink.write(event.data(), event.size());
  22352. }
  22353. return false; // Close connection to trigger reconnect
  22354. });
  22355. });
  22356. Client client("localhost", get_port());
  22357. Headers headers = {{"Authorization", "Bearer old-token"}};
  22358. sse::SSEClient sse(client, "/auth-check", headers);
  22359. // Update headers on each successful connection
  22360. sse.on_open(
  22361. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22362. sse.set_reconnect_interval(100);
  22363. sse.set_max_reconnect_attempts(3);
  22364. sse.start_async();
  22365. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22366. sse.stop();
  22367. std::lock_guard<std::mutex> lock(token_mutex);
  22368. ASSERT_GE(received_tokens.size(), 2u);
  22369. // First connection uses original header
  22370. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22371. // Second connection uses updated header from set_headers
  22372. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22373. }
  22374. // Test: 401 allows reconnection (so on_error can refresh headers)
  22375. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22376. std::atomic<int> connection_count{0};
  22377. // Endpoint: returns 401 on first attempt, 200 on second
  22378. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22379. int conn = connection_count.fetch_add(1);
  22380. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22381. res.status = StatusCode::Unauthorized_401;
  22382. res.set_content("Unauthorized", "text/plain");
  22383. return;
  22384. }
  22385. res.set_chunked_content_provider(
  22386. "text/event-stream", [](size_t offset, DataSink &sink) {
  22387. if (offset == 0) {
  22388. std::string event = "data: authenticated\n\n";
  22389. sink.write(event.data(), event.size());
  22390. }
  22391. return false;
  22392. });
  22393. });
  22394. Client client("localhost", get_port());
  22395. Headers headers = {{"Authorization", "Bearer expired"}};
  22396. sse::SSEClient sse(client, "/auth-retry", headers);
  22397. std::atomic<bool> message_received{false};
  22398. // Refresh token on error
  22399. sse.on_error(
  22400. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22401. sse.on_message([&](const sse::SSEMessage &msg) {
  22402. if (msg.data == "authenticated") { message_received.store(true); }
  22403. });
  22404. sse.set_reconnect_interval(100);
  22405. sse.set_max_reconnect_attempts(3);
  22406. sse.start_async();
  22407. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22408. sse.stop();
  22409. // Should have reconnected after 401 and succeeded with new token
  22410. EXPECT_GE(connection_count.load(), 2);
  22411. EXPECT_TRUE(message_received.load());
  22412. }
  22413. TEST(Issue2318Test, EmptyHostString) {
  22414. {
  22415. httplib::Client cli_empty("", PORT);
  22416. auto res = cli_empty.Get("/");
  22417. ASSERT_FALSE(res);
  22418. EXPECT_EQ(httplib::Error::Connection, res.error());
  22419. }
  22420. {
  22421. httplib::Client cli(" ", PORT);
  22422. auto res = cli.Get("/");
  22423. ASSERT_FALSE(res);
  22424. EXPECT_EQ(httplib::Error::Connection, res.error());
  22425. }
  22426. }
  22427. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22428. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22429. Server svr;
  22430. // Set a small payload limit (1KB)
  22431. svr.set_payload_max_length(1024);
  22432. svr.Post("/test", [&](const Request &req, Response &res) {
  22433. res.set_content("Body size: " + std::to_string(req.body.size()),
  22434. "text/plain");
  22435. });
  22436. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22437. auto se = detail::scope_exit([&] {
  22438. svr.stop();
  22439. listen_thread.join();
  22440. });
  22441. svr.wait_until_ready();
  22442. // Create data that compresses well but exceeds limit when decompressed
  22443. // 8KB of repeated null bytes compresses to a very small size
  22444. std::string original_data(8 * 1024, '\0');
  22445. // Compress the data using gzip
  22446. std::string compressed_data;
  22447. detail::gzip_compressor compressor;
  22448. compressor.compress(original_data.data(), original_data.size(), true,
  22449. [&](const char *data, size_t size) {
  22450. compressed_data.append(data, size);
  22451. return true;
  22452. });
  22453. // Verify compression worked (compressed should be much smaller)
  22454. ASSERT_LT(compressed_data.size(), original_data.size());
  22455. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22456. // Send compressed data with Content-Encoding: gzip
  22457. Client cli(HOST, PORT);
  22458. Headers headers = {{"Content-Encoding", "gzip"}};
  22459. auto res =
  22460. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22461. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22463. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22464. }
  22465. #endif
  22466. // ============================================================================
  22467. // OpenSSL-Specific Tests
  22468. // ============================================================================
  22469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22470. X509 *readCertificate(const std::string &strFileName) {
  22471. std::ifstream inStream(strFileName);
  22472. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22473. std::istreambuf_iterator<char>());
  22474. if (strCertPEM.empty()) return (nullptr);
  22475. BIO *pbCert = BIO_new(BIO_s_mem());
  22476. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22477. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22478. BIO_free(pbCert);
  22479. return (pCert);
  22480. }
  22481. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22482. std::ifstream inStream(strFileName);
  22483. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22484. std::istreambuf_iterator<char>());
  22485. if (strPrivateKeyPEM.empty()) return (nullptr);
  22486. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22487. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22488. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22489. BIO_free(pbPrivKey);
  22490. return (pPrivateKey);
  22491. }
  22492. TEST(BindServerTest, UpdateCerts) {
  22493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22494. int port = svr.bind_to_any_port("0.0.0.0");
  22495. ASSERT_TRUE(svr.is_valid());
  22496. ASSERT_TRUE(port > 0);
  22497. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22498. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22499. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22500. ASSERT_TRUE(cert != nullptr);
  22501. ASSERT_TRUE(ca_cert != nullptr);
  22502. ASSERT_TRUE(key != nullptr);
  22503. X509_STORE *cert_store = X509_STORE_new();
  22504. X509_STORE_add_cert(cert_store, ca_cert);
  22505. // svr.update_certs(cert, key, cert_store); // deprecated
  22506. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22507. CLIENT_CA_CERT_FILE);
  22508. ASSERT_TRUE(svr.is_valid());
  22509. svr.stop();
  22510. X509_STORE_free(cert_store);
  22511. X509_free(cert);
  22512. X509_free(ca_cert);
  22513. EVP_PKEY_free(key);
  22514. }
  22515. // Test that update_certs() updates client CA list correctly
  22516. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22517. // Start with file-based constructor
  22518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22519. ASSERT_TRUE(svr.is_valid());
  22520. // Initially no client CA list should be set
  22521. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22522. ASSERT_TRUE(ssl_ctx != nullptr);
  22523. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22524. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22525. // Now update with client CA (PEM string)
  22526. std::string cert_pem, key_pem, ca_pem;
  22527. read_file(SERVER_CERT_FILE, cert_pem);
  22528. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22529. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22530. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22531. ASSERT_TRUE(svr.is_valid());
  22532. // Now client CA list should be set
  22533. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22534. ASSERT_TRUE(ca_list_after != nullptr);
  22535. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22536. }
  22537. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22538. // Test that the file-path SSLServer constructor properly sets the client CA
  22539. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22541. ASSERT_TRUE(svr.is_valid());
  22542. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22543. ASSERT_TRUE(ssl_ctx != nullptr);
  22544. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22545. ASSERT_TRUE(ca_list != nullptr);
  22546. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22547. }
  22548. #endif
  22549. // ============================================================================
  22550. // MbedTLS-Specific Tests
  22551. // ============================================================================
  22552. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22553. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22554. using namespace httplib::tls;
  22555. // Track if callback was invoked
  22556. bool callback_invoked = false;
  22557. // The callback receives void* ctx which is actually MbedTlsContext*
  22558. // We can access the mbedtls_ssl_config via the context
  22559. auto setup_callback = [&callback_invoked](void *ctx) {
  22560. callback_invoked = true;
  22561. // Cast to MbedTlsContext* to access the ssl config
  22562. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22563. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22564. // Use static variables to hold certificate data (simplified for test)
  22565. static mbedtls_x509_crt own_cert;
  22566. static mbedtls_pk_context own_key;
  22567. static mbedtls_x509_crt ca_chain;
  22568. static bool initialized = false;
  22569. if (!initialized) {
  22570. mbedtls_x509_crt_init(&own_cert);
  22571. mbedtls_pk_init(&own_key);
  22572. mbedtls_x509_crt_init(&ca_chain);
  22573. // Load server certificate
  22574. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22575. return false;
  22576. }
  22577. // Load server private key.
  22578. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22579. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22580. #if MBEDTLS_VERSION_MAJOR == 3
  22581. ,
  22582. mbedtls_ctr_drbg_random, nullptr
  22583. #endif
  22584. ) != 0) {
  22585. return false;
  22586. }
  22587. // Load CA chain for client verification
  22588. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22589. return false;
  22590. }
  22591. initialized = true;
  22592. }
  22593. // Configure the SSL config
  22594. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22595. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22596. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22597. // Set minimum TLS version using mbedTLS native API
  22598. #if MBEDTLS_VERSION_MAJOR >= 3
  22599. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22600. #else
  22601. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22602. MBEDTLS_SSL_MINOR_VERSION_3);
  22603. #endif
  22604. return true;
  22605. };
  22606. SSLServer svr(setup_callback);
  22607. ASSERT_TRUE(svr.is_valid());
  22608. ASSERT_TRUE(callback_invoked);
  22609. svr.Get("/test", [&](const Request &req, Response &res) {
  22610. res.set_content("test", "text/plain");
  22611. auto cert = req.peer_cert();
  22612. ASSERT_TRUE(static_cast<bool>(cert));
  22613. auto common_name = cert.subject_cn();
  22614. EXPECT_EQ("Common Name", common_name);
  22615. });
  22616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22617. auto se = detail::scope_exit([&] {
  22618. svr.stop();
  22619. t.join();
  22620. ASSERT_FALSE(svr.is_running());
  22621. });
  22622. svr.wait_until_ready();
  22623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22624. cli.enable_server_certificate_verification(false);
  22625. cli.set_connection_timeout(30);
  22626. auto res = cli.Get("/test");
  22627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22628. ASSERT_EQ(StatusCode::OK_200, res->status);
  22629. }
  22630. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22631. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22632. // keep-alive SSL session, which reads through that config in
  22633. // mbedtls_ssl_close_notify.
  22634. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22636. ASSERT_TRUE(svr.is_valid());
  22637. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22638. res.set_content("test", "text/plain");
  22639. });
  22640. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22641. auto se = detail::scope_exit([&] {
  22642. svr.stop();
  22643. t.join();
  22644. ASSERT_FALSE(svr.is_running());
  22645. });
  22646. svr.wait_until_ready();
  22647. {
  22648. SSLClient cli(HOST, PORT);
  22649. cli.enable_server_certificate_verification(false);
  22650. cli.set_keep_alive(true);
  22651. auto res = cli.Get("/test");
  22652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22653. ASSERT_EQ(StatusCode::OK_200, res->status);
  22654. // cli is destructed here with the keep-alive SSL session still open.
  22655. }
  22656. }
  22657. #endif
  22658. // WebSocket Tests
  22659. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22660. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22661. // defining the meaning of these bits has been negotiated.
  22662. auto make_frame = [](uint8_t first_byte) {
  22663. std::string frame;
  22664. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22665. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22666. frame += "Hello";
  22667. return frame;
  22668. };
  22669. // RSV1 set (0x40)
  22670. {
  22671. detail::BufferStream strm;
  22672. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22673. ws::Opcode opcode;
  22674. std::string payload;
  22675. bool fin;
  22676. EXPECT_EQ(
  22677. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22678. ws::impl::FrameRead::Fail);
  22679. }
  22680. // RSV2 set (0x20)
  22681. {
  22682. detail::BufferStream strm;
  22683. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22684. ws::Opcode opcode;
  22685. std::string payload;
  22686. bool fin;
  22687. EXPECT_EQ(
  22688. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22689. ws::impl::FrameRead::Fail);
  22690. }
  22691. // RSV3 set (0x10)
  22692. {
  22693. detail::BufferStream strm;
  22694. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22695. ws::Opcode opcode;
  22696. std::string payload;
  22697. bool fin;
  22698. EXPECT_EQ(
  22699. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22700. ws::impl::FrameRead::Fail);
  22701. }
  22702. // No RSV bits set - should succeed
  22703. {
  22704. detail::BufferStream strm;
  22705. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22706. ws::Opcode opcode;
  22707. std::string payload;
  22708. bool fin;
  22709. EXPECT_EQ(
  22710. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22711. ws::impl::FrameRead::Ok);
  22712. EXPECT_EQ(ws::Opcode::Text, opcode);
  22713. EXPECT_EQ("Hello", payload);
  22714. EXPECT_TRUE(fin);
  22715. }
  22716. }
  22717. TEST(WebSocketTest, ControlFrameValidation) {
  22718. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22719. // payload length <= 125.
  22720. // Ping with FIN=0 - must be rejected
  22721. {
  22722. detail::BufferStream strm;
  22723. std::string frame;
  22724. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22725. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22726. strm.write(frame.data(), frame.size());
  22727. ws::Opcode opcode;
  22728. std::string payload;
  22729. bool fin;
  22730. EXPECT_EQ(
  22731. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22732. ws::impl::FrameRead::Fail);
  22733. }
  22734. // Close with FIN=0 - must be rejected
  22735. {
  22736. detail::BufferStream strm;
  22737. std::string frame;
  22738. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22739. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22740. strm.write(frame.data(), frame.size());
  22741. ws::Opcode opcode;
  22742. std::string payload;
  22743. bool fin;
  22744. EXPECT_EQ(
  22745. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22746. ws::impl::FrameRead::Fail);
  22747. }
  22748. // Ping with payload_len=126 (extended length) - must be rejected
  22749. {
  22750. detail::BufferStream strm;
  22751. std::string frame;
  22752. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22753. frame += static_cast<char>(126); // payload_len=126 (>125)
  22754. frame += static_cast<char>(0x00); // extended length high byte
  22755. frame += static_cast<char>(126); // extended length low byte
  22756. frame += std::string(126, 'x');
  22757. strm.write(frame.data(), frame.size());
  22758. ws::Opcode opcode;
  22759. std::string payload;
  22760. bool fin;
  22761. EXPECT_EQ(
  22762. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22763. ws::impl::FrameRead::Fail);
  22764. }
  22765. // Ping with FIN=1 and payload_len=125 - should succeed
  22766. {
  22767. detail::BufferStream strm;
  22768. std::string frame;
  22769. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22770. frame += static_cast<char>(125); // payload_len=125
  22771. frame += std::string(125, 'x');
  22772. strm.write(frame.data(), frame.size());
  22773. ws::Opcode opcode;
  22774. std::string payload;
  22775. bool fin;
  22776. EXPECT_EQ(
  22777. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22778. ws::impl::FrameRead::Ok);
  22779. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22780. EXPECT_EQ(125u, payload.size());
  22781. EXPECT_TRUE(fin);
  22782. }
  22783. }
  22784. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22785. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22786. // length MUST be 0.
  22787. // MSB set - must be rejected
  22788. {
  22789. detail::BufferStream strm;
  22790. std::string frame;
  22791. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22792. frame += static_cast<char>(127); // 64-bit extended length
  22793. frame += static_cast<char>(0x80); // MSB set (invalid)
  22794. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22795. strm.write(frame.data(), frame.size());
  22796. ws::Opcode opcode;
  22797. std::string payload;
  22798. bool fin;
  22799. EXPECT_EQ(
  22800. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22801. ws::impl::FrameRead::Fail);
  22802. }
  22803. // MSB clear - should pass length parsing (will be rejected by max_len,
  22804. // but that's a different check; use a small length to verify)
  22805. {
  22806. detail::BufferStream strm;
  22807. std::string frame;
  22808. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22809. frame += static_cast<char>(127); // 64-bit extended length
  22810. frame += std::string(7, '\0'); // high bytes = 0
  22811. frame += static_cast<char>(0x03); // length = 3
  22812. frame += "abc";
  22813. strm.write(frame.data(), frame.size());
  22814. ws::Opcode opcode;
  22815. std::string payload;
  22816. bool fin;
  22817. EXPECT_EQ(
  22818. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22819. ws::impl::FrameRead::Ok);
  22820. EXPECT_EQ(ws::Opcode::Text, opcode);
  22821. EXPECT_EQ("abc", payload);
  22822. }
  22823. }
  22824. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22825. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22826. // Valid UTF-8
  22827. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22828. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22829. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22830. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22831. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22832. // Invalid UTF-8
  22833. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22834. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22835. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22836. EXPECT_FALSE(
  22837. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22838. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22839. }
  22840. TEST(WebSocketTest, ConnectAndDisconnect) {
  22841. Server svr;
  22842. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22843. std::string msg;
  22844. while (ws.read(msg)) {}
  22845. });
  22846. auto port = svr.bind_to_any_port(HOST);
  22847. std::thread t([&]() { svr.listen_after_bind(); });
  22848. svr.wait_until_ready();
  22849. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22850. auto res = client.connect();
  22851. ASSERT_TRUE(res);
  22852. EXPECT_EQ(Error::Success, res.error());
  22853. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22854. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22855. EXPECT_TRUE(client.is_open());
  22856. client.close();
  22857. EXPECT_FALSE(client.is_open());
  22858. svr.stop();
  22859. t.join();
  22860. }
  22861. TEST(WebSocketTest, ValidURL) {
  22862. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22863. EXPECT_TRUE(ws1.is_valid());
  22864. ws::WebSocketClient ws2("ws://example.com/path");
  22865. EXPECT_TRUE(ws2.is_valid());
  22866. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22867. EXPECT_TRUE(ws3.is_valid());
  22868. #ifdef CPPHTTPLIB_SSL_ENABLED
  22869. ws::WebSocketClient wss1("wss://example.com/path");
  22870. EXPECT_TRUE(wss1.is_valid());
  22871. ws::WebSocketClient wss2("wss://example.com:443/path");
  22872. EXPECT_TRUE(wss2.is_valid());
  22873. #endif
  22874. }
  22875. TEST(WebSocketTest, InvalidURL) {
  22876. // No scheme
  22877. ws::WebSocketClient ws1("localhost:8080/path");
  22878. EXPECT_FALSE(ws1.is_valid());
  22879. // No path
  22880. ws::WebSocketClient ws2("ws://localhost:8080");
  22881. EXPECT_FALSE(ws2.is_valid());
  22882. // Empty string
  22883. ws::WebSocketClient ws3("");
  22884. EXPECT_FALSE(ws3.is_valid());
  22885. // Missing host
  22886. ws::WebSocketClient ws4("ws://:8080/path");
  22887. EXPECT_FALSE(ws4.is_valid());
  22888. // Port number overflow — should not crash
  22889. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22890. EXPECT_FALSE(ws5.is_valid());
  22891. // Port out of range
  22892. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22893. EXPECT_FALSE(ws6.is_valid());
  22894. }
  22895. TEST(WebSocketTest, UnsupportedScheme) {
  22896. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22897. ws::WebSocketClient ws1("http://localhost:8080/path");
  22898. EXPECT_FALSE(ws1.is_valid());
  22899. ws::WebSocketClient ws2("https://localhost:8080/path");
  22900. EXPECT_FALSE(ws2.is_valid());
  22901. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22902. EXPECT_FALSE(ws3.is_valid());
  22903. #else
  22904. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22905. std::invalid_argument);
  22906. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22907. std::invalid_argument);
  22908. #endif
  22909. }
  22910. TEST(WebSocketTest, ConnectWhenInvalid) {
  22911. ws::WebSocketClient ws("not a valid url");
  22912. EXPECT_FALSE(ws.is_valid());
  22913. auto res = ws.connect();
  22914. EXPECT_FALSE(res);
  22915. EXPECT_EQ(Error::Connection, res.error());
  22916. EXPECT_EQ(-1, res.status());
  22917. }
  22918. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22919. // Grab a port that is free, then close it again so nothing listens there
  22920. Server svr;
  22921. auto port = svr.bind_to_any_port(HOST);
  22922. svr.stop();
  22923. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22924. auto res = client.connect();
  22925. ASSERT_FALSE(res);
  22926. EXPECT_EQ(Error::Connection, res.error());
  22927. EXPECT_EQ(-1, res.status());
  22928. }
  22929. TEST(WebSocketTest, DefaultPort) {
  22930. ws::WebSocketClient ws1("ws://example.com/path");
  22931. EXPECT_TRUE(ws1.is_valid());
  22932. // ws:// defaults to port 80 (verified by successful parse)
  22933. #ifdef CPPHTTPLIB_SSL_ENABLED
  22934. ws::WebSocketClient ws2("wss://example.com/path");
  22935. EXPECT_TRUE(ws2.is_valid());
  22936. // wss:// defaults to port 443 (verified by successful parse)
  22937. #endif
  22938. }
  22939. TEST(WebSocketTest, IPv6LiteralAddress) {
  22940. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22941. EXPECT_TRUE(ws1.is_valid());
  22942. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22943. EXPECT_TRUE(ws2.is_valid());
  22944. }
  22945. TEST(WebSocketTest, ComplexPath) {
  22946. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22947. EXPECT_TRUE(ws1.is_valid());
  22948. ws::WebSocketClient ws2("ws://localhost:8080/");
  22949. EXPECT_TRUE(ws2.is_valid());
  22950. }
  22951. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22952. Server svr;
  22953. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22954. std::string msg;
  22955. while (ws.read(msg)) {}
  22956. });
  22957. auto port = svr.bind_to_any_port(HOST);
  22958. std::thread t([&]() { svr.listen_after_bind(); });
  22959. svr.wait_until_ready();
  22960. auto another_host = "example.com";
  22961. auto wrong_ip = "192.0.2.1";
  22962. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22963. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22964. ASSERT_TRUE(client.connect());
  22965. EXPECT_TRUE(client.is_open());
  22966. client.close();
  22967. svr.stop();
  22968. t.join();
  22969. }
  22970. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22971. Server svr;
  22972. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22973. std::string msg;
  22974. while (ws.read(msg)) {}
  22975. });
  22976. auto port = svr.bind_to_any_port(HOST);
  22977. std::thread t([&]() { svr.listen_after_bind(); });
  22978. svr.wait_until_ready();
  22979. auto wrong_ip = "192.0.2.1";
  22980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22981. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22982. client.set_connection_timeout(1);
  22983. client.set_read_timeout(1);
  22984. client.set_write_timeout(1);
  22985. EXPECT_FALSE(client.connect());
  22986. EXPECT_FALSE(client.is_open());
  22987. svr.stop();
  22988. t.join();
  22989. }
  22990. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22991. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22992. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22993. // (RFC 6761) is only a map key and the Host header value.
  22994. auto host = "target.invalid";
  22995. Server svr;
  22996. std::string received_host;
  22997. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22998. received_host = req.get_header_value("Host");
  22999. std::string msg;
  23000. while (ws.read(msg)) {}
  23001. });
  23002. auto port = svr.bind_to_any_port(HOST);
  23003. std::thread t([&]() { svr.listen_after_bind(); });
  23004. // ASSERT_* below returns from the test body, which would leave t joinable
  23005. // and make ~thread call std::terminate.
  23006. auto se = detail::scope_exit([&] {
  23007. svr.stop();
  23008. if (t.joinable()) { t.join(); }
  23009. });
  23010. svr.wait_until_ready();
  23011. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23012. std::to_string(port) + "/ws");
  23013. client.set_hostname_addr_map({{host, HOST}});
  23014. ASSERT_TRUE(client.connect());
  23015. EXPECT_TRUE(client.is_open());
  23016. client.close();
  23017. svr.stop();
  23018. t.join();
  23019. // The mapping only redirects the connection; the identity stays host_.
  23020. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23021. }
  23022. class WebSocketIntegrationTest : public ::testing::Test {
  23023. protected:
  23024. void SetUp() override {
  23025. server_ = httplib::detail::make_unique<Server>();
  23026. setup_server();
  23027. start_server();
  23028. }
  23029. void TearDown() override {
  23030. server_->stop();
  23031. if (server_thread_.joinable()) { server_thread_.join(); }
  23032. }
  23033. void setup_server() {
  23034. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23035. std::string msg;
  23036. ws::ReadResult ret;
  23037. while ((ret = ws.read(msg))) {
  23038. if (ret == ws::Binary) {
  23039. ws.send(msg.data(), msg.size());
  23040. } else {
  23041. ws.send(msg);
  23042. }
  23043. }
  23044. });
  23045. server_->WebSocket("/ws-echo-string",
  23046. [](const Request &, ws::WebSocket &ws) {
  23047. std::string msg;
  23048. while (ws.read(msg)) {
  23049. ws.send("echo: " + msg);
  23050. }
  23051. });
  23052. server_->WebSocket(
  23053. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23054. // Echo back request metadata
  23055. ws.send("path:" + req.path);
  23056. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23057. std::string msg;
  23058. while (ws.read(msg)) {}
  23059. });
  23060. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23061. std::string msg;
  23062. ws.read(msg); // wait for a message
  23063. ws.close();
  23064. });
  23065. server_->WebSocket("/ws-close-status",
  23066. [](const Request &, ws::WebSocket &ws) {
  23067. std::string msg;
  23068. ws.read(msg); // wait for a message
  23069. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23070. });
  23071. server_->WebSocket(
  23072. "/ws-subprotocol",
  23073. [](const Request &, ws::WebSocket &ws) {
  23074. std::string msg;
  23075. while (ws.read(msg)) {
  23076. ws.send(msg);
  23077. }
  23078. },
  23079. [](const std::vector<std::string> &protocols) -> std::string {
  23080. for (const auto &p : protocols) {
  23081. if (p == "graphql-ws") { return p; }
  23082. }
  23083. return "";
  23084. });
  23085. server_->WebSocket(
  23086. "/ws-subprotocol-unoffered",
  23087. [](const Request &, ws::WebSocket &ws) {
  23088. std::string msg;
  23089. while (ws.read(msg)) {
  23090. ws.send(msg);
  23091. }
  23092. },
  23093. [](const std::vector<std::string> &) -> std::string {
  23094. return "admin";
  23095. });
  23096. }
  23097. void start_server() {
  23098. port_ = server_->bind_to_any_port(HOST);
  23099. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23100. server_->wait_until_ready();
  23101. }
  23102. std::unique_ptr<Server> server_;
  23103. std::thread server_thread_;
  23104. int port_ = 0;
  23105. };
  23106. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23108. "/ws-echo");
  23109. ASSERT_TRUE(client.connect());
  23110. ASSERT_TRUE(client.is_open());
  23111. ASSERT_TRUE(client.send("Hello WebSocket"));
  23112. std::string msg;
  23113. EXPECT_EQ(ws::Text, client.read(msg));
  23114. EXPECT_EQ("Hello WebSocket", msg);
  23115. client.close();
  23116. }
  23117. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23118. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23119. "/ws-echo");
  23120. ASSERT_TRUE(client.connect());
  23121. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23122. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23123. std::string msg;
  23124. EXPECT_EQ(ws::Binary, client.read(msg));
  23125. EXPECT_EQ(binary_data, msg);
  23126. client.close();
  23127. }
  23128. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23130. "/ws-echo");
  23131. ASSERT_TRUE(client.connect());
  23132. for (int i = 0; i < 10; i++) {
  23133. auto text = "message " + std::to_string(i);
  23134. ASSERT_TRUE(client.send(text));
  23135. std::string msg;
  23136. ASSERT_TRUE(client.read(msg));
  23137. EXPECT_EQ(text, msg);
  23138. }
  23139. client.close();
  23140. }
  23141. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23142. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23143. "/ws-close");
  23144. ASSERT_TRUE(client.connect());
  23145. // Send a message to trigger the server to close
  23146. ASSERT_TRUE(client.send("trigger close"));
  23147. // The server will close, so read should return false
  23148. std::string msg;
  23149. EXPECT_FALSE(client.read(msg));
  23150. EXPECT_FALSE(client.is_open());
  23151. }
  23152. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23153. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23154. "/ws-echo");
  23155. ASSERT_TRUE(client.connect());
  23156. // 128KB message
  23157. std::string large_data(128 * 1024, 'X');
  23158. ASSERT_TRUE(client.send(large_data));
  23159. std::string msg;
  23160. ASSERT_TRUE(client.read(msg));
  23161. EXPECT_EQ(large_data, msg);
  23162. client.close();
  23163. }
  23164. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23166. "/ws-echo");
  23167. ASSERT_TRUE(client.connect());
  23168. const int num_threads = 4;
  23169. std::vector<std::thread> threads;
  23170. std::atomic<int> send_count{0};
  23171. for (int t = 0; t < num_threads; t++) {
  23172. threads.emplace_back([&client, &send_count, t]() {
  23173. for (int i = 0; i < 5; i++) {
  23174. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23175. if (client.send(text)) { send_count++; }
  23176. }
  23177. });
  23178. }
  23179. for (auto &th : threads) {
  23180. th.join();
  23181. }
  23182. int received = 0;
  23183. std::string msg;
  23184. while (received < send_count.load()) {
  23185. if (!client.read(msg)) { break; }
  23186. received++;
  23187. }
  23188. EXPECT_EQ(send_count.load(), received);
  23189. client.close();
  23190. }
  23191. TEST_F(WebSocketIntegrationTest, ReadString) {
  23192. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23193. "/ws-echo-string");
  23194. ASSERT_TRUE(client.connect());
  23195. ASSERT_TRUE(client.send("hello"));
  23196. std::string msg;
  23197. ASSERT_TRUE(client.read(msg));
  23198. EXPECT_EQ("echo: hello", msg);
  23199. ASSERT_TRUE(client.send("world"));
  23200. ASSERT_TRUE(client.read(msg));
  23201. EXPECT_EQ("echo: world", msg);
  23202. client.close();
  23203. }
  23204. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23205. Headers headers = {{"X-Test-Header", "test-value"}};
  23206. ws::WebSocketClient client(
  23207. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23208. ASSERT_TRUE(client.connect());
  23209. std::string msg;
  23210. ASSERT_TRUE(client.read(msg));
  23211. EXPECT_EQ("path:/ws-request-info", msg);
  23212. ASSERT_TRUE(client.read(msg));
  23213. EXPECT_EQ("header:test-value", msg);
  23214. client.close();
  23215. }
  23216. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23217. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23218. "/ws-echo");
  23219. client.set_read_timeout(1, 0); // 1 second
  23220. ASSERT_TRUE(client.connect());
  23221. // Don't send anything — server echo handler waits for a message, so read()
  23222. // should time out. The connection survives it: nothing was consumed.
  23223. std::string msg;
  23224. EXPECT_EQ(client.read(msg), ws::Timeout);
  23225. EXPECT_TRUE(client.is_open());
  23226. // And it is still usable afterwards.
  23227. EXPECT_TRUE(client.send("after timeout"));
  23228. EXPECT_EQ(client.read(msg), ws::Text);
  23229. EXPECT_EQ(msg, "after timeout");
  23230. }
  23231. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23232. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23233. "/ws-echo");
  23234. client.set_read_timeout(1, 0);
  23235. ASSERT_TRUE(client.connect());
  23236. ASSERT_TRUE(client.send("first"));
  23237. std::string msg;
  23238. ASSERT_EQ(client.read(msg), ws::Text);
  23239. ASSERT_EQ(msg, "first");
  23240. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23241. // not be used with a read timeout: it would reprocess the previous message.
  23242. EXPECT_EQ(client.read(msg), ws::Timeout);
  23243. EXPECT_EQ(msg, "first");
  23244. }
  23245. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23246. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23247. "/ws-echo");
  23248. ASSERT_TRUE(client.connect());
  23249. // Setting it once the connection is open reaches the live stream, not just
  23250. // the seed for the next connect().
  23251. client.set_read_timeout(1, 0);
  23252. std::string msg;
  23253. EXPECT_EQ(client.read(msg), ws::Timeout);
  23254. EXPECT_TRUE(client.is_open());
  23255. }
  23256. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23257. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23258. "/ws-echo");
  23259. client.set_read_timeout(5, 0);
  23260. ASSERT_TRUE(client.connect());
  23261. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23262. // The server should reject it and close the connection.
  23263. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23264. client.send(oversized);
  23265. // The server's read() should have failed due to payload limit,
  23266. // so our read() should return false (connection closed).
  23267. std::string msg;
  23268. EXPECT_FALSE(client.read(msg));
  23269. }
  23270. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23271. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23272. "/ws-echo");
  23273. client.set_read_timeout(10, 0);
  23274. ASSERT_TRUE(client.connect());
  23275. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23276. // This should succeed.
  23277. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23278. ASSERT_TRUE(client.send(at_limit));
  23279. std::string msg;
  23280. ASSERT_TRUE(client.read(msg));
  23281. EXPECT_EQ(at_limit.size(), msg.size());
  23282. client.close();
  23283. }
  23284. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23285. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23286. "/nonexistent");
  23287. auto res = client.connect();
  23288. EXPECT_FALSE(res);
  23289. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23290. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23291. EXPECT_FALSE(client.is_open());
  23292. }
  23293. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23294. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23295. "/ws-echo");
  23296. ASSERT_TRUE(client.connect());
  23297. ASSERT_TRUE(client.send(""));
  23298. std::string msg;
  23299. EXPECT_EQ(ws::Text, client.read(msg));
  23300. EXPECT_EQ("", msg);
  23301. client.close();
  23302. }
  23303. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23305. "/ws-echo");
  23306. // First connection
  23307. ASSERT_TRUE(client.connect());
  23308. ASSERT_TRUE(client.send("first"));
  23309. std::string msg;
  23310. ASSERT_TRUE(client.read(msg));
  23311. EXPECT_EQ("first", msg);
  23312. client.close();
  23313. EXPECT_FALSE(client.is_open());
  23314. // Reconnect using the same client object
  23315. ASSERT_TRUE(client.connect());
  23316. ASSERT_TRUE(client.is_open());
  23317. ASSERT_TRUE(client.send("second"));
  23318. ASSERT_TRUE(client.read(msg));
  23319. EXPECT_EQ("second", msg);
  23320. client.close();
  23321. }
  23322. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23323. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23324. "/ws-close-status");
  23325. ASSERT_TRUE(client.connect());
  23326. // Trigger the server to close with GoingAway status
  23327. ASSERT_TRUE(client.send("trigger"));
  23328. // read() should return false after receiving the close frame
  23329. std::string msg;
  23330. EXPECT_FALSE(client.read(msg));
  23331. EXPECT_FALSE(client.is_open());
  23332. }
  23333. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23335. "/ws-echo");
  23336. ASSERT_TRUE(client.connect());
  23337. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23338. EXPECT_FALSE(client.is_open());
  23339. }
  23340. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23341. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23342. ws::WebSocketClient client(
  23343. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23344. ASSERT_TRUE(client.connect());
  23345. // Server should have selected graphql-ws
  23346. EXPECT_EQ("graphql-ws", client.subprotocol());
  23347. client.close();
  23348. }
  23349. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23350. Headers headers;
  23351. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23352. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23353. ws::WebSocketClient client(
  23354. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23355. ASSERT_TRUE(client.connect());
  23356. // The offer on the second field line counts too, so graphql-ws is selected
  23357. EXPECT_EQ("graphql-ws", client.subprotocol());
  23358. client.close();
  23359. }
  23360. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23361. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23362. ws::WebSocketClient client(
  23363. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23364. ASSERT_TRUE(client.connect());
  23365. // Server should not have selected any subprotocol
  23366. EXPECT_TRUE(client.subprotocol().empty());
  23367. client.close();
  23368. }
  23369. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23370. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23371. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23372. "/ws-subprotocol-unoffered",
  23373. headers);
  23374. ASSERT_TRUE(client.connect());
  23375. EXPECT_TRUE(client.subprotocol().empty());
  23376. client.close();
  23377. }
  23378. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23379. // Connect without requesting any subprotocol
  23380. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23381. "/ws-subprotocol");
  23382. ASSERT_TRUE(client.connect());
  23383. EXPECT_TRUE(client.subprotocol().empty());
  23384. client.close();
  23385. }
  23386. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23388. "/ws-echo");
  23389. client.set_tcp_nodelay(true);
  23390. client.set_connection_timeout(3, 0);
  23391. bool socket_options_called = false;
  23392. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23393. ASSERT_TRUE(client.connect());
  23394. ASSERT_TRUE(client.is_open());
  23395. EXPECT_TRUE(socket_options_called);
  23396. ASSERT_TRUE(client.send("hello"));
  23397. std::string msg;
  23398. auto result = client.read(msg);
  23399. EXPECT_EQ(result, ws::ReadResult::Text);
  23400. EXPECT_EQ(msg, "hello");
  23401. client.close();
  23402. }
  23403. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23405. "/ws-echo");
  23406. client.set_connection_timeout(std::chrono::seconds(3));
  23407. client.set_write_timeout(std::chrono::seconds(3));
  23408. // A sub-second remainder exercises the seconds/microseconds split.
  23409. client.set_read_timeout(std::chrono::milliseconds(1500));
  23410. ASSERT_TRUE(client.connect());
  23411. auto start = std::chrono::steady_clock::now();
  23412. std::string msg;
  23413. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23414. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23415. std::chrono::steady_clock::now() - start)
  23416. .count();
  23417. // Above 1s so that dropping the microseconds half of the split fails here.
  23418. // Ignoring the setter altogether would not reach this line at all: a client
  23419. // waits forever by default.
  23420. EXPECT_GE(elapsed, 1400);
  23421. EXPECT_LT(elapsed, 30000);
  23422. }
  23423. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23424. Server svr;
  23425. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23426. if (!req.has_header("Authorization")) {
  23427. res.status = StatusCode::Unauthorized_401;
  23428. res.set_content("Unauthorized", "text/plain");
  23429. return Server::HandlerResponse::Handled;
  23430. }
  23431. return Server::HandlerResponse::Unhandled;
  23432. });
  23433. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23434. std::string msg;
  23435. while (ws.read(msg)) {
  23436. ws.send(msg);
  23437. }
  23438. });
  23439. auto port = svr.bind_to_any_port("localhost");
  23440. std::thread t([&]() { svr.listen_after_bind(); });
  23441. svr.wait_until_ready();
  23442. // Without Authorization header - should be rejected before upgrade
  23443. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23444. EXPECT_FALSE(client1.connect());
  23445. // The rejection is framed like any other HTTP response
  23446. {
  23447. Client cli("localhost", port);
  23448. Headers headers = {{"Upgrade", "websocket"},
  23449. {"Connection", "Upgrade"},
  23450. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23451. {"Sec-WebSocket-Version", "13"}};
  23452. auto res = cli.Get("/ws", headers);
  23453. ASSERT_TRUE(res);
  23454. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23455. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23456. EXPECT_EQ("Unauthorized", res->body);
  23457. }
  23458. // With Authorization header - should succeed
  23459. Headers headers = {{"Authorization", "Bearer token123"}};
  23460. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23461. headers);
  23462. ASSERT_TRUE(client2.connect());
  23463. ASSERT_TRUE(client2.send("hello"));
  23464. std::string msg;
  23465. ASSERT_TRUE(client2.read(msg));
  23466. EXPECT_EQ("hello", msg);
  23467. client2.close();
  23468. svr.stop();
  23469. t.join();
  23470. }
  23471. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23472. Server svr;
  23473. std::atomic<int> pre_routing_calls{0};
  23474. std::atomic<int> pre_request_calls{0};
  23475. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23476. pre_routing_calls++;
  23477. if (req.path == "/handled") {
  23478. res.set_content("handled", "text/plain");
  23479. return Server::HandlerResponse::Handled;
  23480. }
  23481. return Server::HandlerResponse::Unhandled;
  23482. });
  23483. svr.set_pre_request_handler([&](const Request &, Response &) {
  23484. pre_request_calls++;
  23485. return Server::HandlerResponse::Unhandled;
  23486. });
  23487. svr.Get("/http", [](const Request &, Response &res) {
  23488. res.set_content("http", "text/plain");
  23489. });
  23490. svr.WebSocket("/ws",
  23491. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23492. auto port = svr.bind_to_any_port("localhost");
  23493. std::thread t([&]() { svr.listen_after_bind(); });
  23494. auto se = detail::scope_exit([&] {
  23495. svr.stop();
  23496. t.join();
  23497. });
  23498. svr.wait_until_ready();
  23499. Headers upgrade = {{"Upgrade", "websocket"},
  23500. {"Connection", "Upgrade"},
  23501. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23502. {"Sec-WebSocket-Version", "13"}};
  23503. auto get = [&](const char *path) {
  23504. pre_routing_calls = 0;
  23505. return Client("localhost", port).Get(path, upgrade);
  23506. };
  23507. // No WebSocket route, but an HTTP one
  23508. auto res = get("/http");
  23509. ASSERT_TRUE(res);
  23510. EXPECT_EQ(StatusCode::OK_200, res->status);
  23511. EXPECT_EQ("http", res->body);
  23512. EXPECT_EQ(1, pre_routing_calls);
  23513. EXPECT_EQ(1, pre_request_calls);
  23514. // No route at all
  23515. res = get("/none");
  23516. ASSERT_TRUE(res);
  23517. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23518. EXPECT_EQ(1, pre_routing_calls);
  23519. // Answered by the pre-routing handler
  23520. res = get("/handled");
  23521. ASSERT_TRUE(res);
  23522. EXPECT_EQ(StatusCode::OK_200, res->status);
  23523. EXPECT_EQ("handled", res->body);
  23524. EXPECT_EQ(1, pre_routing_calls);
  23525. // A WebSocket route
  23526. pre_routing_calls = 0;
  23527. pre_request_calls = 0;
  23528. {
  23529. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23530. "/ws");
  23531. ASSERT_TRUE(client.connect());
  23532. std::string msg;
  23533. ASSERT_TRUE(client.read(msg));
  23534. EXPECT_EQ("ws", msg);
  23535. client.close();
  23536. }
  23537. EXPECT_EQ(1, pre_routing_calls);
  23538. EXPECT_EQ(1, pre_request_calls);
  23539. }
  23540. // An upgrade request answered by a hook leaves its body unread, so that body
  23541. // must not be served as the next request on the connection.
  23542. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23543. Server svr;
  23544. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23545. if (req.path == "/pre-routing") {
  23546. res.set_content("pre-routing", "text/plain");
  23547. return Server::HandlerResponse::Handled;
  23548. }
  23549. return Server::HandlerResponse::Unhandled;
  23550. });
  23551. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23552. if (req.matched_route == "/pre-request") {
  23553. res.set_content("pre-request", "text/plain");
  23554. return Server::HandlerResponse::Handled;
  23555. }
  23556. return Server::HandlerResponse::Unhandled;
  23557. });
  23558. svr.Get("/smuggled", [](const Request &, Response &res) {
  23559. res.set_content("smuggled", "text/plain");
  23560. });
  23561. svr.WebSocket("/pre-request",
  23562. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23563. auto port = svr.bind_to_any_port(HOST);
  23564. std::thread t([&]() { svr.listen_after_bind(); });
  23565. auto se = detail::scope_exit([&] {
  23566. svr.stop();
  23567. t.join();
  23568. });
  23569. svr.wait_until_ready();
  23570. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23571. for (auto path : {"/pre-routing", "/pre-request"}) {
  23572. std::string req = std::string("GET ") + path +
  23573. " HTTP/1.1\r\n"
  23574. "Host: localhost\r\n"
  23575. "Upgrade: websocket\r\n"
  23576. "Connection: Upgrade\r\n"
  23577. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23578. "Sec-WebSocket-Version: 13\r\n"
  23579. "Content-Length: " +
  23580. std::to_string(body.size()) + "\r\n\r\n" + body;
  23581. std::string res;
  23582. ASSERT_TRUE(send_request(5, req, &res, port));
  23583. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23584. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23585. // Only one response, and the body was not served as a request
  23586. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23587. }
  23588. }
  23589. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23590. Server svr;
  23591. std::atomic<int> pre_request_calls{0};
  23592. std::atomic<bool> route_matched{false};
  23593. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23594. pre_request_calls++;
  23595. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23596. if (req.get_header_value("Authorization") != "Bearer token123") {
  23597. res.status = StatusCode::Unauthorized_401;
  23598. res.set_content("Unauthorized", "text/plain");
  23599. return Server::HandlerResponse::Handled;
  23600. }
  23601. return Server::HandlerResponse::Unhandled;
  23602. });
  23603. std::atomic<bool> handler_called{false};
  23604. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23605. handler_called = true;
  23606. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23607. });
  23608. auto port = svr.bind_to_any_port("localhost");
  23609. std::thread t([&]() { svr.listen_after_bind(); });
  23610. svr.wait_until_ready();
  23611. // Without Authorization header - should be rejected before upgrade
  23612. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23613. "/ws/1");
  23614. EXPECT_FALSE(client1.connect());
  23615. EXPECT_FALSE(handler_called);
  23616. EXPECT_EQ(1, pre_request_calls);
  23617. EXPECT_TRUE(route_matched);
  23618. // The rejection is an ordinary HTTP response, not a protocol switch
  23619. {
  23620. Client cli("localhost", port);
  23621. Headers headers = {{"Upgrade", "websocket"},
  23622. {"Connection", "Upgrade"},
  23623. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23624. {"Sec-WebSocket-Version", "13"}};
  23625. auto res = cli.Get("/ws/1", headers);
  23626. ASSERT_TRUE(res);
  23627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23628. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23629. EXPECT_EQ("Unauthorized", res->body);
  23630. }
  23631. EXPECT_FALSE(handler_called);
  23632. // With Authorization header - should succeed
  23633. Headers headers = {{"Authorization", "Bearer token123"}};
  23634. ws::WebSocketClient client2(
  23635. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23636. ASSERT_TRUE(client2.connect());
  23637. std::string msg;
  23638. ASSERT_TRUE(client2.read(msg));
  23639. EXPECT_EQ("/ws/:id 2", msg);
  23640. EXPECT_TRUE(handler_called);
  23641. client2.close();
  23642. svr.stop();
  23643. t.join();
  23644. }
  23645. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23646. Server svr;
  23647. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23648. // A read timeout is how a handler gets control back. Without it, a handler
  23649. // parked in read() can never write on the connection it is reading.
  23650. ws.set_read_timeout(std::chrono::milliseconds(100));
  23651. std::string msg;
  23652. while (ws.is_open()) {
  23653. auto r = ws.read(msg);
  23654. if (r == httplib::ws::Timeout) {
  23655. ws.send("tick");
  23656. continue;
  23657. }
  23658. if (r == httplib::ws::Fail) { break; }
  23659. ws.send(msg);
  23660. }
  23661. });
  23662. auto port = svr.bind_to_any_port("localhost");
  23663. std::thread t([&]() { svr.listen_after_bind(); });
  23664. svr.wait_until_ready();
  23665. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23666. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23667. ASSERT_TRUE(client.connect());
  23668. // The client sends nothing, so anything it receives came out of the
  23669. // handler's timeout path.
  23670. std::string msg;
  23671. ASSERT_EQ(client.read(msg), ws::Text);
  23672. EXPECT_EQ("tick", msg);
  23673. client.close();
  23674. svr.stop();
  23675. t.join();
  23676. }
  23677. // Stream::read may return fewer bytes than asked for. This is that contract at
  23678. // its worst -- one byte per call -- which is what a frame header straddling a
  23679. // read buffer's boundary looks like to the frame parser.
  23680. class WsByteAtATimeStream : public Stream {
  23681. public:
  23682. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23683. bool is_readable() const override { return true; }
  23684. bool wait_readable() const override { return true; }
  23685. bool wait_writable() const override { return true; }
  23686. ssize_t read(char *ptr, size_t size) override {
  23687. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23688. *ptr = data_[pos_++];
  23689. return 1;
  23690. }
  23691. ssize_t write(const char *, size_t size) override {
  23692. return static_cast<ssize_t>(size);
  23693. }
  23694. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23695. ip = "127.0.0.1";
  23696. port = 0;
  23697. }
  23698. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23699. ip = "127.0.0.1";
  23700. port = 0;
  23701. }
  23702. socket_t socket() const override { return INVALID_SOCKET; }
  23703. time_t duration() const override { return 0; }
  23704. private:
  23705. std::string data_;
  23706. size_t pos_ = 0;
  23707. };
  23708. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23709. // The payload uses the 16-bit extended length, so the header, the length
  23710. // and the mask key are all multi-byte fields here. Each used to be read
  23711. // with a single read() call, which fails as soon as one is split. The
  23712. // payload is also a little over one read chunk, so it is read in two.
  23713. std::string body;
  23714. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23715. body += static_cast<char>(i % 251);
  23716. }
  23717. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23718. std::string frame;
  23719. frame += static_cast<char>(0x81); // FIN + Text
  23720. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23721. frame += static_cast<char>(body.size() >> 8);
  23722. frame += static_cast<char>(body.size() & 0xff);
  23723. for (size_t i = 0; i < 4; i++) {
  23724. frame += static_cast<char>(mask[i]);
  23725. }
  23726. for (size_t i = 0; i < body.size(); i++) {
  23727. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23728. }
  23729. WsByteAtATimeStream strm(frame);
  23730. ws::Opcode opcode;
  23731. std::string payload;
  23732. bool fin = false;
  23733. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23734. /*expect_masked=*/true, body.size()),
  23735. ws::impl::FrameRead::Ok);
  23736. EXPECT_TRUE(fin);
  23737. EXPECT_EQ(opcode, ws::Opcode::Text);
  23738. EXPECT_EQ(payload, body);
  23739. }
  23740. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23741. std::string body(2000, 'x');
  23742. std::string frame;
  23743. frame += static_cast<char>(0x82); // FIN + Binary
  23744. frame += static_cast<char>(126); // 16-bit length follows
  23745. frame += static_cast<char>(body.size() >> 8);
  23746. frame += static_cast<char>(body.size() & 0xff);
  23747. frame += body;
  23748. detail::BufferStream strm;
  23749. strm.write(frame.data(), frame.size());
  23750. ws::Opcode opcode;
  23751. std::string payload;
  23752. bool fin;
  23753. EXPECT_EQ(
  23754. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23755. ws::impl::FrameRead::Ok);
  23756. EXPECT_EQ(body, payload);
  23757. }
  23758. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23759. // The header announces the largest payload allowed, and only 3 bytes of it
  23760. // ever arrive.
  23761. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23762. std::string frame;
  23763. frame += static_cast<char>(0x82); // FIN + Binary
  23764. frame += static_cast<char>(127); // 64-bit length follows
  23765. for (int shift = 56; shift >= 0; shift -= 8) {
  23766. frame += static_cast<char>((len >> shift) & 0xff);
  23767. }
  23768. frame += "abc";
  23769. detail::BufferStream strm;
  23770. strm.write(frame.data(), frame.size());
  23771. ws::Opcode opcode;
  23772. std::string payload;
  23773. bool fin;
  23774. EXPECT_EQ(
  23775. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23776. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23777. ws::impl::FrameRead::Fail);
  23778. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23779. }
  23780. TEST(WebSocketTest, QueryStringInHandshake) {
  23781. Server svr;
  23782. std::mutex mtx;
  23783. std::string received_target;
  23784. std::string received_token;
  23785. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23786. {
  23787. std::lock_guard<std::mutex> lock(mtx);
  23788. received_target = req.target;
  23789. if (req.has_param("token")) {
  23790. received_token = req.get_param_value("token");
  23791. }
  23792. }
  23793. std::string msg;
  23794. while (ws.read(msg)) {
  23795. ws.send(msg);
  23796. }
  23797. });
  23798. auto port = svr.bind_to_any_port("localhost");
  23799. std::thread t([&]() { svr.listen_after_bind(); });
  23800. svr.wait_until_ready();
  23801. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23802. "/ws?token=ABC&session=123");
  23803. ASSERT_TRUE(client.connect());
  23804. // Round-trip ensures the handler has run and captured the request.
  23805. ASSERT_TRUE(client.send("hello"));
  23806. std::string msg;
  23807. ASSERT_TRUE(client.read(msg));
  23808. EXPECT_EQ("hello", msg);
  23809. client.close();
  23810. {
  23811. std::lock_guard<std::mutex> lock(mtx);
  23812. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23813. EXPECT_EQ("ABC", received_token);
  23814. }
  23815. svr.stop();
  23816. t.join();
  23817. }
  23818. // Run a handshake against a throwaway server and hand the request the server
  23819. // received back to the caller, so tests can assert on the headers the client
  23820. // actually put on the wire.
  23821. static void capture_websocket_handshake_request(
  23822. const Headers &client_headers,
  23823. std::function<void(const Request &, int port)> verify) {
  23824. Server svr;
  23825. std::mutex mtx;
  23826. Request received;
  23827. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23828. {
  23829. std::lock_guard<std::mutex> lock(mtx);
  23830. received = req;
  23831. }
  23832. std::string msg;
  23833. while (ws.read(msg)) {
  23834. ws.send(msg);
  23835. }
  23836. });
  23837. auto port = svr.bind_to_any_port("localhost");
  23838. std::thread t([&]() { svr.listen_after_bind(); });
  23839. auto se = detail::scope_exit([&] {
  23840. svr.stop();
  23841. t.join();
  23842. });
  23843. svr.wait_until_ready();
  23844. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23845. client_headers);
  23846. ASSERT_TRUE(client.connect());
  23847. ASSERT_TRUE(client.send("hello"));
  23848. std::string msg;
  23849. ASSERT_TRUE(client.read(msg));
  23850. client.close();
  23851. {
  23852. std::lock_guard<std::mutex> lock(mtx);
  23853. verify(received, port);
  23854. }
  23855. }
  23856. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23857. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23858. // Non-default port must be present in the Host header. Default ports
  23859. // (80/443) are omitted; that logic is covered by
  23860. // MakeHostAndPortStringTest.
  23861. EXPECT_EQ("localhost:" + std::to_string(port),
  23862. req.get_header_value("Host"));
  23863. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23864. req.get_header_value("User-Agent"));
  23865. EXPECT_FALSE(req.has_header("Accept"));
  23866. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23867. EXPECT_FALSE(req.has_header("Content-Length"));
  23868. });
  23869. }
  23870. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23871. capture_websocket_handshake_request(
  23872. {{"Host", "example.com"},
  23873. {"User-Agent", "custom-agent"},
  23874. {"X-Custom", "value"}},
  23875. [](const Request &req, int) {
  23876. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23877. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23878. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23879. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23880. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23881. });
  23882. }
  23883. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23884. capture_websocket_handshake_request(
  23885. {{"Upgrade", "bogus"},
  23886. {"Connection", "close"},
  23887. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23888. {"Sec-WebSocket-Version", "8"}},
  23889. [](const Request &req, int) {
  23890. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23891. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23892. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23893. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23894. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23895. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23896. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23897. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23898. req.get_header_value("Sec-WebSocket-Key"));
  23899. });
  23900. }
  23901. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23902. // A header the client refuses to send must abort the handshake before any
  23903. // part of it reaches the wire; a lone request line would otherwise sit in
  23904. // the peer's buffer as a truncated request.
  23905. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23906. ASSERT_NE(INVALID_SOCKET, srv);
  23907. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23908. sockaddr_in addr{};
  23909. addr.sin_family = AF_INET;
  23910. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23911. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23912. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23913. ASSERT_EQ(0, ::listen(srv, 1));
  23914. sockaddr_in bound{};
  23915. socklen_t bound_len = sizeof(bound);
  23916. ASSERT_EQ(
  23917. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23918. auto port = ntohs(bound.sin_port);
  23919. ssize_t received = -1;
  23920. std::thread t([&] {
  23921. // Bound every blocking call so a regression fails the test with a bad
  23922. // value instead of hanging the suite.
  23923. fd_set rfds;
  23924. FD_ZERO(&rfds);
  23925. FD_SET(srv, &rfds);
  23926. timeval tv{5, 0};
  23927. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23928. 0) {
  23929. return;
  23930. }
  23931. sockaddr_in cli_addr{};
  23932. socklen_t cli_len = sizeof(cli_addr);
  23933. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23934. if (cli == INVALID_SOCKET) { return; }
  23935. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23936. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23937. char buf[4096];
  23938. received = ::recv(cli, buf, sizeof(buf), 0);
  23939. });
  23940. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23941. // connect() has already shut the socket down by the time it returns false,
  23942. // so the peer sees EOF without waiting for the client to be destroyed.
  23943. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23944. {{"X-Bad", "a\r\nInjected: 1"}});
  23945. EXPECT_FALSE(client.connect());
  23946. t.join();
  23947. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23948. EXPECT_EQ(0, received);
  23949. }
  23950. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23951. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23952. // contains "upgrade" as a substring is a different token and must not
  23953. // start a WebSocket handshake.
  23954. auto make_request = [](const std::vector<std::string> &connection_values) {
  23955. Request req;
  23956. req.method = "GET";
  23957. req.headers.emplace("Upgrade", "websocket");
  23958. for (const auto &value : connection_values) {
  23959. req.headers.emplace("Connection", value);
  23960. }
  23961. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23962. req.headers.emplace("Sec-WebSocket-Version", "13");
  23963. return req;
  23964. };
  23965. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23966. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23967. EXPECT_TRUE(
  23968. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23969. EXPECT_TRUE(
  23970. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23971. EXPECT_TRUE(
  23972. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23973. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23974. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23975. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23976. EXPECT_FALSE(
  23977. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23978. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23979. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23980. }
  23981. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23982. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23983. // asks recipients to match each protocol-name case-insensitively, and RFC
  23984. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23985. // client naming websocket alongside another protocol, or on a second field
  23986. // line, is offering websocket; a value that merely contains "websocket" as a
  23987. // substring is a different protocol name and is not.
  23988. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23989. Request req;
  23990. req.method = "GET";
  23991. for (const auto &value : upgrade_values) {
  23992. req.headers.emplace("Upgrade", value);
  23993. }
  23994. req.headers.emplace("Connection", "Upgrade");
  23995. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23996. req.headers.emplace("Sec-WebSocket-Version", "13");
  23997. return req;
  23998. };
  23999. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24000. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24001. EXPECT_TRUE(
  24002. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24003. EXPECT_TRUE(
  24004. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24005. EXPECT_TRUE(
  24006. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24007. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24008. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24009. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24010. EXPECT_FALSE(
  24011. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24012. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24013. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24014. }
  24015. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24016. Server svr;
  24017. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24018. auto port = svr.bind_to_any_port("localhost");
  24019. std::thread t([&]() { svr.listen_after_bind(); });
  24020. auto se = detail::scope_exit([&] {
  24021. svr.stop();
  24022. t.join();
  24023. });
  24024. svr.wait_until_ready();
  24025. Headers headers = {{"Upgrade", "websocket"},
  24026. {"Connection", "notupgrade"},
  24027. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24028. {"Sec-WebSocket-Version", "13"}};
  24029. Client cli("localhost", port);
  24030. auto res = cli.Get("/ws", headers);
  24031. // The route exists only as a WebSocket route, so a request that fails the
  24032. // handshake check falls through to ordinary routing.
  24033. ASSERT_TRUE(res);
  24034. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24035. }
  24036. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24037. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24038. // Connection value is the only thing left for the client to reject.
  24039. Server svr;
  24040. svr.Get("/ws", [](const Request &req, Response &res) {
  24041. res.status = StatusCode::SwitchingProtocol_101;
  24042. res.set_header("Upgrade", "websocket");
  24043. res.set_header("Connection", "notupgrade");
  24044. res.set_header("Sec-WebSocket-Accept",
  24045. detail::websocket_accept_key(
  24046. req.get_header_value("Sec-WebSocket-Key")));
  24047. });
  24048. auto port = svr.bind_to_any_port("localhost");
  24049. std::thread t([&]() { svr.listen_after_bind(); });
  24050. auto se = detail::scope_exit([&] {
  24051. svr.stop();
  24052. t.join();
  24053. });
  24054. svr.wait_until_ready();
  24055. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24056. auto res = client.connect();
  24057. EXPECT_FALSE(res);
  24058. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24059. EXPECT_FALSE(client.is_open());
  24060. }
  24061. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24062. Server svr;
  24063. svr.Get("/ws", [](const Request &req, Response &res) {
  24064. res.status = StatusCode::SwitchingProtocol_101;
  24065. res.set_header("Upgrade", "websocket");
  24066. res.set_header("Connection", "Upgrade");
  24067. res.set_header("Sec-WebSocket-Accept",
  24068. detail::websocket_accept_key(
  24069. req.get_header_value("Sec-WebSocket-Key")));
  24070. res.set_header("Sec-WebSocket-Protocol", "admin");
  24071. });
  24072. auto port = svr.bind_to_any_port("localhost");
  24073. std::thread t([&]() { svr.listen_after_bind(); });
  24074. auto se = detail::scope_exit([&] {
  24075. svr.stop();
  24076. t.join();
  24077. });
  24078. svr.wait_until_ready();
  24079. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24080. // Server selects a subprotocol the client never offered
  24081. {
  24082. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24083. ws::WebSocketClient client(url, headers);
  24084. auto res = client.connect();
  24085. EXPECT_FALSE(res);
  24086. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24087. EXPECT_FALSE(client.is_open());
  24088. EXPECT_TRUE(client.subprotocol().empty());
  24089. }
  24090. // Client offered none but the server named one anyway
  24091. {
  24092. ws::WebSocketClient client(url);
  24093. auto res = client.connect();
  24094. EXPECT_FALSE(res);
  24095. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24096. EXPECT_FALSE(client.is_open());
  24097. EXPECT_TRUE(client.subprotocol().empty());
  24098. }
  24099. }
  24100. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24101. // The socket path doubles as the URL host, so it must not contain '/'.
  24102. const char *shard = getenv("GTEST_SHARD_INDEX");
  24103. const std::string sock_path =
  24104. shard ? std::string("httplib-ws-") + shard + ".sock"
  24105. : std::string("httplib-ws.sock");
  24106. std::remove(sock_path.c_str());
  24107. Server svr;
  24108. std::mutex mtx;
  24109. std::string received_host;
  24110. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24111. {
  24112. std::lock_guard<std::mutex> lock(mtx);
  24113. received_host = req.get_header_value("Host");
  24114. }
  24115. std::string msg;
  24116. while (ws.read(msg)) {
  24117. ws.send(msg);
  24118. }
  24119. });
  24120. svr.set_address_family(AF_UNIX);
  24121. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24122. auto se = detail::scope_exit([&] {
  24123. svr.stop();
  24124. t.join();
  24125. std::remove(sock_path.c_str());
  24126. });
  24127. svr.wait_until_ready();
  24128. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24129. client.set_address_family(AF_UNIX);
  24130. ASSERT_TRUE(client.connect());
  24131. ASSERT_TRUE(client.send("hello"));
  24132. std::string msg;
  24133. ASSERT_TRUE(client.read(msg));
  24134. client.close();
  24135. {
  24136. std::lock_guard<std::mutex> lock(mtx);
  24137. // There is no host:port for a Unix socket, so the same "localhost"
  24138. // placeholder the HTTP client uses is expected.
  24139. EXPECT_EQ("localhost", received_host);
  24140. }
  24141. }
  24142. // Two threads must never parse WebSocket frames from the same stream.
  24143. // close() used to read the peer's Close reply with its own frame read, so it
  24144. // raced a reader thread that was in the middle of a payload: the payload loop
  24145. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24146. // so bytes taken by close() were replaced with bytes from further along the
  24147. // stream. The message kept its length and silently changed content.
  24148. //
  24149. // The raw peer below sends a frame header plus part of the payload, waits for
  24150. // the handler to call close(), and only then sends the rest. Whichever thread
  24151. // would win the race for those bytes, the message must arrive intact, because
  24152. // close() must not touch the stream while read() owns it.
  24153. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24154. #ifndef _WIN32
  24155. signal(SIGPIPE, SIG_IGN);
  24156. #endif
  24157. const size_t payload_len = 120; // fits the 7-bit length field
  24158. const size_t prefix_len = 8;
  24159. const int attempts = 8;
  24160. std::string expected(payload_len, '\0');
  24161. for (size_t i = 0; i < payload_len; i++) {
  24162. expected[i] = static_cast<char>('a' + i % 26);
  24163. }
  24164. std::atomic<bool> peer_stalled{false};
  24165. std::atomic<bool> handler_done{false};
  24166. std::mutex received_mutex;
  24167. std::vector<std::string> received;
  24168. // Bound every wait, so a regression fails the test instead of hanging the
  24169. // suite.
  24170. auto wait_for = [](const std::atomic<bool> &flag) {
  24171. for (int i = 0; i < 500 && !flag; i++) {
  24172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24173. }
  24174. };
  24175. Server svr;
  24176. svr.set_websocket_ping_interval(0);
  24177. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24178. std::thread reader([&]() {
  24179. std::string msg;
  24180. while (ws.read(msg)) {
  24181. std::lock_guard<std::mutex> guard(received_mutex);
  24182. received.push_back(msg);
  24183. }
  24184. });
  24185. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24186. // inside read_websocket_frame() when close() runs.
  24187. wait_for(peer_stalled);
  24188. ws.close();
  24189. reader.join();
  24190. handler_done = true;
  24191. });
  24192. auto port = svr.bind_to_any_port("127.0.0.1");
  24193. std::thread t([&]() { svr.listen_after_bind(); });
  24194. auto se = detail::scope_exit([&] {
  24195. svr.stop();
  24196. t.join();
  24197. });
  24198. svr.wait_until_ready();
  24199. auto send_bytes = [](socket_t s, const std::string &data) {
  24200. #ifdef _WIN32
  24201. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24202. #else
  24203. auto n = ::send(s, data.data(), data.size(), 0);
  24204. #endif
  24205. return n == static_cast<decltype(n)>(data.size());
  24206. };
  24207. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24208. // Every length used here fits the 7-bit length field.
  24209. auto masked_header = [](uint8_t first_byte, size_t len) {
  24210. std::string h;
  24211. h += static_cast<char>(first_byte);
  24212. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24213. h.append(4, '\0'); // mask key
  24214. return h;
  24215. };
  24216. for (int attempt = 0; attempt < attempts; attempt++) {
  24217. peer_stalled = false;
  24218. handler_done = false;
  24219. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24220. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24221. auto se_sock = detail::scope_exit([&] {
  24222. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24223. });
  24224. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24225. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24226. sockaddr_in addr{};
  24227. addr.sin_family = AF_INET;
  24228. addr.sin_port = htons(static_cast<uint16_t>(port));
  24229. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24230. ASSERT_EQ(
  24231. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24232. << "attempt " << attempt;
  24233. ASSERT_TRUE(send_bytes(sock,
  24234. "GET /ws HTTP/1.1\r\n"
  24235. "Host: 127.0.0.1\r\n"
  24236. "Upgrade: websocket\r\n"
  24237. "Connection: Upgrade\r\n"
  24238. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24239. "Sec-WebSocket-Version: 13\r\n"
  24240. "\r\n"))
  24241. << "attempt " << attempt;
  24242. std::string response;
  24243. while (response.find("\r\n\r\n") == std::string::npos) {
  24244. char buf[512];
  24245. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24246. if (n <= 0) { break; }
  24247. response.append(buf, static_cast<size_t>(n));
  24248. }
  24249. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24250. << "attempt " << attempt;
  24251. // Send the header of a Binary message but only the first prefix_len bytes
  24252. // of its payload, leaving the reader thread stalled inside the payload.
  24253. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24254. expected.substr(0, prefix_len)))
  24255. << "attempt " << attempt;
  24256. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24257. peer_stalled = true;
  24258. // Let close() send its Close frame and park in its own read before the
  24259. // rest of the payload arrives, so both threads are waiting for it.
  24260. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24261. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24262. close_frame += static_cast<char>(0x03); // status 1000
  24263. close_frame += static_cast<char>(0xE8);
  24264. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24265. << "attempt " << attempt;
  24266. // Closing the peer releases the reader thread even on the buggy path,
  24267. // where it waits for bytes another thread already consumed.
  24268. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24269. detail::close_socket(sock);
  24270. sock = INVALID_SOCKET;
  24271. wait_for(handler_done);
  24272. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24273. }
  24274. std::lock_guard<std::mutex> guard(received_mutex);
  24275. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24276. << "a message in flight when close() ran was dropped";
  24277. for (size_t i = 0; i < received.size(); i++) {
  24278. EXPECT_EQ(expected, received[i]) << "message " << i;
  24279. }
  24280. }
  24281. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24282. // returning the socket, or INVALID_SOCKET.
  24283. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24284. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24285. if (sock == INVALID_SOCKET) { return sock; }
  24286. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24287. sockaddr_in addr{};
  24288. addr.sin_family = AF_INET;
  24289. addr.sin_port = htons(static_cast<uint16_t>(port));
  24290. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24291. std::string req = "GET " + path +
  24292. " HTTP/1.1\r\n"
  24293. "Host: 127.0.0.1\r\n"
  24294. "Upgrade: websocket\r\n"
  24295. "Connection: Upgrade\r\n"
  24296. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24297. "Sec-WebSocket-Version: 13\r\n"
  24298. "\r\n";
  24299. std::string res;
  24300. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24301. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24302. static_cast<ssize_t>(req.size())) {
  24303. char c;
  24304. while (res.find("\r\n\r\n") == std::string::npos &&
  24305. ::recv(sock, &c, 1, 0) == 1) {
  24306. res += c;
  24307. }
  24308. }
  24309. if (res.find(" 101 ") == std::string::npos) {
  24310. detail::close_socket(sock);
  24311. return INVALID_SOCKET;
  24312. }
  24313. return sock;
  24314. }
  24315. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24316. // The payload must fit the 7-bit length field.
  24317. static std::string masked_frame(uint8_t first_byte,
  24318. const std::string &payload) {
  24319. std::string f;
  24320. f += static_cast<char>(first_byte);
  24321. f += static_cast<char>(0x80 | payload.size());
  24322. f.append(4, '\0');
  24323. return f + payload;
  24324. }
  24325. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24326. std::atomic<bool> done{false};
  24327. std::string received;
  24328. Server svr;
  24329. svr.set_websocket_ping_interval(0);
  24330. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24331. std::string msg;
  24332. if (ws.read(msg) == ws::Binary) { received = msg; }
  24333. done = true;
  24334. });
  24335. auto port = svr.bind_to_any_port("127.0.0.1");
  24336. std::thread t([&]() { svr.listen_after_bind(); });
  24337. auto se = detail::scope_exit([&] {
  24338. svr.stop();
  24339. t.join();
  24340. });
  24341. svr.wait_until_ready();
  24342. auto sock = connect_raw_websocket(port, "/ws");
  24343. ASSERT_NE(INVALID_SOCKET, sock);
  24344. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24345. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24346. masked_frame(0x89, "p") + // FIN + Ping
  24347. masked_frame(0x80, "lo"); // FIN + Continuation
  24348. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24349. for (int i = 0; i < 500 && !done; i++) {
  24350. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24351. }
  24352. ASSERT_TRUE(done);
  24353. EXPECT_EQ("Hello", received);
  24354. // The Ping between the fragments is answered with a Pong.
  24355. char pong[3];
  24356. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24357. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24358. }
  24359. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24360. Server svr;
  24361. svr.set_websocket_ping_interval(-1);
  24362. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24363. std::string msg;
  24364. while (ws.read(msg)) {}
  24365. });
  24366. auto port = svr.bind_to_any_port("127.0.0.1");
  24367. std::thread t([&]() { svr.listen_after_bind(); });
  24368. auto se = detail::scope_exit([&] {
  24369. svr.stop();
  24370. t.join();
  24371. });
  24372. svr.wait_until_ready();
  24373. auto sock = connect_raw_websocket(port, "/ws");
  24374. ASSERT_NE(INVALID_SOCKET, sock);
  24375. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24376. // Nothing comes while the client stays quiet.
  24377. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24378. char c;
  24379. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24380. }
  24381. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24382. // and that has to end a read() already waiting on the peer, on every platform.
  24383. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24384. // The peer sends no pings, and its handler never calls read(), which is
  24385. // where pongs are written.
  24386. std::mutex mutex;
  24387. std::condition_variable cv;
  24388. auto release = false;
  24389. svr.set_websocket_ping_interval(0);
  24390. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24391. std::unique_lock<std::mutex> lock(mutex);
  24392. cv.wait(lock, [&] { return release; });
  24393. });
  24394. auto port = svr.bind_to_any_port(HOST);
  24395. std::thread t([&]() { svr.listen_after_bind(); });
  24396. auto se = detail::scope_exit([&] {
  24397. {
  24398. std::lock_guard<std::mutex> lock(mutex);
  24399. release = true;
  24400. }
  24401. cv.notify_all();
  24402. svr.stop();
  24403. t.join();
  24404. });
  24405. svr.wait_until_ready();
  24406. ws::WebSocketClient client(std::string(scheme) +
  24407. "://localhost:" + std::to_string(port) + "/ws");
  24408. #ifdef CPPHTTPLIB_SSL_ENABLED
  24409. client.enable_server_certificate_verification(false);
  24410. #endif
  24411. // A ping a second, given up on after two go unanswered: about 3s
  24412. client.set_websocket_ping_interval(1);
  24413. client.set_websocket_max_missed_pongs(2);
  24414. // Well past that, so that a read the timeout ends instead stands out
  24415. client.set_read_timeout(10);
  24416. ASSERT_TRUE(client.connect());
  24417. auto start = std::chrono::steady_clock::now();
  24418. std::string msg;
  24419. EXPECT_EQ(ws::Fail, client.read(msg));
  24420. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24421. std::chrono::steady_clock::now() - start)
  24422. .count(),
  24423. 6000);
  24424. EXPECT_FALSE(client.is_open());
  24425. }
  24426. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24427. Server svr;
  24428. check_pong_timeout_ends_read(svr, "ws");
  24429. }
  24430. #ifdef CPPHTTPLIB_SSL_ENABLED
  24431. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24433. ASSERT_TRUE(svr.is_valid());
  24434. check_pong_timeout_ends_read(svr, "wss");
  24435. }
  24436. #endif
  24437. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24438. Server svr;
  24439. svr.set_websocket_ping_interval(0);
  24440. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24441. std::string msg;
  24442. while (ws.read(msg)) {}
  24443. });
  24444. auto port = svr.bind_to_any_port("127.0.0.1");
  24445. std::thread t([&]() { svr.listen_after_bind(); });
  24446. auto se = detail::scope_exit([&] {
  24447. svr.stop();
  24448. t.join();
  24449. });
  24450. svr.wait_until_ready();
  24451. // Each Close payload and the reply it should get: an echo when valid, 1002
  24452. // otherwise.
  24453. std::vector<std::pair<std::string, std::string>> cases = {
  24454. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24455. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24456. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24457. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24458. };
  24459. // Also between the fragments of a message.
  24460. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24461. for (const auto &c : cases) {
  24462. auto sock = connect_raw_websocket(port, "/ws");
  24463. ASSERT_NE(INVALID_SOCKET, sock);
  24464. auto frames = prefix + masked_frame(0x88, c.first);
  24465. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24466. std::string reply;
  24467. char buf[256];
  24468. while (reply.size() < 2 + c.second.size()) {
  24469. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24470. if (n <= 0) { break; }
  24471. reply.append(buf, static_cast<size_t>(n));
  24472. }
  24473. detail::close_socket(sock);
  24474. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24475. c.second,
  24476. reply);
  24477. }
  24478. }
  24479. }
  24480. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24481. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24482. protected:
  24483. void SetUp() override {
  24484. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24485. SERVER_PRIVATE_KEY_FILE);
  24486. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24487. std::string msg;
  24488. ws::ReadResult ret;
  24489. while ((ret = ws.read(msg))) {
  24490. if (ret == ws::Binary) {
  24491. ws.send(msg.data(), msg.size());
  24492. } else {
  24493. ws.send(msg);
  24494. }
  24495. }
  24496. });
  24497. port_ = server_->bind_to_any_port(HOST);
  24498. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24499. server_->wait_until_ready();
  24500. }
  24501. void TearDown() override {
  24502. server_->stop();
  24503. if (server_thread_.joinable()) { server_thread_.join(); }
  24504. }
  24505. std::unique_ptr<SSLServer> server_;
  24506. std::thread server_thread_;
  24507. int port_ = 0;
  24508. };
  24509. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24510. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24511. {
  24512. ws::WebSocketClient client(url);
  24513. client.enable_server_certificate_verification(false);
  24514. auto calls = 0;
  24515. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24516. calls++;
  24517. return false;
  24518. });
  24519. EXPECT_FALSE(client.connect());
  24520. EXPECT_GT(calls, 0);
  24521. }
  24522. {
  24523. ws::WebSocketClient client(url);
  24524. client.enable_server_certificate_verification(false);
  24525. client.set_session_verifier([](tls::session_t) {
  24526. return SSLVerifierResponse::CertificateRejected;
  24527. });
  24528. EXPECT_FALSE(client.connect());
  24529. }
  24530. {
  24531. ws::WebSocketClient client(url);
  24532. client.enable_server_certificate_verification(false);
  24533. client.set_session_verifier([](tls::session_t) {
  24534. return SSLVerifierResponse::CertificateAccepted;
  24535. });
  24536. EXPECT_TRUE(client.connect());
  24537. }
  24538. }
  24539. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24540. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24541. "/ws-echo");
  24542. client.enable_server_certificate_verification(false);
  24543. ASSERT_TRUE(client.connect());
  24544. ASSERT_TRUE(client.is_open());
  24545. ASSERT_TRUE(client.send("Hello WSS"));
  24546. std::string msg;
  24547. EXPECT_EQ(ws::Text, client.read(msg));
  24548. EXPECT_EQ("Hello WSS", msg);
  24549. client.close();
  24550. }
  24551. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24552. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24553. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24554. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24555. // client (without calling close() first) is the only path that runs
  24556. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24557. // bug exactly.
  24558. //
  24559. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24560. // when linked against an instrumented libssl; run under Valgrind to catch it
  24561. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24562. // suite (the freed session otherwise stalls on the close handshake) — this test
  24563. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24564. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24565. {
  24566. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24567. "/ws-echo");
  24568. client.enable_server_certificate_verification(false);
  24569. client.set_read_timeout(2, 0);
  24570. client.set_write_timeout(2, 0);
  24571. ASSERT_TRUE(client.connect());
  24572. ASSERT_TRUE(client.is_open());
  24573. ASSERT_TRUE(client.send("still open"));
  24574. // Intentionally do NOT call client.close(): leaving scope runs
  24575. // shutdown_and_close() with the WebSocket still open, which must send the
  24576. // close frame while the TLS session is still alive.
  24577. }
  24578. }
  24579. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24580. // shutdown_and_close() at the start of connect(), reproducing the same
  24581. // use-after-free within the test body rather than at scope exit. The second
  24582. // connect must succeed and echo, proving the close handshake ran over a live
  24583. // session. See the note above about memory-tool requirements.
  24584. TEST_F(WebSocketSSLIntegrationTest,
  24585. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24586. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24587. "/ws-echo");
  24588. client.enable_server_certificate_verification(false);
  24589. client.set_read_timeout(2, 0);
  24590. client.set_write_timeout(2, 0);
  24591. ASSERT_TRUE(client.connect());
  24592. ASSERT_TRUE(client.is_open());
  24593. ASSERT_TRUE(client.send("still open"));
  24594. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24595. // the still-open connection, which must not touch a freed TLS session.
  24596. ASSERT_TRUE(client.connect());
  24597. ASSERT_TRUE(client.is_open());
  24598. ASSERT_TRUE(client.send("after reconnect"));
  24599. std::string msg;
  24600. EXPECT_EQ(ws::Text, client.read(msg));
  24601. EXPECT_EQ("after reconnect", msg);
  24602. client.close();
  24603. }
  24604. #endif
  24605. #ifdef CPPHTTPLIB_SSL_ENABLED
  24606. class WebSocketSSLCATest : public ::testing::Test {
  24607. protected:
  24608. void SetUp() override {
  24609. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24610. SERVER_PRIVATE_KEY_FILE);
  24611. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24612. std::string msg;
  24613. while (ws.read(msg)) {
  24614. ws.send(msg);
  24615. }
  24616. });
  24617. port_ = server_->bind_to_any_port("127.0.0.1");
  24618. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24619. server_->wait_until_ready();
  24620. }
  24621. void TearDown() override {
  24622. server_->stop();
  24623. if (server_thread_.joinable()) { server_thread_.join(); }
  24624. }
  24625. std::string url() const {
  24626. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24627. }
  24628. std::unique_ptr<SSLServer> server_;
  24629. std::thread server_thread_;
  24630. int port_ = 0;
  24631. };
  24632. // A custom CA loaded as PEM verifies the server with full certificate
  24633. // verification enabled
  24634. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24635. ws::WebSocketClient client(url());
  24636. std::string cert;
  24637. read_file(SERVER_CERT2_FILE, cert);
  24638. client.load_ca_cert_store(cert.c_str(), cert.size());
  24639. ASSERT_TRUE(client.connect());
  24640. ASSERT_TRUE(client.send("hello"));
  24641. std::string msg;
  24642. EXPECT_EQ(ws::Text, client.read(msg));
  24643. EXPECT_EQ("hello", msg);
  24644. client.close();
  24645. }
  24646. // A custom CA that does not cover the server must fail verification (the
  24647. // custom CA is exclusive; system certs are not loaded alongside it)
  24648. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24649. ws::WebSocketClient client(url());
  24650. std::string cert;
  24651. read_file(CLIENT_CA_CERT_FILE, cert);
  24652. client.load_ca_cert_store(cert.c_str(), cert.size());
  24653. auto res = client.connect();
  24654. ASSERT_FALSE(res);
  24655. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24656. EXPECT_EQ(-1, res.status());
  24657. EXPECT_NE(0u, res.ssl_backend_error());
  24658. }
  24659. // The same CA as a file path rather than PEM in memory
  24660. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24661. ws::WebSocketClient client(url());
  24662. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24663. ASSERT_TRUE(client.connect());
  24664. ASSERT_TRUE(client.send("hello"));
  24665. std::string msg;
  24666. EXPECT_EQ(ws::Text, client.read(msg));
  24667. EXPECT_EQ("hello", msg);
  24668. client.close();
  24669. }
  24670. // ...and a CA file that does not cover the server still fails, so it is the
  24671. // path above that decides the outcome
  24672. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24673. ws::WebSocketClient client(url());
  24674. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24675. ASSERT_FALSE(client.connect());
  24676. }
  24677. // Regression test: reconnecting with a native custom CA store used to reuse
  24678. // a store handle the previous TLS context had already freed (use-after-free
  24679. // under the OpenSSL backend). The context now lives as long as the client.
  24680. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24681. ws::WebSocketClient client(url());
  24682. std::string cert;
  24683. read_file(SERVER_CERT2_FILE, cert);
  24684. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24685. ASSERT_TRUE(client.connect());
  24686. client.close();
  24687. ASSERT_TRUE(client.connect());
  24688. ASSERT_TRUE(client.send("again"));
  24689. std::string msg;
  24690. EXPECT_EQ(ws::Text, client.read(msg));
  24691. EXPECT_EQ("again", msg);
  24692. client.close();
  24693. }
  24694. // Regression test: a certificate with a trusted chain but no identity match
  24695. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24696. // verification entirely for IP hosts, so this connection succeeded there.
  24697. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24698. // chain verification while the identity check must still fail.
  24699. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24701. ASSERT_TRUE(svr.is_valid());
  24702. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24703. std::string msg;
  24704. while (ws.read(msg)) {
  24705. ws.send(msg);
  24706. }
  24707. });
  24708. auto port = svr.bind_to_any_port("127.0.0.1");
  24709. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24710. auto se = detail::scope_exit([&] {
  24711. svr.stop();
  24712. t.join();
  24713. });
  24714. svr.wait_until_ready();
  24715. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24716. "/echo");
  24717. std::string cert;
  24718. read_file(SERVER_CERT_FILE, cert);
  24719. client.load_ca_cert_store(cert.c_str(), cert.size());
  24720. ASSERT_FALSE(client.connect());
  24721. }
  24722. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24723. // SNI, so nothing binds the host name to the TLS session. These bind the
  24724. // server to "localhost" instead, the only shape that exercises the SNI and
  24725. // hostname-verification path with certificate verification left enabled.
  24726. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24727. protected:
  24728. void Start(const char *cert_file) {
  24729. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24730. SERVER_PRIVATE_KEY_FILE);
  24731. ASSERT_TRUE(server_->is_valid());
  24732. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24733. std::string msg;
  24734. while (ws.read(msg)) {
  24735. ws.send(msg);
  24736. }
  24737. });
  24738. port_ = server_->bind_to_any_port("localhost");
  24739. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24740. server_->wait_until_ready();
  24741. }
  24742. void TearDown() override {
  24743. if (server_) { server_->stop(); }
  24744. if (server_thread_.joinable()) { server_thread_.join(); }
  24745. }
  24746. std::string url() const {
  24747. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24748. }
  24749. std::unique_ptr<SSLServer> server_;
  24750. std::thread server_thread_;
  24751. int port_ = 0;
  24752. };
  24753. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24754. // out and the connection is usable
  24755. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24756. Start(SERVER_CERT2_FILE);
  24757. ws::WebSocketClient client(url());
  24758. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24759. ASSERT_TRUE(client.connect());
  24760. ASSERT_TRUE(client.send("hello"));
  24761. std::string msg;
  24762. EXPECT_EQ(ws::Text, client.read(msg));
  24763. EXPECT_EQ("hello", msg);
  24764. client.close();
  24765. }
  24766. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24767. // while the identity check must still reject "localhost"
  24768. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24769. Start(SERVER_CERT_FILE);
  24770. ws::WebSocketClient client(url());
  24771. client.set_ca_cert_path(SERVER_CERT_FILE);
  24772. auto res = client.connect();
  24773. ASSERT_FALSE(res);
  24774. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24775. EXPECT_EQ(-1, res.status());
  24776. }
  24777. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24778. // disabled: the chain is still checked, only the identity check is skipped
  24779. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24780. Start(SERVER_CERT_FILE);
  24781. ws::WebSocketClient client(url());
  24782. client.set_ca_cert_path(SERVER_CERT_FILE);
  24783. client.enable_server_hostname_verification(false);
  24784. ASSERT_TRUE(client.connect());
  24785. ASSERT_TRUE(client.send("hello"));
  24786. std::string msg;
  24787. EXPECT_EQ(ws::Text, client.read(msg));
  24788. EXPECT_EQ("hello", msg);
  24789. client.close();
  24790. }
  24791. // A CA that did not sign the server certificate fails the chain, even though
  24792. // the name would match
  24793. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24794. Start(SERVER_CERT2_FILE);
  24795. ws::WebSocketClient client(url());
  24796. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24797. ASSERT_FALSE(client.connect());
  24798. }
  24799. // With verification disabled, neither the chain nor the name is checked
  24800. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24801. Start(SERVER_CERT_FILE);
  24802. ws::WebSocketClient client(url());
  24803. client.enable_server_certificate_verification(false);
  24804. ASSERT_TRUE(client.connect());
  24805. ASSERT_TRUE(client.send("hello"));
  24806. std::string msg;
  24807. EXPECT_EQ(ws::Text, client.read(msg));
  24808. EXPECT_EQ("hello", msg);
  24809. client.close();
  24810. }
  24811. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24812. protected:
  24813. void SetUp() override {
  24814. server_ = httplib::detail::make_unique<SSLServer>(
  24815. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24816. ASSERT_TRUE(server_->is_valid());
  24817. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24818. std::string msg;
  24819. while (ws.read(msg)) {
  24820. ws.send(msg);
  24821. }
  24822. });
  24823. port_ = server_->bind_to_any_port("localhost");
  24824. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24825. server_->wait_until_ready();
  24826. }
  24827. void TearDown() override {
  24828. server_->stop();
  24829. if (server_thread_.joinable()) { server_thread_.join(); }
  24830. }
  24831. std::string url() const {
  24832. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24833. }
  24834. void ConnectWithClientCert(const std::string &client_cert_file,
  24835. const std::string &client_private_key_file,
  24836. const char *private_key_password) {
  24837. std::string cert_pem, key_pem;
  24838. read_file(client_cert_file, cert_pem);
  24839. read_file(client_private_key_file, key_pem);
  24840. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24841. key_pem.c_str(), key_pem.size(),
  24842. private_key_password};
  24843. ConnectWithPem(pem);
  24844. }
  24845. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24846. ws::WebSocketClient client(url(), pem);
  24847. ASSERT_TRUE(client.is_valid());
  24848. client.enable_server_certificate_verification(false);
  24849. ASSERT_TRUE(client.connect());
  24850. ASSERT_TRUE(client.send("hello"));
  24851. std::string msg;
  24852. EXPECT_EQ(ws::Text, client.read(msg));
  24853. EXPECT_EQ("hello", msg);
  24854. client.close();
  24855. }
  24856. std::unique_ptr<SSLServer> server_;
  24857. std::thread server_thread_;
  24858. int port_ = 0;
  24859. };
  24860. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24861. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24862. }
  24863. // Control for the tests above: the fixture's server really does require a
  24864. // client certificate, so it is the PEM the constructor installed that decides
  24865. // the outcome.
  24866. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24867. ws::WebSocketClient client(url());
  24868. ASSERT_TRUE(client.is_valid());
  24869. client.enable_server_certificate_verification(false);
  24870. EXPECT_FALSE(client.connect());
  24871. }
  24872. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24873. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24874. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24875. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24876. }
  24877. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24878. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24879. std::string cert_pem, key_pem;
  24880. read_file(CLIENT_CERT_FILE, cert_pem);
  24881. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24882. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24883. std::vector<char> key(key_pem.begin(), key_pem.end());
  24884. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24885. key.size(), nullptr};
  24886. ConnectWithPem(pem);
  24887. }
  24888. #endif
  24889. #if !defined(_WIN32)
  24890. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24891. auto secret_dir = std::string("./symlink_test_secret");
  24892. auto served_dir = std::string("./symlink_test_served");
  24893. auto secret_file = secret_dir + "/secret.txt";
  24894. auto symlink_path = served_dir + "/escape";
  24895. // Setup: create directories and files
  24896. mkdir(secret_dir.c_str(), 0755);
  24897. mkdir(served_dir.c_str(), 0755);
  24898. {
  24899. std::ofstream ofs(secret_file);
  24900. ofs << "SECRET_DATA";
  24901. }
  24902. // Create symlink using absolute path so it resolves correctly
  24903. #ifdef PATH_MAX
  24904. char abs_secret[PATH_MAX];
  24905. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24906. #else
  24907. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24908. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24909. ASSERT_NE(nullptr, abs_secret);
  24910. #endif
  24911. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24912. auto se = detail::scope_exit([&] {
  24913. unlink(symlink_path.c_str());
  24914. unlink(secret_file.c_str());
  24915. rmdir(served_dir.c_str());
  24916. rmdir(secret_dir.c_str());
  24917. });
  24918. Server svr;
  24919. svr.set_mount_point("/", served_dir);
  24920. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24921. auto se2 = detail::scope_exit([&] {
  24922. svr.stop();
  24923. listen_thread.join();
  24924. });
  24925. svr.wait_until_ready();
  24926. Client cli("localhost", PORT);
  24927. // Symlink pointing outside base dir should be blocked
  24928. auto res = cli.Get("/escape/secret.txt");
  24929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24930. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24931. }
  24932. #endif
  24933. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24934. // "GET /smuggled" request), reads the first response, and only then sends the
  24935. // embedded request as the body. Returns how many times /smuggled ran.
  24936. //
  24937. // The body is sent AFTER receiving the first response (as in the original
  24938. // PoC) so that the stream_line_reader cannot buffer it together with the
  24939. // headers of the first request.
  24940. static int count_smuggled_requests(const std::string &outer_head,
  24941. std::string &first_response) {
  24942. Server svr;
  24943. svr.set_mount_point("/", "./www");
  24944. std::atomic<int> smuggled_count(0);
  24945. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24946. smuggled_count++;
  24947. res.set_content("oops", "text/plain");
  24948. });
  24949. svr.Post("/post", [&](const Request &req, Response &res) {
  24950. res.set_content(req.body, "text/plain");
  24951. });
  24952. auto port = svr.bind_to_any_port("localhost");
  24953. thread t = thread([&] { svr.listen_after_bind(); });
  24954. auto se = detail::scope_exit([&] {
  24955. svr.stop();
  24956. t.join();
  24957. });
  24958. svr.wait_until_ready();
  24959. auto error = Error::Success;
  24960. auto sock = detail::create_client_socket(
  24961. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24962. /*connection_timeout_sec=*/2, 0,
  24963. /*read_timeout_sec=*/2, 0,
  24964. /*write_timeout_sec=*/2, 0, std::string(), error);
  24965. EXPECT_NE(INVALID_SOCKET, sock);
  24966. if (sock == INVALID_SOCKET) { return -1; }
  24967. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24968. // The "smuggled" request will be sent as the body of the outer request
  24969. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24970. "Host: localhost\r\n"
  24971. "Connection: close\r\n"
  24972. "\r\n";
  24973. auto head = outer_head;
  24974. auto len = std::to_string(smuggled.size());
  24975. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24976. pos = head.find("{len}", pos + len.size())) {
  24977. head.replace(pos, 5, len);
  24978. }
  24979. // Step 1: Send only the outer request headers (no body yet)
  24980. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24981. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24982. // Step 2: Read the first response
  24983. char buf[4096];
  24984. for (;;) {
  24985. auto n = recv(sock, buf, sizeof(buf), 0);
  24986. if (n <= 0) break;
  24987. first_response.append(buf, static_cast<size_t>(n));
  24988. // Stop once we have a complete response (headers + body)
  24989. auto hdr_end = first_response.find("\r\n\r\n");
  24990. if (hdr_end != std::string::npos) {
  24991. // Check for Content-Length to know when the body is complete
  24992. auto cl_pos = first_response.find("Content-Length:");
  24993. if (cl_pos != std::string::npos) {
  24994. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24995. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24996. auto cl = std::stoul(
  24997. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24998. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24999. } else {
  25000. break; // No Content-Length, assume headers-only response
  25001. }
  25002. }
  25003. }
  25004. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25005. // vulnerable server the keep-alive loop reads this as a second request. The
  25006. // server may already have closed the connection, so the result is ignored.
  25007. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25008. // Half-close so that a server which drained the body sees EOF and closes,
  25009. // instead of the read below waiting for the read timeout.
  25010. #ifdef _WIN32
  25011. ::shutdown(sock, SD_SEND);
  25012. #else
  25013. ::shutdown(sock, SHUT_WR);
  25014. #endif
  25015. // Step 4: Read until the server closes the connection
  25016. for (;;) {
  25017. auto n = recv(sock, buf, sizeof(buf), 0);
  25018. if (n <= 0) break;
  25019. }
  25020. return smuggled_count.load();
  25021. }
  25022. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25023. // A GET request with Content-Length to a static file handler must have its
  25024. // body drained before the keep-alive connection is reused. Otherwise the
  25025. // unread body bytes are interpreted as the next HTTP request.
  25026. std::string first_response;
  25027. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25028. "Host: localhost\r\n"
  25029. "Content-Length: {len}\r\n"
  25030. "\r\n",
  25031. first_response));
  25032. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25033. }
  25034. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25035. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25036. // be answered with 400 and the connection closed. Treating it as "no body"
  25037. // leaves the body to be parsed as the next request.
  25038. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25039. const char *targets[] = {
  25040. "GET /file", // handler that never reads the body
  25041. "GET /not-found", // no handler matches (404)
  25042. "POST /post", // handler that reads the body
  25043. };
  25044. for (auto target : targets) {
  25045. for (auto value : values) {
  25046. std::string first_response;
  25047. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25048. " HTTP/1.1\r\n"
  25049. "Host: localhost\r\n"
  25050. "Content-Length: " +
  25051. value + "\r\n\r\n",
  25052. first_response))
  25053. << target << " with Content-Length: " << value;
  25054. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25055. << target << " with Content-Length: " << value;
  25056. }
  25057. }
  25058. }
  25059. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25060. // A 400 for an unparseable request line leaves the rest of the message
  25061. // unread, so the connection must be closed rather than reused.
  25062. std::string first_response;
  25063. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25064. "Host: localhost\r\n"
  25065. "Content-Length: {len}\r\n"
  25066. "\r\n",
  25067. first_response));
  25068. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25069. }
  25070. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25071. // Same as above for a header block that fails to parse.
  25072. std::string first_response;
  25073. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25074. "Host: localhost\r\n"
  25075. "Bad Header\r\n"
  25076. "Content-Length: {len}\r\n"
  25077. "\r\n",
  25078. first_response));
  25079. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25080. }
  25081. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25082. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25083. // server must not read another request on that connection, even when the
  25084. // request had no body to drain.
  25085. std::string first_response;
  25086. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25087. "Host: localhost\r\n"
  25088. "\r\n",
  25089. first_response));
  25090. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25091. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25092. }
  25093. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25094. // A content reader that stops early leaves the stream inside the body.
  25095. // Draining the whole Content-Length from there, or reading the body again,
  25096. // reads into the next request, and whatever follows is parsed as a request
  25097. // of its own.
  25098. Server svr;
  25099. std::atomic<int> smuggled_count(0);
  25100. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25101. svr.Post("/upload", [](const Request &req, Response &res,
  25102. const ContentReader &content_reader) {
  25103. // Stop at the last chunk, so the whole body has been read however it
  25104. // arrives.
  25105. auto length = req.get_header_value_u64("Content-Length");
  25106. size_t total = 0;
  25107. auto consumed = content_reader([&](const char *, size_t n) {
  25108. total += n;
  25109. return total < length;
  25110. });
  25111. EXPECT_FALSE(consumed);
  25112. if (req.has_param("retry")) {
  25113. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25114. }
  25115. // Replace the 400 the aborted read set, which would close the connection.
  25116. res.set_redirect("/done");
  25117. });
  25118. auto port = svr.bind_to_any_port(HOST);
  25119. thread t = thread([&] { svr.listen_after_bind(); });
  25120. auto se = detail::scope_exit([&] {
  25121. svr.stop();
  25122. t.join();
  25123. });
  25124. svr.wait_until_ready();
  25125. // A front end sees the second request as a POST whose body is the GET. The
  25126. // first body is as long as the POST's headers, so draining it again reads
  25127. // exactly those and leaves the GET to be parsed next.
  25128. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25129. "Host: localhost\r\n"
  25130. "\r\n";
  25131. std::string second_head = "POST /post HTTP/1.1\r\n"
  25132. "Host: localhost\r\n"
  25133. "Content-Length: " +
  25134. std::to_string(inner.size()) +
  25135. "\r\n"
  25136. "\r\n";
  25137. for (auto target : {"/upload", "/upload?retry"}) {
  25138. smuggled_count = 0;
  25139. std::string request = "POST " + std::string(target) +
  25140. " HTTP/1.1\r\n"
  25141. "Host: localhost\r\n"
  25142. "Content-Length: " +
  25143. std::to_string(second_head.size()) +
  25144. "\r\n"
  25145. "\r\n" +
  25146. std::string(second_head.size(), 'A') + second_head +
  25147. inner;
  25148. std::string response;
  25149. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25150. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25151. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25152. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25153. EXPECT_EQ(0, smuggled_count.load()) << target;
  25154. }
  25155. }
  25156. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25157. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25158. // must be rejected with 400 Bad Request.
  25159. Server svr;
  25160. svr.Post("/test", [&](const Request &, Response &res) {
  25161. res.set_content("ok", "text/plain");
  25162. });
  25163. thread t = thread([&] { svr.listen(HOST, PORT); });
  25164. auto se = detail::scope_exit([&] {
  25165. svr.stop();
  25166. t.join();
  25167. ASSERT_FALSE(svr.is_running());
  25168. });
  25169. svr.wait_until_ready();
  25170. // Exact "chunked"
  25171. {
  25172. auto req = "POST /test HTTP/1.1\r\n"
  25173. "Host: localhost\r\n"
  25174. "Content-Length: 5\r\n"
  25175. "Transfer-Encoding: chunked\r\n"
  25176. "Connection: close\r\n"
  25177. "\r\n"
  25178. "hello";
  25179. std::string response;
  25180. ASSERT_TRUE(send_request(1, req, &response));
  25181. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25182. response.substr(0, response.find("\r\n")));
  25183. }
  25184. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25185. {
  25186. auto req = "POST /test HTTP/1.1\r\n"
  25187. "Host: localhost\r\n"
  25188. "Content-Length: 5\r\n"
  25189. "Transfer-Encoding: gzip, chunked\r\n"
  25190. "Connection: close\r\n"
  25191. "\r\n"
  25192. "hello";
  25193. std::string response;
  25194. ASSERT_TRUE(send_request(1, req, &response));
  25195. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25196. response.substr(0, response.find("\r\n")));
  25197. }
  25198. }
  25199. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25200. Server svr;
  25201. svr.Post("/test", [&](const Request &, Response &res) {
  25202. res.set_content("ok", "text/plain");
  25203. });
  25204. thread t = thread([&] { svr.listen(HOST, PORT); });
  25205. auto se = detail::scope_exit([&] {
  25206. svr.stop();
  25207. t.join();
  25208. ASSERT_FALSE(svr.is_running());
  25209. });
  25210. svr.wait_until_ready();
  25211. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25212. // length cannot be determined, so the server must answer 400 and close
  25213. // rather than treat the request as bodyless and leave the body in the
  25214. // socket for the next request to pick up.
  25215. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25216. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25217. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25218. std::string response;
  25219. ASSERT_TRUE(send_request(1, req, &response));
  25220. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25221. response.substr(0, response.find("\r\n")))
  25222. << transfer_encoding;
  25223. }
  25224. // RFC 9110 5.3: the codings may also be split across several
  25225. // Transfer-Encoding lines, which combine in the order they were received.
  25226. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25227. // just like the single-line "chunked, gzip" above.
  25228. {
  25229. auto req = "POST /test HTTP/1.1\r\n"
  25230. "Host: localhost\r\n"
  25231. "Transfer-Encoding: chunked\r\n"
  25232. "Transfer-Encoding: gzip\r\n"
  25233. "\r\n"
  25234. "0\r\n\r\n";
  25235. std::string response;
  25236. ASSERT_TRUE(send_request(1, req, &response));
  25237. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25238. response.substr(0, response.find("\r\n")));
  25239. }
  25240. // A sequence ending in chunked stays valid.
  25241. auto req = "POST /test HTTP/1.1\r\n"
  25242. "Host: localhost\r\n"
  25243. "Transfer-Encoding: gzip, chunked\r\n"
  25244. "Connection: close\r\n"
  25245. "\r\n"
  25246. "0\r\n\r\n";
  25247. std::string response;
  25248. ASSERT_TRUE(send_request(1, req, &response));
  25249. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25250. // ...including when it is spread over several lines.
  25251. auto split_req = "POST /test HTTP/1.1\r\n"
  25252. "Host: localhost\r\n"
  25253. "Transfer-Encoding: gzip\r\n"
  25254. "Transfer-Encoding: chunked\r\n"
  25255. "Connection: close\r\n"
  25256. "\r\n"
  25257. "0\r\n\r\n";
  25258. std::string split_response;
  25259. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25260. EXPECT_EQ("HTTP/1.1 200 OK",
  25261. split_response.substr(0, split_response.find("\r\n")));
  25262. }
  25263. // Regression for issue #2450: a DELETE without Content-Length on a
  25264. // keep-alive connection must not let the post-response drain consume the
  25265. // next request's bytes.
  25266. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25267. Server svr;
  25268. std::atomic<int> delete_count(0);
  25269. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25270. delete_count++;
  25271. res.status = StatusCode::NoContent_204;
  25272. });
  25273. auto port = svr.bind_to_any_port(HOST);
  25274. thread t = thread([&] { svr.listen_after_bind(); });
  25275. auto se = detail::scope_exit([&] {
  25276. svr.stop();
  25277. t.join();
  25278. });
  25279. svr.wait_until_ready();
  25280. auto error = Error::Success;
  25281. auto sock = detail::create_client_socket(
  25282. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25283. /*connection_timeout_sec=*/2, 0,
  25284. /*read_timeout_sec=*/2, 0,
  25285. /*write_timeout_sec=*/2, 0, std::string(), error);
  25286. ASSERT_NE(INVALID_SOCKET, sock);
  25287. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25288. auto send_request_and_read_response = [&](const std::string &req,
  25289. std::string &out) -> bool {
  25290. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25291. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25292. char buf[4096];
  25293. for (;;) {
  25294. auto n = recv(sock, buf, sizeof(buf), 0);
  25295. if (n <= 0) { return !out.empty(); }
  25296. out.append(buf, static_cast<size_t>(n));
  25297. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25298. }
  25299. };
  25300. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25301. "Host: localhost\r\n"
  25302. "\r\n";
  25303. std::string resp1;
  25304. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25305. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25306. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25307. "Host: localhost\r\n"
  25308. "Connection: close\r\n"
  25309. "\r\n";
  25310. std::string resp2;
  25311. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25312. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25313. EXPECT_EQ(2, delete_count.load());
  25314. }
  25315. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25316. Server svr;
  25317. svr.Post("/ingest", [&](const Request &, Response &res,
  25318. const ContentReader &content_reader) {
  25319. auto consumed = content_reader([](const char *, size_t) { return false; });
  25320. EXPECT_FALSE(consumed);
  25321. res.status = StatusCode::Conflict_409;
  25322. res.set_header("Connection", "close");
  25323. });
  25324. auto port = svr.bind_to_any_port(HOST);
  25325. thread t = thread([&] { svr.listen_after_bind(); });
  25326. auto se = detail::scope_exit([&] {
  25327. svr.stop();
  25328. t.join();
  25329. });
  25330. svr.wait_until_ready();
  25331. auto error = Error::Success;
  25332. auto sock = detail::create_client_socket(
  25333. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25334. /*connection_timeout_sec=*/2, 0,
  25335. /*read_timeout_sec=*/1, 0,
  25336. /*write_timeout_sec=*/2, 0, std::string(), error);
  25337. ASSERT_NE(INVALID_SOCKET, sock);
  25338. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25339. std::string request = "POST /ingest HTTP/1.1\r\n"
  25340. "Host: localhost\r\n"
  25341. "Transfer-Encoding: chunked\r\n"
  25342. "\r\n"
  25343. "4\r\n"
  25344. "data\r\n";
  25345. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25346. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25347. std::string response;
  25348. ssize_t received = 0;
  25349. do {
  25350. char buf[4096];
  25351. received = recv(sock, buf, sizeof(buf), 0);
  25352. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25353. } while (received > 0);
  25354. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25355. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25356. EXPECT_EQ(0, received);
  25357. }
  25358. namespace no_proxy_test {
  25359. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25360. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25361. // calling listen().
  25362. class ScopedServer {
  25363. public:
  25364. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25365. ~ScopedServer() {
  25366. svr_.stop();
  25367. if (th_.joinable()) { th_.join(); }
  25368. }
  25369. Server &svr() { return svr_; }
  25370. int port() const { return port_; }
  25371. void listen() {
  25372. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25373. svr_.wait_until_ready();
  25374. }
  25375. private:
  25376. Server svr_;
  25377. std::thread th_;
  25378. int port_ = 0;
  25379. };
  25380. class ProxyAndTargetServers {
  25381. public:
  25382. ProxyAndTargetServers() {
  25383. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25384. proxy_hits_++;
  25385. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25386. res.set_content("via-proxy", "text/plain");
  25387. });
  25388. target_.Get(".*", [this](const Request &req, Response &res) {
  25389. target_hits_++;
  25390. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25391. res.set_content("direct", "text/plain");
  25392. });
  25393. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25394. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25395. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25396. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25397. proxy_mock_.wait_until_ready();
  25398. target_.wait_until_ready();
  25399. }
  25400. ~ProxyAndTargetServers() {
  25401. proxy_mock_.stop();
  25402. target_.stop();
  25403. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25404. if (target_thread_.joinable()) { target_thread_.join(); }
  25405. }
  25406. Server &proxy_mock() { return proxy_mock_; }
  25407. Server &target() { return target_; }
  25408. int proxy_port() const { return proxy_port_; }
  25409. int target_port() const { return target_port_; }
  25410. int proxy_hits() const { return proxy_hits_.load(); }
  25411. int target_hits() const { return target_hits_.load(); }
  25412. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25413. void reset_counters() {
  25414. proxy_hits_ = 0;
  25415. target_hits_ = 0;
  25416. last_had_proxy_authz_ = false;
  25417. }
  25418. private:
  25419. Server proxy_mock_;
  25420. Server target_;
  25421. std::thread proxy_thread_;
  25422. std::thread target_thread_;
  25423. int proxy_port_ = 0;
  25424. int target_port_ = 0;
  25425. std::atomic<int> proxy_hits_{0};
  25426. std::atomic<int> target_hits_{0};
  25427. std::atomic<bool> last_had_proxy_authz_{false};
  25428. };
  25429. inline std::unique_ptr<Client> make_client(const std::string &host,
  25430. ProxyAndTargetServers &s) {
  25431. auto cli = detail::make_unique<Client>(host, s.target_port());
  25432. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25433. cli->set_proxy("127.0.0.1", s.proxy_port());
  25434. return cli;
  25435. }
  25436. } // namespace no_proxy_test
  25437. using no_proxy_test::make_client;
  25438. using no_proxy_test::ProxyAndTargetServers;
  25439. // A stream request carries the credentials a buffered request does
  25440. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25441. no_proxy_test::ScopedServer origin;
  25442. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25443. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25444. });
  25445. origin.listen();
  25446. Client cli("127.0.0.1", origin.port());
  25447. cli.set_basic_auth("user", "pass");
  25448. auto handle = cli.open_stream("GET", "/x");
  25449. ASSERT_TRUE(handle.is_valid());
  25450. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25451. Client bearer("127.0.0.1", origin.port());
  25452. bearer.set_bearer_token_auth("tok");
  25453. auto handle2 = bearer.open_stream("GET", "/x");
  25454. ASSERT_TRUE(handle2.is_valid());
  25455. EXPECT_EQ("Bearer tok", read_all(handle2));
  25456. }
  25457. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25458. // takes its own credentials, as for a buffered request
  25459. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25460. std::string target, authz, proxy_authz;
  25461. no_proxy_test::ScopedServer proxy;
  25462. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25463. target = req.target;
  25464. authz = req.get_header_value("Authorization");
  25465. proxy_authz = req.get_header_value("Proxy-Authorization");
  25466. res.set_content("ok", "text/plain");
  25467. });
  25468. proxy.listen();
  25469. Client cli("origin.example", 8080);
  25470. cli.set_proxy("127.0.0.1", proxy.port());
  25471. cli.set_proxy_basic_auth("puser", "ppass");
  25472. cli.set_basic_auth("user", "pass");
  25473. auto handle = cli.open_stream("GET", "/x");
  25474. ASSERT_TRUE(handle.is_valid());
  25475. EXPECT_EQ("ok", read_all(handle));
  25476. EXPECT_EQ("http://origin.example:8080/x", target);
  25477. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25478. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25479. }
  25480. TEST(NoProxyTest, ExactHostnameBypasses) {
  25481. ProxyAndTargetServers s;
  25482. auto cli = make_client("example.com", s);
  25483. cli->set_no_proxy({"example.com"});
  25484. auto res = cli->Get("/");
  25485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25486. EXPECT_EQ(0, s.proxy_hits());
  25487. EXPECT_EQ(1, s.target_hits());
  25488. }
  25489. TEST(NoProxyTest, SubdomainBypasses) {
  25490. ProxyAndTargetServers s;
  25491. auto cli = make_client("foo.example.com", s);
  25492. cli->set_no_proxy({"example.com"});
  25493. auto res = cli->Get("/");
  25494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25495. EXPECT_EQ(0, s.proxy_hits());
  25496. EXPECT_EQ(1, s.target_hits());
  25497. }
  25498. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25499. // Regression guard: "evilexample.com" must not be considered a subdomain
  25500. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25501. // check would let traffic bypass the proxy and leak credentials direct
  25502. // to the attacker host.
  25503. ProxyAndTargetServers s;
  25504. auto cli = make_client("evilexample.com", s);
  25505. cli->set_no_proxy({"example.com"});
  25506. auto res = cli->Get("/");
  25507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25508. EXPECT_GE(s.proxy_hits(), 1);
  25509. EXPECT_EQ(0, s.target_hits());
  25510. }
  25511. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25512. ProxyAndTargetServers s;
  25513. auto cli = make_client("example.com.evil.com", s);
  25514. cli->set_no_proxy({"example.com"});
  25515. auto res = cli->Get("/");
  25516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25517. EXPECT_GE(s.proxy_hits(), 1);
  25518. EXPECT_EQ(0, s.target_hits());
  25519. }
  25520. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25521. ProxyAndTargetServers s;
  25522. auto cli = make_client("example.com", s);
  25523. cli->set_no_proxy({".example.com"});
  25524. auto res = cli->Get("/");
  25525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25526. EXPECT_EQ(0, s.proxy_hits());
  25527. EXPECT_EQ(1, s.target_hits());
  25528. }
  25529. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25530. ProxyAndTargetServers s;
  25531. auto cli = make_client("Example.COM", s);
  25532. cli->set_no_proxy({"EXAMPLE.com"});
  25533. auto res = cli->Get("/");
  25534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25535. EXPECT_EQ(0, s.proxy_hits());
  25536. EXPECT_EQ(1, s.target_hits());
  25537. }
  25538. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25539. ProxyAndTargetServers s;
  25540. auto cli = make_client("example.com.", s);
  25541. cli->set_no_proxy({"example.com"});
  25542. auto res = cli->Get("/");
  25543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25544. EXPECT_EQ(0, s.proxy_hits());
  25545. EXPECT_EQ(1, s.target_hits());
  25546. }
  25547. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25548. // Trailing dots must be normalized on BOTH sides — host and entry.
  25549. // An implementation that only strips the host-side trailing dot would
  25550. // fail to match host "example.com" against entry "example.com." because
  25551. // a literal substring search would compare 11 chars against 12.
  25552. ProxyAndTargetServers s;
  25553. auto cli = make_client("example.com", s);
  25554. cli->set_no_proxy({"example.com."});
  25555. auto res = cli->Get("/");
  25556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25557. EXPECT_EQ(0, s.proxy_hits());
  25558. EXPECT_EQ(1, s.target_hits());
  25559. }
  25560. TEST(NoProxyTest, WildcardBypassesEverything) {
  25561. ProxyAndTargetServers s;
  25562. auto cli = make_client("anything.invalid.test", s);
  25563. cli->set_no_proxy({"*"});
  25564. auto res = cli->Get("/");
  25565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25566. EXPECT_EQ(0, s.proxy_hits());
  25567. EXPECT_EQ(1, s.target_hits());
  25568. }
  25569. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25570. ProxyAndTargetServers s;
  25571. Client cli("127.0.0.1", s.target_port());
  25572. cli.set_proxy("127.0.0.1", s.proxy_port());
  25573. cli.set_no_proxy({"127.0.0.1"});
  25574. auto res = cli.Get("/");
  25575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25576. EXPECT_EQ(0, s.proxy_hits());
  25577. EXPECT_EQ(1, s.target_hits());
  25578. }
  25579. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25580. ProxyAndTargetServers s;
  25581. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25582. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25583. cli.set_proxy("127.0.0.1", s.proxy_port());
  25584. cli.set_no_proxy({"::1"});
  25585. auto res = cli.Get("/");
  25586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25587. EXPECT_EQ(0, s.proxy_hits());
  25588. EXPECT_EQ(1, s.target_hits());
  25589. }
  25590. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25591. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25592. // must still be recognized as IPv6 for CIDR matching. Implementations
  25593. // that detect IPv6 only when the host begins with '[' would parse the
  25594. // host as a hostname and miss the match.
  25595. ProxyAndTargetServers s;
  25596. Client cli("fe80::1", s.target_port());
  25597. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25598. cli.set_proxy("127.0.0.1", s.proxy_port());
  25599. cli.set_no_proxy({"fe80::/10"});
  25600. auto res = cli.Get("/");
  25601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25602. EXPECT_EQ(0, s.proxy_hits());
  25603. EXPECT_EQ(1, s.target_hits());
  25604. }
  25605. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25606. ProxyAndTargetServers s;
  25607. Client cli("::1", s.target_port());
  25608. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25609. cli.set_proxy("127.0.0.1", s.proxy_port());
  25610. cli.set_no_proxy({"[::1]"});
  25611. auto res = cli.Get("/");
  25612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25613. EXPECT_EQ(0, s.proxy_hits());
  25614. EXPECT_EQ(1, s.target_hits());
  25615. }
  25616. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25617. ProxyAndTargetServers s;
  25618. Client cli("fe80::1", s.target_port());
  25619. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25620. cli.set_proxy("127.0.0.1", s.proxy_port());
  25621. cli.set_no_proxy({"[fe80::]/10"});
  25622. auto res = cli.Get("/");
  25623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25624. EXPECT_EQ(0, s.proxy_hits());
  25625. EXPECT_EQ(1, s.target_hits());
  25626. }
  25627. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25628. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25629. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25630. // tricks via address-family conversion.
  25631. ProxyAndTargetServers s;
  25632. Client cli("::ffff:127.0.0.1", s.target_port());
  25633. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25634. cli.set_proxy("127.0.0.1", s.proxy_port());
  25635. cli.set_no_proxy({"127.0.0.1"});
  25636. auto res = cli.Get("/");
  25637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25638. EXPECT_GE(s.proxy_hits(), 1);
  25639. EXPECT_EQ(0, s.target_hits());
  25640. }
  25641. TEST(NoProxyTest, IPv4CidrMatch) {
  25642. ProxyAndTargetServers s;
  25643. Client cli("127.0.0.1", s.target_port());
  25644. cli.set_proxy("127.0.0.1", s.proxy_port());
  25645. cli.set_no_proxy({"127.0.0.0/8"});
  25646. auto res = cli.Get("/");
  25647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25648. EXPECT_EQ(0, s.proxy_hits());
  25649. EXPECT_EQ(1, s.target_hits());
  25650. }
  25651. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25652. ProxyAndTargetServers s;
  25653. Client cli("127.0.0.1", s.target_port());
  25654. cli.set_proxy("127.0.0.1", s.proxy_port());
  25655. cli.set_no_proxy({"10.0.0.0/8"});
  25656. auto res = cli.Get("/");
  25657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25658. EXPECT_GE(s.proxy_hits(), 1);
  25659. EXPECT_EQ(0, s.target_hits());
  25660. }
  25661. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25662. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25663. // IPv4 target matches.
  25664. ProxyAndTargetServers s;
  25665. Client cli("127.0.0.1", s.target_port());
  25666. cli.set_proxy("127.0.0.1", s.proxy_port());
  25667. cli.set_no_proxy({"0.0.0.0/0"});
  25668. auto res = cli.Get("/");
  25669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25670. EXPECT_EQ(0, s.proxy_hits());
  25671. EXPECT_EQ(1, s.target_hits());
  25672. }
  25673. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25674. ProxyAndTargetServers s;
  25675. Client cli("127.0.0.1", s.target_port());
  25676. cli.set_proxy("127.0.0.1", s.proxy_port());
  25677. cli.set_no_proxy({"127.0.0.1"});
  25678. auto res = cli.Get("/");
  25679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25680. EXPECT_EQ(0, s.proxy_hits());
  25681. EXPECT_EQ(1, s.target_hits());
  25682. }
  25683. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25684. ProxyAndTargetServers s;
  25685. Client cli("127.0.0.1", s.target_port());
  25686. cli.set_proxy("127.0.0.1", s.proxy_port());
  25687. cli.set_no_proxy({"127.0.0.0/33"});
  25688. auto res = cli.Get("/");
  25689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25690. EXPECT_GE(s.proxy_hits(), 1);
  25691. EXPECT_EQ(0, s.target_hits());
  25692. }
  25693. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25694. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25695. ProxyAndTargetServers s;
  25696. Client cli("127.0.0.1", s.target_port());
  25697. cli.set_proxy("127.0.0.1", s.proxy_port());
  25698. cli.set_no_proxy({"127.0.0.1/"});
  25699. auto res = cli.Get("/");
  25700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25701. EXPECT_GE(s.proxy_hits(), 1);
  25702. EXPECT_EQ(0, s.target_hits());
  25703. }
  25704. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25705. ProxyAndTargetServers s;
  25706. auto cli = make_client("internal.corp", s);
  25707. cli->set_proxy_basic_auth("u", "p");
  25708. cli->set_no_proxy({"internal.corp"});
  25709. auto res = cli->Get("/");
  25710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25711. EXPECT_EQ(1, s.target_hits());
  25712. EXPECT_EQ(0, s.proxy_hits());
  25713. EXPECT_FALSE(s.last_had_proxy_authz())
  25714. << "Proxy-Authorization must not be sent direct to the target";
  25715. }
  25716. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25717. ProxyAndTargetServers s;
  25718. auto cli = make_client("public.example", s);
  25719. cli->set_proxy_basic_auth("u", "p");
  25720. cli->set_no_proxy({"internal.corp"}); // does not match
  25721. auto res = cli->Get("/");
  25722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25723. EXPECT_GE(s.proxy_hits(), 1);
  25724. EXPECT_TRUE(s.last_had_proxy_authz());
  25725. }
  25726. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25727. std::atomic<int> hits{0};
  25728. std::atomic<int> hits_with_authz{0};
  25729. no_proxy_test::ScopedServer proxy_mock;
  25730. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25731. hits++;
  25732. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25733. if (req.target.find("/redir") != std::string::npos) {
  25734. res.set_redirect("http://other.example/landed");
  25735. } else {
  25736. res.set_content("via-proxy", "text/plain");
  25737. }
  25738. });
  25739. proxy_mock.listen();
  25740. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25741. hits = 0;
  25742. hits_with_authz = 0;
  25743. Client cli("public.example", 80);
  25744. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25745. cli.set_proxy_basic_auth(c.first, c.second);
  25746. cli.set_follow_location(true);
  25747. // The redirect to another host goes through the proxy as well
  25748. auto res = cli.Get("/redir");
  25749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25750. EXPECT_EQ(2, hits.load());
  25751. EXPECT_EQ(2, hits_with_authz.load());
  25752. }
  25753. }
  25754. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25755. ProxyAndTargetServers s;
  25756. auto cli = make_client("anything.test", s);
  25757. auto res = cli->Get("/");
  25758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25759. EXPECT_GE(s.proxy_hits(), 1);
  25760. EXPECT_EQ(0, s.target_hits());
  25761. }
  25762. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25763. ProxyAndTargetServers s;
  25764. auto cli = make_client("example.com", s);
  25765. cli->set_no_proxy({"example.com:8080"});
  25766. auto res = cli->Get("/");
  25767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25768. EXPECT_GE(s.proxy_hits(), 1);
  25769. EXPECT_EQ(0, s.target_hits());
  25770. }
  25771. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25772. ProxyAndTargetServers s;
  25773. auto cli = make_client("anything.test", s);
  25774. cli->set_no_proxy({"", " ", "\t"});
  25775. auto res = cli->Get("/");
  25776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25777. EXPECT_GE(s.proxy_hits(), 1);
  25778. EXPECT_EQ(0, s.target_hits());
  25779. }
  25780. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25781. // An entry with leading/trailing whitespace must still match — env-style
  25782. // values are commonly pasted with stray spaces and an implementation
  25783. // that feeds the raw token directly to inet_pton would fail to match
  25784. // valid CIDRs because of the spaces.
  25785. ProxyAndTargetServers s;
  25786. Client cli("127.0.0.1", s.target_port());
  25787. cli.set_proxy("127.0.0.1", s.proxy_port());
  25788. cli.set_no_proxy({" 127.0.0.0/8 "});
  25789. auto res = cli.Get("/");
  25790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25791. EXPECT_EQ(0, s.proxy_hits());
  25792. EXPECT_EQ(1, s.target_hits());
  25793. }
  25794. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25795. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25796. // go direct and must NOT carry Proxy-Authorization.
  25797. std::atomic<int> proxy_hits{0};
  25798. std::atomic<int> target_hits{0};
  25799. std::atomic<bool> target_saw_authz{false};
  25800. no_proxy_test::ScopedServer proxy_mock, target;
  25801. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25802. proxy_hits++;
  25803. res.status = 302;
  25804. res.set_header("Location", "http://127.0.0.1:" +
  25805. std::to_string(target.port()) + "/landed");
  25806. });
  25807. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25808. target_hits++;
  25809. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25810. res.set_content("direct", "text/plain");
  25811. });
  25812. proxy_mock.listen();
  25813. target.listen();
  25814. Client cli("public.example", target.port());
  25815. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25816. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25817. cli.set_proxy_basic_auth("u", "p");
  25818. cli.set_no_proxy({"127.0.0.1"});
  25819. cli.set_follow_location(true);
  25820. auto res = cli.Get("/redir");
  25821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25822. EXPECT_GE(proxy_hits.load(), 1);
  25823. EXPECT_GE(target_hits.load(), 1);
  25824. EXPECT_FALSE(target_saw_authz.load());
  25825. }
  25826. #ifdef CPPHTTPLIB_SSL_ENABLED
  25827. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25828. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25829. // proxy creds would be sent to the (possibly hostile) origin.
  25830. std::atomic<int> target_hits{0};
  25831. std::atomic<bool> target_saw_proxy_authz{false};
  25832. no_proxy_test::ScopedServer target;
  25833. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25834. target_hits++;
  25835. if (req.has_header("Proxy-Authorization")) {
  25836. target_saw_proxy_authz = true;
  25837. }
  25838. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25839. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25840. "nonce=\"abc\", algorithm=MD5");
  25841. });
  25842. target.listen();
  25843. // The proxy address is set to the target's port: the bypass MUST kick in;
  25844. // if it doesn't, the test still routes "via proxy" to the same server and
  25845. // the Proxy-Authorization assertion below catches the leak.
  25846. Client cli("evil.example", target.port());
  25847. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25848. cli.set_proxy("127.0.0.1", target.port());
  25849. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25850. cli.set_no_proxy({"evil.example"});
  25851. auto res = cli.Get("/x");
  25852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25853. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25854. EXPECT_EQ(1, target_hits.load());
  25855. EXPECT_FALSE(target_saw_proxy_authz.load());
  25856. }
  25857. #endif
  25858. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25859. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25860. std::atomic<int> proxy_hits{0};
  25861. std::atomic<int> bypass_hits{0};
  25862. std::atomic<bool> proxy_saw_c_url{false};
  25863. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25864. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25865. proxy_hits++;
  25866. if (req.path.find("/start") != std::string::npos) {
  25867. res.status = 302;
  25868. res.set_header("Location", "http://127.0.0.1:" +
  25869. std::to_string(bypass_server.port()) +
  25870. "/middle");
  25871. return;
  25872. }
  25873. if (req.path.find("/end") != std::string::npos) {
  25874. proxy_saw_c_url = true;
  25875. res.set_content("c-via-proxy", "text/plain");
  25876. return;
  25877. }
  25878. res.set_content("unexpected", "text/plain");
  25879. });
  25880. // public.example's "advertised" port is arbitrary (the request never lands
  25881. // there — it goes through the proxy), but use a dynamic value to stay
  25882. // friendly with sharded parallel runs.
  25883. int public_port = bypass_server.port();
  25884. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25885. bypass_hits++;
  25886. res.status = 302;
  25887. res.set_header("Location", "http://public.example:" +
  25888. std::to_string(public_port) + "/end");
  25889. });
  25890. proxy_mock.listen();
  25891. bypass_server.listen();
  25892. Client cli("public.example", public_port);
  25893. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25894. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25895. cli.set_no_proxy({"127.0.0.1"});
  25896. cli.set_follow_location(true);
  25897. auto res = cli.Get("/start");
  25898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25899. EXPECT_EQ(StatusCode::OK_200, res->status);
  25900. EXPECT_EQ("c-via-proxy", res->body);
  25901. EXPECT_GE(proxy_hits.load(), 2);
  25902. EXPECT_GE(bypass_hits.load(), 1);
  25903. EXPECT_TRUE(proxy_saw_c_url.load());
  25904. }
  25905. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25906. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25907. // request reconnects to the correct endpoint.
  25908. std::atomic<int> proxy_hits{0};
  25909. std::atomic<int> target_hits{0};
  25910. no_proxy_test::ScopedServer proxy_mock, target;
  25911. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25912. proxy_hits++;
  25913. res.set_content("via-proxy", "text/plain");
  25914. });
  25915. target.svr().Get(".*", [&](const Request &, Response &res) {
  25916. target_hits++;
  25917. res.set_content("direct", "text/plain");
  25918. });
  25919. proxy_mock.listen();
  25920. target.listen();
  25921. Client cli("public.example", target.port());
  25922. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25923. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25924. cli.set_keep_alive(true);
  25925. auto res1 = cli.Get("/a");
  25926. ASSERT_TRUE(res1);
  25927. EXPECT_EQ("via-proxy", res1->body);
  25928. EXPECT_EQ(1, proxy_hits.load());
  25929. EXPECT_EQ(0, target_hits.load());
  25930. cli.set_no_proxy({"public.example"});
  25931. auto res2 = cli.Get("/b");
  25932. ASSERT_TRUE(res2);
  25933. EXPECT_EQ("direct", res2->body);
  25934. EXPECT_EQ(1, proxy_hits.load());
  25935. EXPECT_EQ(1, target_hits.load());
  25936. }
  25937. // Forward declarations (see the base64_encode note).
  25938. namespace httplib {
  25939. namespace detail {
  25940. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25941. int shutdown_socket(socket_t sock) noexcept;
  25942. } // namespace detail
  25943. } // namespace httplib
  25944. namespace proxy_tunnel_test {
  25945. const char *const kTunnelEstablished =
  25946. "HTTP/1.1 200 Connection established\r\n\r\n";
  25947. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25948. using ConnectReply = std::function<std::string(const std::string &head)>;
  25949. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25950. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25951. class ScopedConnectProxy {
  25952. public:
  25953. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25954. : forward_port_(forward_port), reply_(std::move(reply)) {
  25955. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25956. if (listen_sock_ == INVALID_SOCKET) { return; }
  25957. auto a = loopback(0);
  25958. auto addr = reinterpret_cast<sockaddr *>(&a);
  25959. socklen_t alen = sizeof(a);
  25960. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25961. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25962. ::listen(listen_sock_, 4) != 0) {
  25963. return;
  25964. }
  25965. port_ = ntohs(a.sin_port);
  25966. th_ = std::thread([this] { run(); });
  25967. }
  25968. ~ScopedConnectProxy() {
  25969. if (th_.joinable()) {
  25970. stop_ = true;
  25971. auto wake = connect_to(port_);
  25972. th_.join();
  25973. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25974. }
  25975. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25976. }
  25977. int port() const { return port_; }
  25978. int connect_hits() const { return connect_hits_.load(); }
  25979. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25980. std::string connect_request() const {
  25981. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25982. return connect_request_;
  25983. }
  25984. private:
  25985. static sockaddr_in loopback(int port) {
  25986. sockaddr_in a{};
  25987. a.sin_family = AF_INET;
  25988. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25989. a.sin_port = htons(static_cast<unsigned short>(port));
  25990. return a;
  25991. }
  25992. static socket_t connect_to(int port) {
  25993. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25994. if (sock == INVALID_SOCKET) { return sock; }
  25995. auto a = loopback(port);
  25996. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25997. detail::close_socket(sock);
  25998. return INVALID_SOCKET;
  25999. }
  26000. return sock;
  26001. }
  26002. static bool send_all(socket_t sock, const char *data, size_t size) {
  26003. while (size > 0) {
  26004. auto n = detail::send_socket(sock, data, size, 0);
  26005. if (n <= 0) { return false; }
  26006. data += n;
  26007. size -= static_cast<size_t>(n);
  26008. }
  26009. return true;
  26010. }
  26011. void run() {
  26012. for (;;) {
  26013. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26014. if (stop_) {
  26015. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26016. return;
  26017. }
  26018. if (client == INVALID_SOCKET) { continue; }
  26019. serve(client);
  26020. detail::close_socket(client);
  26021. }
  26022. }
  26023. void serve(socket_t client) {
  26024. std::string head;
  26025. char buf[2048];
  26026. while (head.find("\r\n\r\n") == std::string::npos) {
  26027. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26028. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26029. if (n <= 0) { return; }
  26030. head.append(buf, static_cast<size_t>(n));
  26031. }
  26032. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26033. connect_hits_++;
  26034. {
  26035. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26036. connect_request_ = head;
  26037. }
  26038. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26039. if (!send_all(client, res.data(), res.size()) ||
  26040. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26041. return;
  26042. }
  26043. auto origin = connect_to(forward_port_);
  26044. if (origin == INVALID_SOCKET) { return; }
  26045. // When either side stops, shut both down so the other pump returns too.
  26046. auto pump = [&](socket_t from, socket_t to) {
  26047. char b[8192];
  26048. for (;;) {
  26049. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26050. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26051. }
  26052. detail::shutdown_socket(client);
  26053. detail::shutdown_socket(origin);
  26054. };
  26055. std::thread up([&] { pump(client, origin); });
  26056. pump(origin, client);
  26057. up.join();
  26058. detail::close_socket(origin);
  26059. }
  26060. int forward_port_;
  26061. ConnectReply reply_;
  26062. socket_t listen_sock_ = INVALID_SOCKET;
  26063. int port_ = 0;
  26064. std::thread th_;
  26065. std::atomic<bool> stop_{false};
  26066. std::atomic<int> connect_hits_{0};
  26067. mutable std::mutex connect_request_mutex_;
  26068. std::string connect_request_;
  26069. };
  26070. } // namespace proxy_tunnel_test
  26071. #ifdef CPPHTTPLIB_SSL_ENABLED
  26072. namespace proxy_tunnel_test {
  26073. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26074. class ScopedSSLServer {
  26075. public:
  26076. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26077. port_ = svr_.bind_to_any_port("127.0.0.1");
  26078. }
  26079. ~ScopedSSLServer() {
  26080. svr_.stop();
  26081. if (th_.joinable()) { th_.join(); }
  26082. }
  26083. SSLServer &svr() { return svr_; }
  26084. int port() const { return port_; }
  26085. void listen() {
  26086. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26087. svr_.wait_until_ready();
  26088. }
  26089. private:
  26090. SSLServer svr_;
  26091. std::thread th_;
  26092. int port_ = 0;
  26093. };
  26094. // Sends one request through the CONNECT proxy to the TLS origin with a
  26095. // credential configured for each hop, and checks that each credential reaches
  26096. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26097. // origin's (every header in origin_headers) on the tunnelled request.
  26098. void CredentialsStayWithTheirHop(
  26099. const std::function<void(SSLClient &)> &set_credentials,
  26100. const std::string &scheme,
  26101. const std::vector<std::string> &origin_headers = {"Authorization"},
  26102. bool stream = false) {
  26103. std::atomic<int> origin_hits{0};
  26104. std::atomic<bool> origin_saw_proxy_authz{false};
  26105. std::atomic<bool> origin_saw_headers{false};
  26106. ScopedSSLServer origin;
  26107. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26108. origin_hits++;
  26109. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26110. origin_saw_headers =
  26111. std::all_of(origin_headers.begin(), origin_headers.end(),
  26112. [&](const std::string &h) { return req.has_header(h); });
  26113. res.set_content("ok", "text/plain");
  26114. });
  26115. origin.listen();
  26116. ScopedConnectProxy proxy(origin.port());
  26117. ASSERT_NE(0, proxy.port());
  26118. // Pinned to 127.0.0.1 for the same reason as the test below.
  26119. SSLClient cli("127.0.0.1", origin.port());
  26120. cli.enable_server_certificate_verification(false);
  26121. cli.set_proxy("127.0.0.1", proxy.port());
  26122. set_credentials(cli);
  26123. if (stream) {
  26124. auto handle = cli.open_stream("GET", "/x");
  26125. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26126. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26127. } else {
  26128. auto res = cli.Get("/x");
  26129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26130. EXPECT_EQ(StatusCode::OK_200, res->status);
  26131. }
  26132. EXPECT_EQ(1, origin_hits.load());
  26133. EXPECT_EQ(1, proxy.connect_hits());
  26134. EXPECT_TRUE(origin_saw_headers.load());
  26135. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26136. << "Proxy-Authorization must not be sent inside the tunnel";
  26137. auto connect_req = proxy.connect_request();
  26138. EXPECT_NE(std::string::npos,
  26139. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26140. for (const auto &h : origin_headers) {
  26141. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26142. << h << " must not be sent to the proxy on CONNECT";
  26143. }
  26144. }
  26145. } // namespace proxy_tunnel_test
  26146. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26147. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26148. [](SSLClient &cli) {
  26149. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26150. cli.set_basic_auth("origin-user", "origin-pass");
  26151. },
  26152. "Basic");
  26153. }
  26154. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26155. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26156. [](SSLClient &cli) {
  26157. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26158. cli.set_basic_auth("origin-user", "origin-pass");
  26159. },
  26160. "Basic", {"Authorization"}, true);
  26161. }
  26162. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26163. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26164. [](SSLClient &cli) {
  26165. cli.set_proxy_bearer_token_auth("proxy-token");
  26166. cli.set_bearer_token_auth("origin-token");
  26167. },
  26168. "Bearer");
  26169. }
  26170. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26171. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26172. [](SSLClient &cli) {
  26173. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26174. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26175. {"Cookie", "sid=origin-session"},
  26176. {"X-Api-Key", "origin-key"}});
  26177. },
  26178. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26179. }
  26180. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26181. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26182. // retry; otherwise proxy creds would be sent to the origin.
  26183. std::atomic<int> origin_hits{0};
  26184. std::atomic<bool> origin_saw_proxy_authz{false};
  26185. proxy_tunnel_test::ScopedSSLServer origin;
  26186. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26187. origin_hits++;
  26188. if (req.has_header("Proxy-Authorization")) {
  26189. origin_saw_proxy_authz = true;
  26190. }
  26191. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26192. res.set_header("Proxy-Authenticate",
  26193. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26194. "algorithm=MD5");
  26195. });
  26196. origin.listen();
  26197. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26198. ASSERT_NE(0, proxy.port());
  26199. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26200. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26201. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26202. // and answer with its own status, making this test flaky.
  26203. SSLClient cli("127.0.0.1", origin.port());
  26204. cli.enable_server_certificate_verification(false);
  26205. cli.set_proxy("127.0.0.1", proxy.port());
  26206. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26207. auto res = cli.Get("/x");
  26208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26209. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26210. EXPECT_EQ(1, origin_hits.load());
  26211. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26212. EXPECT_EQ(1, proxy.connect_hits());
  26213. }
  26214. #endif
  26215. namespace proxy_tunnel_test {
  26216. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26217. // anything else gets a 407 with `challenge`.
  26218. ConnectReply require_proxy_auth(const std::string &expected,
  26219. const std::string &challenge) {
  26220. return [=](const std::string &head) -> std::string {
  26221. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26222. std::string::npos) {
  26223. return kTunnelEstablished;
  26224. }
  26225. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26226. "Proxy-Authenticate: " +
  26227. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26228. };
  26229. }
  26230. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26231. // request, then echoes.
  26232. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26233. ws.send(
  26234. "authorization:" + req.get_header_value("Authorization") +
  26235. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26236. std::string msg;
  26237. while (ws.read(msg)) {
  26238. ws.send(msg);
  26239. }
  26240. }
  26241. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26242. class ScopedWebSocketOrigin {
  26243. public:
  26244. ScopedWebSocketOrigin() {
  26245. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26246. server_.listen();
  26247. }
  26248. int port() const { return server_.port(); }
  26249. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26250. std::string url() const {
  26251. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26252. }
  26253. private:
  26254. no_proxy_test::ScopedServer server_;
  26255. };
  26256. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26257. // passed as a constructor header, and checks that each reaches only its hop.
  26258. void WebSocketCredentialsStayWithTheirHop(
  26259. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26260. const std::string &proxy_authz, const std::string &origin_authz) {
  26261. ScopedWebSocketOrigin origin;
  26262. ScopedConnectProxy proxy(
  26263. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26264. ASSERT_NE(0, proxy.port());
  26265. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26266. client.set_proxy("127.0.0.1", proxy.port());
  26267. set_proxy_credentials(client);
  26268. auto res = client.connect();
  26269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26270. std::string msg;
  26271. ASSERT_TRUE(client.read(msg));
  26272. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26273. client.close();
  26274. EXPECT_EQ(1, proxy.connect_hits());
  26275. EXPECT_EQ(std::string::npos,
  26276. proxy.connect_request().find("\r\nAuthorization: "))
  26277. << "origin credentials must not be sent to the proxy";
  26278. }
  26279. } // namespace proxy_tunnel_test
  26280. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26281. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26282. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26283. ASSERT_NE(0, proxy.port());
  26284. ws::WebSocketClient client(origin.url());
  26285. client.set_proxy("127.0.0.1", proxy.port());
  26286. auto res = client.connect();
  26287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26288. std::string msg;
  26289. ASSERT_TRUE(client.read(msg));
  26290. ASSERT_TRUE(client.send("hello"));
  26291. ASSERT_TRUE(client.read(msg));
  26292. EXPECT_EQ("hello", msg);
  26293. client.close();
  26294. EXPECT_EQ(1, proxy.connect_hits());
  26295. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26296. auto connect_req = proxy.connect_request();
  26297. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26298. EXPECT_NE(std::string::npos,
  26299. connect_req.find("\r\nHost: " + target + "\r\n"));
  26300. }
  26301. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26302. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26303. [](ws::WebSocketClient &cli) {
  26304. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26305. },
  26306. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26307. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26308. }
  26309. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26310. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26311. [](ws::WebSocketClient &cli) {
  26312. cli.set_proxy_bearer_token_auth("proxy-token");
  26313. },
  26314. "Bearer proxy-token", "Bearer origin-token");
  26315. }
  26316. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26317. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26318. proxy_tunnel_test::ScopedConnectProxy proxy(
  26319. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26320. "Basic " + detail::base64_encode("proxy-user:"),
  26321. "Basic realm=\"proxy\""));
  26322. ASSERT_NE(0, proxy.port());
  26323. ws::WebSocketClient client(origin.url());
  26324. client.set_proxy("127.0.0.1", proxy.port());
  26325. client.set_proxy_basic_auth("proxy-user", "");
  26326. auto res = client.connect();
  26327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26328. client.close();
  26329. EXPECT_EQ(1, proxy.connect_hits());
  26330. }
  26331. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26332. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26333. proxy_tunnel_test::ScopedConnectProxy proxy(
  26334. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26335. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26336. ASSERT_NE(0, proxy.port());
  26337. ws::WebSocketClient client(origin.url());
  26338. client.set_proxy("127.0.0.1", proxy.port());
  26339. auto res = client.connect();
  26340. EXPECT_FALSE(res);
  26341. EXPECT_EQ(Error::ProxyConnection, res.error());
  26342. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26343. EXPECT_EQ("Basic realm=\"proxy\"",
  26344. res.get_header_value("Proxy-Authenticate"));
  26345. EXPECT_FALSE(client.is_open());
  26346. }
  26347. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26348. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26349. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26350. ASSERT_NE(0, proxy.port());
  26351. ws::WebSocketClient client(origin.url());
  26352. client.set_proxy("127.0.0.1", proxy.port());
  26353. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26354. client.set_no_proxy({"127.0.0.1"});
  26355. auto res = client.connect();
  26356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26357. std::string msg;
  26358. ASSERT_TRUE(client.read(msg));
  26359. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26360. << "proxy credentials must not reach a bypassed origin";
  26361. client.close();
  26362. EXPECT_EQ(0, proxy.connect_hits());
  26363. }
  26364. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26365. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26366. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26367. ASSERT_NE(0, proxy.port());
  26368. ws::WebSocketClient client(origin.url());
  26369. client.set_proxy("127.0.0.1", proxy.port());
  26370. ASSERT_TRUE(client.connect());
  26371. ASSERT_TRUE(client.connect());
  26372. client.close();
  26373. EXPECT_EQ(2, proxy.connect_hits());
  26374. }
  26375. #ifdef CPPHTTPLIB_SSL_ENABLED
  26376. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26377. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26378. proxy_tunnel_test::ScopedConnectProxy proxy(
  26379. origin.port(), [](const std::string &head) -> std::string {
  26380. if (head.find(
  26381. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26382. std::string::npos) {
  26383. return proxy_tunnel_test::kTunnelEstablished;
  26384. }
  26385. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26386. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26387. "nonce=\"abc\", algorithm=MD5\r\n"
  26388. "Content-Length: 0\r\n\r\n";
  26389. });
  26390. ASSERT_NE(0, proxy.port());
  26391. ws::WebSocketClient client(origin.url());
  26392. client.set_proxy("127.0.0.1", proxy.port());
  26393. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26394. auto res = client.connect();
  26395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26396. std::string msg;
  26397. ASSERT_TRUE(client.read(msg));
  26398. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26399. client.close();
  26400. EXPECT_EQ(2, proxy.connect_hits());
  26401. }
  26402. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26403. proxy_tunnel_test::ScopedSSLServer origin;
  26404. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26405. origin.listen();
  26406. proxy_tunnel_test::ScopedConnectProxy proxy(
  26407. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26408. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26409. ASSERT_NE(0, proxy.port());
  26410. ws::WebSocketClient client(
  26411. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26412. client.enable_server_certificate_verification(false);
  26413. client.set_proxy("127.0.0.1", proxy.port());
  26414. client.set_proxy_bearer_token_auth("proxy-token");
  26415. auto res = client.connect();
  26416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26417. std::string msg;
  26418. ASSERT_TRUE(client.read(msg));
  26419. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26420. << "Proxy-Authorization must not be sent inside the tunnel";
  26421. client.close();
  26422. EXPECT_EQ(1, proxy.connect_hits());
  26423. }
  26424. #endif