test.cc 1017 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265
  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. Server svr;
  9527. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9528. // res.headers is a public field an application can populate directly,
  9529. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9530. // A valid header that must survive.
  9531. res.headers.emplace("X-Safe", "safe");
  9532. // Attacker-controlled value carrying CR/LF (response splitting).
  9533. res.headers.emplace("X-Reflected",
  9534. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9535. // Attacker-controlled name carrying CR/LF.
  9536. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9537. res.set_content("body", "text/plain");
  9538. });
  9539. thread t = thread([&] { svr.listen(HOST, PORT); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. t.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9547. "Host: " + HOST +
  9548. "\r\n"
  9549. "Connection: close\r\n"
  9550. "\r\n";
  9551. std::string res;
  9552. ASSERT_TRUE(send_request(5, req, &res));
  9553. // The injected fields must not appear anywhere in the raw response.
  9554. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9555. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9556. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9557. // Invalid headers are dropped entirely, matching set_header().
  9558. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9559. // The valid header still passes through.
  9560. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9561. }
  9562. // Forward declaration: in split builds split.py strips `inline` and moves the
  9563. // definition into httplib.cc, so detail::write_request_line is not visible from
  9564. // the public httplib.h. Re-declaring it here lets the tests link against the
  9565. // symbol in both header-only and split builds.
  9566. namespace httplib {
  9567. namespace detail {
  9568. ssize_t write_request_line(Stream &strm, const std::string &method,
  9569. const std::string &path);
  9570. } // namespace detail
  9571. } // namespace httplib
  9572. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9573. // A well-formed target is written verbatim.
  9574. {
  9575. detail::BufferStream strm;
  9576. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9577. EXPECT_GT(n, 0);
  9578. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9579. }
  9580. // A target carrying CR/LF, SP or other control octets must be rejected
  9581. // before anything reaches the wire, otherwise it splits the request line and
  9582. // injects a header or a whole request.
  9583. const std::string evil_targets[] = {
  9584. "/a\r\nInjected: pwned",
  9585. "/a\rInjected",
  9586. "/a\nInjected",
  9587. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9588. "/a b",
  9589. "/a\tb",
  9590. "/a\x7f",
  9591. };
  9592. for (const auto &evil : evil_targets) {
  9593. detail::BufferStream strm;
  9594. auto n = detail::write_request_line(strm, "GET", evil);
  9595. EXPECT_LT(n, 0);
  9596. EXPECT_TRUE(strm.get_buffer().empty());
  9597. }
  9598. }
  9599. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9600. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9601. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9602. // target reaches write_request. The client must fail cleanly with
  9603. // Error::Write instead of putting a request-line-less, header-injecting
  9604. // request on the wire.
  9605. Server svr;
  9606. svr.Get("/a", [](const Request &, Response &res) {
  9607. res.set_content("ok", "text/plain");
  9608. });
  9609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9610. auto se = detail::scope_exit([&] {
  9611. svr.stop();
  9612. thread.join();
  9613. ASSERT_FALSE(svr.is_running());
  9614. });
  9615. svr.wait_until_ready();
  9616. {
  9617. Client cli(HOST, PORT);
  9618. cli.set_path_encode(false);
  9619. // The request is rejected before anything is written, so the connection
  9620. // stays silent and the subsequent response read would otherwise block for
  9621. // the full default read timeout. Shorten it -- the assertion is on the
  9622. // error, not the timeout.
  9623. cli.set_read_timeout(1, 0);
  9624. auto res = cli.Get("/a\r\nInjected: pwned");
  9625. EXPECT_FALSE(res);
  9626. EXPECT_EQ(Error::Write, res.error());
  9627. }
  9628. }
  9629. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9630. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9631. // including extension methods.
  9632. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9633. for (const auto &method : good_methods) {
  9634. detail::BufferStream strm;
  9635. auto n = detail::write_request_line(strm, method, "/");
  9636. EXPECT_GT(n, 0);
  9637. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9638. }
  9639. // A method carrying CR/LF would split the request line and smuggle a whole
  9640. // request ahead of the real one. A space or an empty method corrupts the
  9641. // request line. All must be rejected before anything reaches the wire.
  9642. const std::string evil_methods[] = {
  9643. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9644. "GET\r\nInjected: pwned",
  9645. "GET\r",
  9646. "GET\n",
  9647. "GE T",
  9648. "",
  9649. };
  9650. for (const auto &evil : evil_methods) {
  9651. detail::BufferStream strm;
  9652. auto n = detail::write_request_line(strm, evil, "/");
  9653. EXPECT_LT(n, 0);
  9654. EXPECT_TRUE(strm.get_buffer().empty());
  9655. }
  9656. }
  9657. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9658. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9659. // through Client::send must fail with Error::Write and no request, neither
  9660. // the smuggled one nor the real one, may reach the server.
  9661. Server svr;
  9662. std::atomic<int> request_count(0);
  9663. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9664. request_count++;
  9665. res.status = StatusCode::OK_200;
  9666. return Server::HandlerResponse::Handled;
  9667. });
  9668. auto port = svr.bind_to_any_port(HOST);
  9669. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9670. auto se = detail::scope_exit([&] {
  9671. svr.stop();
  9672. thread.join();
  9673. ASSERT_FALSE(svr.is_running());
  9674. });
  9675. svr.wait_until_ready();
  9676. {
  9677. Client cli(HOST, port);
  9678. const std::string evil_methods[] = {
  9679. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9680. "GE T",
  9681. "",
  9682. };
  9683. for (const auto &evil : evil_methods) {
  9684. Request req;
  9685. req.method = evil;
  9686. req.path = "/";
  9687. auto res = cli.send(req);
  9688. EXPECT_FALSE(res);
  9689. EXPECT_EQ(Error::Write, res.error());
  9690. }
  9691. auto handle =
  9692. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9693. EXPECT_FALSE(handle.is_valid());
  9694. EXPECT_EQ(Error::Write, handle.error);
  9695. // A valid request on the same client still goes through.
  9696. auto res = cli.Get("/");
  9697. ASSERT_TRUE(res);
  9698. EXPECT_EQ(StatusCode::OK_200, res->status);
  9699. }
  9700. EXPECT_EQ(1, request_count.load());
  9701. }
  9702. // Sends a raw request and verifies that there isn't a crash or exception.
  9703. static void test_raw_request(const std::string &req,
  9704. std::string *out = nullptr) {
  9705. Server svr;
  9706. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9707. res.set_content("ok", "text/plain");
  9708. });
  9709. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9710. res.set_content("ok", "text/plain");
  9711. });
  9712. svr.Get("/header_field_value_check",
  9713. [&](const Request & /*req*/, Response &res) {
  9714. res.set_content("ok", "text/plain");
  9715. });
  9716. svr.CustomRoute("PROPFIND", "/dav",
  9717. [&](const Request & /*req*/, Response &res) {
  9718. res.status = StatusCode::MultiStatus_207;
  9719. });
  9720. // Server read timeout must be longer than the client read timeout for the
  9721. // bug to reproduce, probably to force the server to process a request
  9722. // without a trailing blank line.
  9723. const time_t client_read_timeout_sec = 1;
  9724. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9725. bool listen_thread_ok = false;
  9726. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9727. auto se = detail::scope_exit([&] {
  9728. svr.stop();
  9729. t.join();
  9730. ASSERT_FALSE(svr.is_running());
  9731. EXPECT_TRUE(listen_thread_ok);
  9732. });
  9733. svr.wait_until_ready();
  9734. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9735. }
  9736. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9737. // A certain header line causes an exception if the header property is parsed
  9738. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9739. test_raw_request(
  9740. "GET /hi HTTP/1.1\r\n"
  9741. " : "
  9742. " "
  9743. " ");
  9744. }
  9745. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9746. // A certain header line causes an exception if the header property *name* is
  9747. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9748. // greedy matcher and requires backtracking when there are a lot of ":"
  9749. // characters.
  9750. // This occurs with libc++ but not libstdc++.
  9751. test_raw_request(
  9752. "GET /hi HTTP/1.1\r\n"
  9753. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9754. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9755. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9756. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9757. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9758. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9759. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9760. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9761. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9762. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9763. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9764. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9765. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9766. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9767. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9768. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9769. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9770. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9771. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9772. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9773. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9774. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9775. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9776. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9777. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9778. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9779. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9780. "&&&%%%");
  9781. }
  9782. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9783. // Make sure this doesn't crash the server.
  9784. // In a previous version of the header line regex, the "\r" rendered the line
  9785. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9786. // a new position where the leading white space ended and the field value
  9787. // began.
  9788. // The crash occurs with libc++ but not libstdc++.
  9789. test_raw_request("GET /hi HTTP/1.1\r\n"
  9790. "a:" +
  9791. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9792. "\r\n"
  9793. "\r\n");
  9794. }
  9795. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9796. const char *rejected[] = {
  9797. // RFC 9112 §3: one SP between the parts, and nothing else
  9798. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9799. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9800. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9801. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9802. // A request-target has no fragment
  9803. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9804. // An HTTP/1.1 request needs a Host
  9805. "GET /hi HTTP/1.1\r\n\r\n",
  9806. };
  9807. for (auto request : rejected) {
  9808. std::string out;
  9809. test_raw_request(request, &out);
  9810. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9811. }
  9812. std::string out;
  9813. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9814. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9815. }
  9816. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9817. // RFC 9112 §6.1
  9818. const char *requests[] = {
  9819. "PUT /put_hi HTTP/1.1\r\n"
  9820. "Host: localhost\r\n"
  9821. "Content-Length: 0\r\n"
  9822. "Transfer-Encoding: chunked\r\n"
  9823. "\r\n"
  9824. "0\r\n\r\n",
  9825. "PUT /put_hi HTTP/1.0\r\n"
  9826. "Connection: keep-alive\r\n"
  9827. "Transfer-Encoding: chunked\r\n"
  9828. "\r\n"
  9829. "0\r\n\r\n",
  9830. };
  9831. for (auto request : requests) {
  9832. std::string out;
  9833. test_raw_request(request, &out);
  9834. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9835. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9836. }
  9837. }
  9838. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9839. std::string out;
  9840. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9841. "Content-Type: text/plain\r\n"
  9842. "Transfer-Encoding: chunked\r\n"
  9843. "\r\n"
  9844. "nothex\r\n",
  9845. &out);
  9846. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9847. }
  9848. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9849. std::string out;
  9850. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9851. "Content-Type: text/plain\r\n"
  9852. "Transfer-Encoding: chunked\r\n"
  9853. "\r\n"
  9854. "3\r\n"
  9855. "xyz\r\n"
  9856. "NaN\r\n",
  9857. &out);
  9858. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9859. }
  9860. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9861. std::string out;
  9862. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9863. "Content-Type: text/plain\r\n"
  9864. "Transfer-Encoding: chunked\r\n"
  9865. "\r\n"
  9866. // Length is too large for 64 bits.
  9867. "1ffffffffffffffff\r\n"
  9868. "xyz\r\n",
  9869. &out);
  9870. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9871. }
  9872. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9873. test_raw_request("GET /hi HTTP/1.1\r\n"
  9874. "Content-Type: text/plain\r\n\r");
  9875. }
  9876. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9877. std::string out;
  9878. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9879. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9880. }
  9881. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9882. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9883. std::string out;
  9884. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9885. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9886. }
  9887. }
  9888. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9889. std::string out;
  9890. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9891. "Host: localhost\r\n"
  9892. "Connection: close\r\n\r\n",
  9893. &out);
  9894. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9895. }
  9896. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9897. Server svr;
  9898. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9899. EXPECT_TRUE(!req.remote_addr.empty());
  9900. });
  9901. thread t = thread([&] { svr.listen(HOST, PORT); });
  9902. auto se = detail::scope_exit([&] {
  9903. svr.stop();
  9904. t.join();
  9905. ASSERT_FALSE(svr.is_running());
  9906. });
  9907. svr.wait_until_ready();
  9908. // Send an invalid request line to trigger Bad Request
  9909. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9910. std::string out;
  9911. ASSERT_TRUE(send_request(5, bad_req, &out));
  9912. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9913. }
  9914. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9915. // answered right away rather than blocking on a read that waits for EOF.
  9916. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9917. std::string out;
  9918. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9919. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9920. }
  9921. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9922. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9923. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9924. for (const auto *method : methods) {
  9925. Server svr;
  9926. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9927. EXPECT_FALSE(svr.is_valid()) << method;
  9928. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9929. }
  9930. }
  9931. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9932. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9933. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9934. for (const auto *method : methods) {
  9935. Server svr;
  9936. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9937. EXPECT_FALSE(svr.is_valid()) << method;
  9938. }
  9939. }
  9940. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9941. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9942. "COPY", "MOVE", "LOCK",
  9943. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9944. Server svr;
  9945. for (const auto *method : methods) {
  9946. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9947. }
  9948. EXPECT_TRUE(svr.is_valid());
  9949. }
  9950. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9951. Server svr;
  9952. svr.CustomRoute("POST", "/x",
  9953. [](const Request &, Response &, const ContentReader &) {});
  9954. EXPECT_FALSE(svr.is_valid());
  9955. }
  9956. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9957. Server svr;
  9958. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9959. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9960. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9961. EXPECT_FALSE(svr.is_valid());
  9962. }
  9963. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9964. Server svr;
  9965. auto captured = Error::Success;
  9966. svr.set_error_logger(
  9967. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9968. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9969. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9970. }
  9971. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9972. std::string out;
  9973. std::string request(
  9974. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9975. test_raw_request(request, &out);
  9976. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9977. }
  9978. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9979. std::string out;
  9980. std::string request(
  9981. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9982. test_raw_request(request, &out);
  9983. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9984. }
  9985. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9986. std::string out;
  9987. std::string request(
  9988. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9989. test_raw_request(request, &out);
  9990. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9991. }
  9992. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9993. std::string out;
  9994. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9995. "Host: localhost\r\n"
  9996. "Test: \r\n\r\n",
  9997. &out);
  9998. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9999. }
  10000. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10001. Server svr;
  10002. std::string x_custom;
  10003. std::string cookie;
  10004. std::string xff;
  10005. std::string x_unicode;
  10006. std::string x_iis;
  10007. svr.Get("/check", [&](const Request &req, Response &res) {
  10008. x_custom = req.get_header_value("X-Custom");
  10009. cookie = req.get_header_value("Cookie");
  10010. xff = req.get_header_value("X-Forwarded-For");
  10011. x_unicode = req.get_header_value("X-Unicode");
  10012. x_iis = req.get_header_value("X-IIS");
  10013. res.set_content("ok", "text/plain");
  10014. });
  10015. thread t = thread([&] { svr.listen(HOST, PORT); });
  10016. auto se = detail::scope_exit([&] {
  10017. svr.stop();
  10018. t.join();
  10019. ASSERT_FALSE(svr.is_running());
  10020. });
  10021. svr.wait_until_ready();
  10022. const std::string req = "GET /check HTTP/1.1\r\n"
  10023. "Host: localhost\r\n"
  10024. "X-Custom: a%0D%0AInjected: b\r\n"
  10025. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10026. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10027. "X-Unicode: %E3%81%82\r\n"
  10028. "X-IIS: %u00E9\r\n"
  10029. "Connection: close\r\n"
  10030. "\r\n";
  10031. std::string res;
  10032. ASSERT_TRUE(send_request(5, req, &res));
  10033. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10034. // Every value must be returned verbatim (wire form), with no decoding.
  10035. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10036. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10037. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10038. EXPECT_EQ("%E3%81%82", x_unicode);
  10039. EXPECT_EQ("%u00E9", x_iis);
  10040. }
  10041. // Applications that previously relied on automatic percent-decoding can
  10042. // reproduce the old behavior by explicitly calling decode_path_component()
  10043. // or, for RFC 3986 conformance, decode_uri_component().
  10044. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10045. Server svr;
  10046. std::string decoded;
  10047. svr.Get("/check", [&](const Request &req, Response &res) {
  10048. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10049. res.set_content("ok", "text/plain");
  10050. });
  10051. thread t = thread([&] { svr.listen(HOST, PORT); });
  10052. auto se = detail::scope_exit([&] {
  10053. svr.stop();
  10054. t.join();
  10055. ASSERT_FALSE(svr.is_running());
  10056. });
  10057. svr.wait_until_ready();
  10058. const std::string req = "GET /check HTTP/1.1\r\n"
  10059. "Host: localhost\r\n"
  10060. "X-Custom: hello%20world\r\n"
  10061. "Connection: close\r\n"
  10062. "\r\n";
  10063. std::string res;
  10064. ASSERT_TRUE(send_request(5, req, &res));
  10065. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10066. EXPECT_EQ("hello world", decoded);
  10067. }
  10068. // Regression test for #2033. Browsers send Referer values that include
  10069. // percent-encoded characters such as %0A inside the URL. Decoding the
  10070. // header value would either trip the post-decode CR/LF/NUL guard (the
  10071. // original bug, returning 400) or, after that guard was relaxed, silently
  10072. // store a literal LF — both unacceptable. The wire form must round-trip.
  10073. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10074. Server svr;
  10075. std::string referer;
  10076. svr.Get("/check", [&](const Request &req, Response &res) {
  10077. referer = req.get_header_value("Referer");
  10078. res.set_content("ok", "text/plain");
  10079. });
  10080. thread t = thread([&] { svr.listen(HOST, PORT); });
  10081. auto se = detail::scope_exit([&] {
  10082. svr.stop();
  10083. t.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. });
  10086. svr.wait_until_ready();
  10087. const std::string req = "GET /check HTTP/1.1\r\n"
  10088. "Host: localhost\r\n"
  10089. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10090. "Connection: close\r\n"
  10091. "\r\n";
  10092. std::string res;
  10093. ASSERT_TRUE(send_request(5, req, &res));
  10094. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10095. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10096. }
  10097. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10098. Server svr;
  10099. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10100. res.set_header("Cache-Control", "no-cache");
  10101. res.set_chunked_content_provider(
  10102. "text/event-stream", [](size_t offset, DataSink &sink) {
  10103. std::string s = "data:";
  10104. s += std::to_string(offset);
  10105. s += "\n\n";
  10106. auto ret = sink.write(s.data(), s.size());
  10107. EXPECT_TRUE(ret);
  10108. std::this_thread::sleep_for(std::chrono::seconds(1));
  10109. return true;
  10110. });
  10111. });
  10112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10113. svr.wait_until_ready();
  10114. Client client(HOST, PORT);
  10115. const Headers headers = {{"Accept", "text/event-stream"}};
  10116. auto get_thread = std::thread([&client, &headers]() {
  10117. auto res = client.Get(
  10118. "/events", headers,
  10119. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10120. });
  10121. auto se = detail::scope_exit([&] {
  10122. svr.stop();
  10123. get_thread.join();
  10124. listen_thread.join();
  10125. ASSERT_FALSE(svr.is_running());
  10126. });
  10127. // Give GET time to get a few messages.
  10128. std::this_thread::sleep_for(std::chrono::seconds(2));
  10129. }
  10130. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10131. httplib::Server svr;
  10132. svr.Post("/hi",
  10133. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10134. res.status = StatusCode::OK_200;
  10135. });
  10136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10137. svr.wait_until_ready();
  10138. Client cli(HOST, PORT);
  10139. auto res = cli.Post("/hi", "data", "text/plain");
  10140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10141. EXPECT_EQ(StatusCode::OK_200, res->status);
  10142. svr.stop();
  10143. thread.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. res = cli.Post("/hi", "data", "text/plain");
  10146. ASSERT_FALSE(res);
  10147. }
  10148. TEST(ServerStopTest, ListenFailure) {
  10149. Server svr;
  10150. auto t = thread([&]() {
  10151. auto ret = svr.listen("????", PORT);
  10152. EXPECT_FALSE(ret);
  10153. });
  10154. svr.wait_until_ready();
  10155. svr.stop();
  10156. t.join();
  10157. }
  10158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10159. TEST(ServerStopTest, Decommision) {
  10160. Server svr;
  10161. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10162. for (int i = 0; i < 4; i++) {
  10163. auto is_even = !(i % 2);
  10164. std::thread t{[&] {
  10165. try {
  10166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10167. if (is_even) {
  10168. throw std::runtime_error("Some thing that happens to go wrong.");
  10169. }
  10170. svr.listen(HOST, PORT);
  10171. } catch (...) { svr.decommission(); }
  10172. }};
  10173. svr.wait_until_ready();
  10174. // Server is up
  10175. {
  10176. Client cli(HOST, PORT);
  10177. auto res = cli.Get("/hi");
  10178. if (is_even) {
  10179. EXPECT_FALSE(res);
  10180. } else {
  10181. EXPECT_TRUE(res);
  10182. EXPECT_EQ("hi...", res->body);
  10183. }
  10184. }
  10185. svr.stop();
  10186. t.join();
  10187. // Server is down...
  10188. {
  10189. Client cli(HOST, PORT);
  10190. auto res = cli.Get("/hi");
  10191. EXPECT_FALSE(res);
  10192. }
  10193. }
  10194. }
  10195. #endif
  10196. // Helper function for string body upload progress tests
  10197. template <typename SetupHandler, typename ClientCall>
  10198. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10199. ClientCall &&client_call,
  10200. const string &body) {
  10201. Server svr;
  10202. setup_handler(svr);
  10203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10204. auto se = detail::scope_exit([&] {
  10205. svr.stop();
  10206. t.join();
  10207. });
  10208. svr.wait_until_ready();
  10209. Client cli(HOST, PORT);
  10210. vector<uint64_t> progress_values;
  10211. bool progress_called = false;
  10212. auto res =
  10213. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10214. progress_values.push_back(current);
  10215. progress_called = true;
  10216. return true;
  10217. });
  10218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10219. EXPECT_EQ(200, res->status);
  10220. EXPECT_TRUE(progress_called);
  10221. }
  10222. TEST(UploadProgressTest, PostStringBodyBasic) {
  10223. TestStringBodyUploadProgress(
  10224. [](Server &svr) {
  10225. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10226. res.set_content("received", "text/plain");
  10227. });
  10228. },
  10229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10230. return cli.Post("/test", body, "text/plain", progress_callback);
  10231. },
  10232. "test data for upload progress");
  10233. }
  10234. TEST(UploadProgressTest, PutStringBodyBasic) {
  10235. TestStringBodyUploadProgress(
  10236. [](Server &svr) {
  10237. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10238. res.set_content("put received", "text/plain");
  10239. });
  10240. },
  10241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10242. return cli.Put("/test", body, "text/plain", progress_callback);
  10243. },
  10244. "put test data for upload progress");
  10245. }
  10246. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10247. TestStringBodyUploadProgress(
  10248. [](Server &svr) {
  10249. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10250. res.set_content("patch received", "text/plain");
  10251. });
  10252. },
  10253. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10254. return cli.Patch("/test", body, "text/plain", progress_callback);
  10255. },
  10256. "patch test data for upload progress");
  10257. }
  10258. // Helper function for content provider upload progress tests
  10259. template <typename SetupHandler, typename ClientCall>
  10260. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10261. ClientCall &&client_call) {
  10262. Server svr;
  10263. setup_handler(svr);
  10264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. t.join();
  10268. });
  10269. svr.wait_until_ready();
  10270. Client cli(HOST, PORT);
  10271. vector<uint64_t> progress_values;
  10272. auto res =
  10273. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10274. progress_values.push_back(current);
  10275. return true;
  10276. });
  10277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10278. EXPECT_EQ(200, res->status);
  10279. EXPECT_FALSE(progress_values.empty());
  10280. }
  10281. TEST(UploadProgressTest, PostContentProviderProgress) {
  10282. TestContentProviderUploadProgress(
  10283. [](Server &svr) {
  10284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10285. res.set_content("provider received", "text/plain");
  10286. });
  10287. },
  10288. [](Client &cli, UploadProgress progress_callback) {
  10289. return cli.Post(
  10290. "/test", 9,
  10291. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10292. sink.os << "test data";
  10293. return true;
  10294. },
  10295. "text/plain", progress_callback);
  10296. });
  10297. }
  10298. // Helper function for multipart upload progress tests
  10299. template <typename SetupHandler, typename ClientCall>
  10300. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10301. ClientCall &&client_call,
  10302. const string &endpoint) {
  10303. Server svr;
  10304. setup_handler(svr);
  10305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10306. auto se = detail::scope_exit([&] {
  10307. svr.stop();
  10308. t.join();
  10309. });
  10310. svr.wait_until_ready();
  10311. Client cli(HOST, PORT);
  10312. vector<uint64_t> progress_values;
  10313. UploadFormDataItems items = {
  10314. {"field1", "value1", "", ""},
  10315. {"field2", "longer value for progress tracking test", "", ""},
  10316. {"file1", "file content data for upload progress", "test.txt",
  10317. "text/plain"}};
  10318. auto res = client_call(cli, endpoint, items,
  10319. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10320. progress_values.push_back(current);
  10321. return true;
  10322. });
  10323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10324. EXPECT_EQ(200, res->status);
  10325. EXPECT_FALSE(progress_values.empty());
  10326. }
  10327. TEST(UploadProgressTest, PostMultipartProgress) {
  10328. TestMultipartUploadProgress(
  10329. [](Server &svr) {
  10330. svr.Post("/multipart", [](const Request &req, Response &res) {
  10331. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10332. res.set_content("multipart received", "text/plain");
  10333. });
  10334. },
  10335. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10336. UploadProgress progress_callback) {
  10337. return cli.Post(endpoint, items, progress_callback);
  10338. },
  10339. "/multipart");
  10340. }
  10341. // Helper function for basic download progress tests
  10342. template <typename SetupHandler, typename ClientCall>
  10343. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10344. ClientCall &&client_call, const string &endpoint,
  10345. size_t expected_content_size) {
  10346. Server svr;
  10347. setup_handler(svr);
  10348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10349. auto se = detail::scope_exit([&] {
  10350. svr.stop();
  10351. t.join();
  10352. });
  10353. svr.wait_until_ready();
  10354. Client cli(HOST, PORT);
  10355. vector<uint64_t> progress_values;
  10356. auto res = client_call(cli, endpoint,
  10357. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10358. progress_values.push_back(current);
  10359. return true;
  10360. });
  10361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10362. EXPECT_EQ(200, res->status);
  10363. EXPECT_FALSE(progress_values.empty());
  10364. EXPECT_EQ(expected_content_size, res->body.size());
  10365. }
  10366. TEST(DownloadProgressTest, GetBasic) {
  10367. TestBasicDownloadProgress(
  10368. [](Server &svr) {
  10369. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10370. string content(1000, 'D');
  10371. res.set_content(content, "text/plain");
  10372. });
  10373. },
  10374. [](Client &cli, const string &endpoint,
  10375. DownloadProgress progress_callback) {
  10376. return cli.Get(endpoint, progress_callback);
  10377. },
  10378. "/download", 1000u);
  10379. }
  10380. // Helper function for content receiver download progress tests
  10381. template <typename SetupHandler, typename ClientCall>
  10382. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10383. ClientCall &&client_call,
  10384. const string &endpoint,
  10385. size_t expected_content_size) {
  10386. Server svr;
  10387. setup_handler(svr);
  10388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. t.join();
  10392. });
  10393. svr.wait_until_ready();
  10394. Client cli(HOST, PORT);
  10395. vector<uint64_t> progress_values;
  10396. string received_body;
  10397. auto res = client_call(
  10398. cli, endpoint,
  10399. [&](const char *data, size_t data_length) -> bool {
  10400. received_body.append(data, data_length);
  10401. return true;
  10402. },
  10403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10404. progress_values.push_back(current);
  10405. return true;
  10406. });
  10407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10408. EXPECT_EQ(200, res->status);
  10409. EXPECT_FALSE(progress_values.empty());
  10410. EXPECT_EQ(expected_content_size, received_body.size());
  10411. EXPECT_TRUE(res->body.empty());
  10412. }
  10413. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10414. TestContentReceiverDownloadProgress(
  10415. [](Server &svr) {
  10416. svr.Get("/download-receiver",
  10417. [](const Request & /*req*/, Response &res) {
  10418. string content(2000, 'R');
  10419. res.set_content(content, "text/plain");
  10420. });
  10421. },
  10422. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10423. DownloadProgress progress_callback) {
  10424. return cli.Get(endpoint, content_receiver, progress_callback);
  10425. },
  10426. "/download-receiver", 2000u);
  10427. }
  10428. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10429. // A provider reaching a pass with nothing to hand over - an empty buffer
  10430. // popped off a queue, say - must not be taken to mean the body is finished.
  10431. // It used to end the loop with the terminating chunk unwritten while the
  10432. // server still considered the response complete, so the peer waited for an
  10433. // end that never arrived.
  10434. Server svr;
  10435. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10436. auto step = std::make_shared<int>(0);
  10437. res.set_chunked_content_provider("text/plain",
  10438. [step](size_t /*offset*/, DataSink &sink) {
  10439. switch ((*step)++) {
  10440. case 0: sink.write("", 0); break;
  10441. case 1: sink.write("hello", 5); break;
  10442. default: sink.done(); break;
  10443. }
  10444. return true;
  10445. });
  10446. });
  10447. auto port = svr.bind_to_any_port(HOST);
  10448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10449. auto listen_se = detail::scope_exit([&] {
  10450. svr.stop();
  10451. listen_thread.join();
  10452. ASSERT_FALSE(svr.is_running());
  10453. });
  10454. svr.wait_until_ready();
  10455. Client cli(HOST, port);
  10456. // Without the fix the body is never terminated, so bound the wait rather
  10457. // than letting the test hang on the default read timeout.
  10458. cli.set_read_timeout(5, 0);
  10459. auto res = cli.Get("/stream");
  10460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10461. EXPECT_EQ(StatusCode::OK_200, res->status);
  10462. EXPECT_EQ("hello", res->body);
  10463. }
  10464. TEST(StreamingTest, NoContentLengthStreaming) {
  10465. Server svr;
  10466. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10467. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10468. if (offset < 6) {
  10469. sink.os << (offset < 3 ? "a" : "b");
  10470. } else {
  10471. sink.done();
  10472. }
  10473. return true;
  10474. });
  10475. });
  10476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10477. auto listen_se = detail::scope_exit([&] {
  10478. svr.stop();
  10479. listen_thread.join();
  10480. ASSERT_FALSE(svr.is_running());
  10481. });
  10482. svr.wait_until_ready();
  10483. Client client(HOST, PORT);
  10484. auto get_thread = std::thread([&client]() {
  10485. std::string s;
  10486. auto res =
  10487. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10488. s += std::string(data, len);
  10489. return true;
  10490. });
  10491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10492. EXPECT_EQ(StatusCode::OK_200, res->status);
  10493. EXPECT_EQ("aaabbb", s);
  10494. });
  10495. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10496. // Give GET time to get a few messages.
  10497. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10498. }
  10499. TEST(MountTest, Unmount) {
  10500. Server svr;
  10501. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10502. auto se = detail::scope_exit([&] {
  10503. svr.stop();
  10504. listen_thread.join();
  10505. ASSERT_FALSE(svr.is_running());
  10506. });
  10507. svr.wait_until_ready();
  10508. Client cli("localhost", PORT);
  10509. svr.set_mount_point("/mount2", "./www2");
  10510. auto res = cli.Get("/");
  10511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10513. res = cli.Get("/mount2/dir/test.html");
  10514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10515. EXPECT_EQ(StatusCode::OK_200, res->status);
  10516. svr.set_mount_point("/", "./www");
  10517. res = cli.Get("/dir/");
  10518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10519. EXPECT_EQ(StatusCode::OK_200, res->status);
  10520. svr.remove_mount_point("/");
  10521. res = cli.Get("/dir/");
  10522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10524. svr.remove_mount_point("/mount2");
  10525. res = cli.Get("/mount2/dir/test.html");
  10526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10527. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10528. }
  10529. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10530. Server svr;
  10531. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10532. svr.Get("/api/hello", [](const Request &, Response &res) {
  10533. res.set_content("api", "text/plain");
  10534. });
  10535. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10536. auto se = detail::scope_exit([&] {
  10537. svr.stop();
  10538. listen_thread.join();
  10539. ASSERT_FALSE(svr.is_running());
  10540. });
  10541. svr.wait_until_ready();
  10542. Client cli(HOST, PORT);
  10543. auto res = cli.Get("/dir/test.html");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::OK_200, res->status);
  10546. res = cli.Get("/api/hello");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::OK_200, res->status);
  10549. EXPECT_EQ("api", res->body);
  10550. }
  10551. TEST(MountTest, PathSegmentBoundary) {
  10552. Server svr;
  10553. svr.set_mount_point("/mount2", "./www2");
  10554. svr.set_mount_point("/", "./www");
  10555. auto port = svr.bind_to_any_port(HOST);
  10556. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10557. auto se = detail::scope_exit([&] {
  10558. svr.stop();
  10559. listen_thread.join();
  10560. ASSERT_FALSE(svr.is_running());
  10561. });
  10562. svr.wait_until_ready();
  10563. Client cli(HOST, port);
  10564. auto res = cli.Get("/mount2/dir/test.html");
  10565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10566. EXPECT_EQ(StatusCode::OK_200, res->status);
  10567. // "/mount2" must not match part-way through a path segment.
  10568. res = cli.Get("/mount2dir/test.html");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10571. // A mount point ending in '/' keeps matching every path below it.
  10572. res = cli.Get("/dir/test.html");
  10573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10574. EXPECT_EQ(StatusCode::OK_200, res->status);
  10575. }
  10576. TEST(MountTest, Redicect) {
  10577. Server svr;
  10578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10579. auto se = detail::scope_exit([&] {
  10580. svr.stop();
  10581. listen_thread.join();
  10582. ASSERT_FALSE(svr.is_running());
  10583. });
  10584. svr.set_mount_point("/", "./www");
  10585. svr.wait_until_ready();
  10586. Client cli("localhost", PORT);
  10587. auto res = cli.Get("/dir/");
  10588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10589. EXPECT_EQ(StatusCode::OK_200, res->status);
  10590. res = cli.Get("/dir");
  10591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10592. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10593. res = cli.Get("/file");
  10594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10595. EXPECT_EQ(StatusCode::OK_200, res->status);
  10596. res = cli.Get("/file/");
  10597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10598. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10599. cli.set_follow_location(true);
  10600. res = cli.Get("/dir");
  10601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10602. EXPECT_EQ(StatusCode::OK_200, res->status);
  10603. }
  10604. TEST(MountTest, MultibytesPathName) {
  10605. Server svr;
  10606. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10607. auto se = detail::scope_exit([&] {
  10608. svr.stop();
  10609. listen_thread.join();
  10610. ASSERT_FALSE(svr.is_running());
  10611. });
  10612. svr.set_mount_point("/", "./www");
  10613. svr.wait_until_ready();
  10614. Client cli("localhost", PORT);
  10615. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(StatusCode::OK_200, res->status);
  10618. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10619. }
  10620. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10621. // in the pre-routing handler sees the path of every file that is served
  10622. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10623. Server svr;
  10624. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10625. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10626. if (req.path == "/dir/test.html") {
  10627. res.status = StatusCode::Unauthorized_401;
  10628. return Server::HandlerResponse::Handled;
  10629. }
  10630. return Server::HandlerResponse::Unhandled;
  10631. });
  10632. auto port = svr.bind_to_any_port(HOST);
  10633. ASSERT_LT(0, port);
  10634. thread t = thread([&] { svr.listen_after_bind(); });
  10635. auto se = detail::scope_exit([&] {
  10636. svr.stop();
  10637. t.join();
  10638. ASSERT_FALSE(svr.is_running());
  10639. });
  10640. svr.wait_until_ready();
  10641. Client cli(HOST, port);
  10642. for (auto path :
  10643. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10644. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10645. SCOPED_TRACE(path);
  10646. auto res = cli.Get(path);
  10647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10648. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10649. }
  10650. }
  10651. #ifdef _WIN32
  10652. // Issue #2435: mmap::open() must succeed even when another handle holds
  10653. // the file open for writing (e.g. an active log file).
  10654. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10655. const char *path = "mmap_concurrent_writer_test.txt";
  10656. const char *content = "hello";
  10657. {
  10658. std::ofstream f(path, std::ios::binary);
  10659. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10660. }
  10661. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10662. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10663. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10664. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10665. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10666. detail::mmap m(path);
  10667. ASSERT_TRUE(m.is_open());
  10668. EXPECT_EQ(strlen(content), m.size());
  10669. char buf[8];
  10670. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10671. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10672. }
  10673. #endif
  10674. #ifndef _WIN32
  10675. // A directory or a device has no size to serve.
  10676. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10677. const char *path = "./mmap_not_regular_test_dir";
  10678. ASSERT_EQ(0, ::mkdir(path, 0755));
  10679. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10680. for (auto p : {path, "/dev/null"}) {
  10681. detail::mmap m(p);
  10682. EXPECT_FALSE(m.is_open()) << p;
  10683. EXPECT_EQ(0U, m.size()) << p;
  10684. }
  10685. Server svr;
  10686. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10687. res.set_file_content("/dev/null");
  10688. });
  10689. auto port = svr.bind_to_any_port(HOST);
  10690. thread t = thread([&] { svr.listen_after_bind(); });
  10691. auto se = detail::scope_exit([&] {
  10692. svr.stop();
  10693. t.join();
  10694. });
  10695. svr.wait_until_ready();
  10696. auto res = Client(HOST, port).Get("/null");
  10697. ASSERT_TRUE(res);
  10698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10699. }
  10700. #endif
  10701. #ifdef __linux__
  10702. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10703. TEST(MmapTest, FileIsNotMapped) {
  10704. const char *path = "mmap_not_mapped_test.txt";
  10705. {
  10706. std::ofstream f(path, std::ios::binary);
  10707. f << "hello";
  10708. }
  10709. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10710. detail::mmap m(path);
  10711. ASSERT_TRUE(m.is_open());
  10712. std::ifstream maps("/proc/self/maps");
  10713. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10714. std::istreambuf_iterator<char>());
  10715. EXPECT_EQ(std::string::npos, mappings.find(path));
  10716. }
  10717. #endif
  10718. TEST(KeepAliveTest, ReadTimeout) {
  10719. Server svr;
  10720. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10721. std::this_thread::sleep_for(std::chrono::seconds(2));
  10722. res.set_content("a", "text/plain");
  10723. });
  10724. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10725. res.set_content("b", "text/plain");
  10726. });
  10727. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. listen_thread.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli("localhost", PORT);
  10735. cli.set_keep_alive(true);
  10736. cli.set_read_timeout(std::chrono::seconds(1));
  10737. auto resa = cli.Get("/a");
  10738. ASSERT_FALSE(resa);
  10739. EXPECT_EQ(Error::Read, resa.error());
  10740. auto resb = cli.Get("/b");
  10741. ASSERT_TRUE(resb);
  10742. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10743. EXPECT_EQ("b", resb->body);
  10744. }
  10745. TEST(KeepAliveTest, MaxCount) {
  10746. size_t keep_alive_max_count = 3;
  10747. Server svr;
  10748. svr.set_keep_alive_max_count(keep_alive_max_count);
  10749. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10750. res.set_content("Hello World!", "text/plain");
  10751. });
  10752. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10753. auto se = detail::scope_exit([&] {
  10754. svr.stop();
  10755. listen_thread.join();
  10756. ASSERT_FALSE(svr.is_running());
  10757. });
  10758. svr.wait_until_ready();
  10759. Client cli(HOST, PORT);
  10760. cli.set_keep_alive(true);
  10761. for (size_t i = 0; i < 5; i++) {
  10762. auto result = cli.Get("/hi");
  10763. ASSERT_TRUE(result);
  10764. EXPECT_EQ(StatusCode::OK_200, result->status);
  10765. if (i == keep_alive_max_count - 1) {
  10766. EXPECT_EQ("close", result->get_header_value("Connection"));
  10767. } else {
  10768. EXPECT_FALSE(result->has_header("Connection"));
  10769. }
  10770. }
  10771. }
  10772. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10773. // can pull the next one into the server's buffer. The server must serve it
  10774. // without waiting for the socket to become readable again. The keep-alive
  10775. // timeout outlasts the client's read timeout, so a request left waiting for it
  10776. // shows up as a missing response.
  10777. static void serve_pipelining_routes(Server &svr,
  10778. const std::function<void(int)> &client) {
  10779. svr.set_keep_alive_timeout(5);
  10780. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10781. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10782. });
  10783. svr.Post("/echo", [](const Request &req, Response &res) {
  10784. res.set_content("echo " + req.body, "text/plain");
  10785. });
  10786. auto port = svr.bind_to_any_port(HOST);
  10787. thread t = thread([&] { svr.listen_after_bind(); });
  10788. auto se = detail::scope_exit([&] {
  10789. svr.stop();
  10790. t.join();
  10791. });
  10792. svr.wait_until_ready();
  10793. client(port);
  10794. }
  10795. static std::string
  10796. send_pipelined_requests(const std::vector<std::string> &parts) {
  10797. Server svr;
  10798. std::string res;
  10799. serve_pipelining_routes(svr, [&](int port) {
  10800. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10801. });
  10802. return res;
  10803. }
  10804. static void expect_in_order(const std::string &res,
  10805. const std::vector<std::string> &bodies) {
  10806. size_t pos = 0;
  10807. for (const auto &body : bodies) {
  10808. pos = res.find(body, pos);
  10809. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10810. pos += body.size();
  10811. }
  10812. }
  10813. TEST(KeepAliveTest, PipelinedRequests) {
  10814. auto res = send_pipelined_requests(
  10815. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10816. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10817. "Content-Length: 4\r\n\r\nbody"
  10818. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10819. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10820. }
  10821. // The second request starts in the server's buffer and ends on the socket.
  10822. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10823. auto res =
  10824. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10825. "GET /hi/2 HTTP/1.1\r\nHo",
  10826. "st: localhost\r\nConnection: close\r\n\r\n"});
  10827. expect_in_order(res, {"hi 1", "hi 2"});
  10828. }
  10829. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10830. // CRLF after a body does not turn into a 400 for the next request.
  10831. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10832. auto res = send_pipelined_requests(
  10833. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10834. "Content-Length: 4\r\n\r\nbody\r\n"
  10835. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10836. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10837. expect_in_order(res, {"echo body", "hi 2"});
  10838. }
  10839. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10840. // must not be served as the next request.
  10841. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10842. auto res = send_pipelined_requests(
  10843. {"INVALID REQUEST LINE\r\n\r\n"
  10844. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10845. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10846. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10847. }
  10848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10849. // Over TLS, the next request is held by the TLS library as already decrypted
  10850. // data rather than on the socket.
  10851. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10853. std::string res;
  10854. serve_pipelining_routes(svr, [&](int port) {
  10855. // One part, so all three requests arrive in one TLS record
  10856. EXPECT_TRUE(send_ssl_request_in_parts(
  10857. 2,
  10858. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10859. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10860. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10861. &res, port));
  10862. });
  10863. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10864. }
  10865. #endif
  10866. TEST(KeepAliveTest, Issue1041) {
  10867. Server svr;
  10868. svr.set_keep_alive_timeout(3);
  10869. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10870. res.set_content("Hello World!", "text/plain");
  10871. });
  10872. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10873. auto se = detail::scope_exit([&] {
  10874. svr.stop();
  10875. listen_thread.join();
  10876. ASSERT_FALSE(svr.is_running());
  10877. });
  10878. svr.wait_until_ready();
  10879. Client cli(HOST, PORT);
  10880. cli.set_keep_alive(true);
  10881. auto result = cli.Get("/hi");
  10882. ASSERT_TRUE(result);
  10883. EXPECT_EQ(StatusCode::OK_200, result->status);
  10884. std::this_thread::sleep_for(std::chrono::seconds(5));
  10885. result = cli.Get("/hi");
  10886. ASSERT_TRUE(result);
  10887. EXPECT_EQ(StatusCode::OK_200, result->status);
  10888. }
  10889. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10890. Server svr;
  10891. svr.set_keep_alive_max_count(0);
  10892. std::set<int> remote_ports;
  10893. svr.Get("/hi", [&](const Request &req, Response &res) {
  10894. remote_ports.insert(req.remote_port);
  10895. res.set_content("hi", "text/plain");
  10896. });
  10897. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10898. auto se = detail::scope_exit([&] {
  10899. svr.stop();
  10900. listen_thread.join();
  10901. ASSERT_FALSE(svr.is_running());
  10902. });
  10903. svr.wait_until_ready();
  10904. Client cli(HOST, PORT);
  10905. cli.set_keep_alive(true);
  10906. for (int i = 0; i < 3; i++) {
  10907. auto res = cli.Get("/hi");
  10908. ASSERT_TRUE(res);
  10909. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10910. }
  10911. // All three over one connection
  10912. EXPECT_EQ(1u, remote_ports.size());
  10913. }
  10914. TEST(KeepAliveTest, Issue1959) {
  10915. Server svr;
  10916. svr.set_keep_alive_timeout(5);
  10917. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10918. res.set_content("a", "text/plain");
  10919. });
  10920. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10921. auto se = detail::scope_exit([&] {
  10922. if (!svr.is_running()) return;
  10923. svr.stop();
  10924. listen_thread.join();
  10925. ASSERT_FALSE(svr.is_running());
  10926. });
  10927. svr.wait_until_ready();
  10928. Client cli("localhost", PORT);
  10929. cli.set_keep_alive(true);
  10930. using namespace std::chrono;
  10931. auto start = steady_clock::now();
  10932. cli.Get("/a");
  10933. svr.stop();
  10934. listen_thread.join();
  10935. auto end = steady_clock::now();
  10936. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10937. EXPECT_LT(elapsed, 5000);
  10938. }
  10939. #ifdef CPPHTTPLIB_SSL_ENABLED
  10940. TEST(KeepAliveTest, SSLClientReconnection) {
  10941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10942. ASSERT_TRUE(svr.is_valid());
  10943. svr.set_keep_alive_timeout(1);
  10944. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10945. res.set_content("Hello World!", "text/plain");
  10946. });
  10947. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10948. auto se = detail::scope_exit([&] {
  10949. svr.stop();
  10950. listen_thread.join();
  10951. ASSERT_FALSE(svr.is_running());
  10952. });
  10953. svr.wait_until_ready();
  10954. SSLClient cli(HOST, PORT);
  10955. cli.enable_server_certificate_verification(false);
  10956. cli.set_keep_alive(true);
  10957. auto result = cli.Get("/hi");
  10958. ASSERT_TRUE(result);
  10959. EXPECT_EQ(StatusCode::OK_200, result->status);
  10960. result = cli.Get("/hi");
  10961. ASSERT_TRUE(result);
  10962. EXPECT_EQ(StatusCode::OK_200, result->status);
  10963. std::this_thread::sleep_for(std::chrono::seconds(2));
  10964. // Recoonect
  10965. result = cli.Get("/hi");
  10966. ASSERT_TRUE(result);
  10967. EXPECT_EQ(StatusCode::OK_200, result->status);
  10968. result = cli.Get("/hi");
  10969. ASSERT_TRUE(result);
  10970. EXPECT_EQ(StatusCode::OK_200, result->status);
  10971. }
  10972. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10974. ASSERT_TRUE(svr.is_valid());
  10975. svr.set_keep_alive_timeout(1);
  10976. std::string content = "reconnect";
  10977. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10978. res.set_content("Hello World!", "text/plain");
  10979. });
  10980. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10981. auto se = detail::scope_exit([&] {
  10982. svr.stop();
  10983. listen_thread.join();
  10984. ASSERT_FALSE(svr.is_running());
  10985. });
  10986. svr.wait_until_ready();
  10987. SSLClient cli(HOST, PORT);
  10988. cli.enable_server_certificate_verification(false);
  10989. cli.set_keep_alive(true);
  10990. auto result = cli.Post(
  10991. "/hi", content.size(),
  10992. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10993. sink.write(content.c_str(), content.size());
  10994. return true;
  10995. },
  10996. "text/plain");
  10997. ASSERT_TRUE(result);
  10998. EXPECT_EQ(200, result->status);
  10999. std::this_thread::sleep_for(std::chrono::seconds(2));
  11000. // Recoonect
  11001. result = cli.Post(
  11002. "/hi", content.size(),
  11003. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11004. sink.write(content.c_str(), content.size());
  11005. return true;
  11006. },
  11007. "text/plain");
  11008. ASSERT_TRUE(result);
  11009. EXPECT_EQ(200, result->status);
  11010. result = cli.Post(
  11011. "/hi", content.size(),
  11012. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11013. sink.write(content.c_str(), content.size());
  11014. return true;
  11015. },
  11016. "text/plain");
  11017. ASSERT_TRUE(result);
  11018. EXPECT_EQ(200, result->status);
  11019. }
  11020. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11021. using namespace httplib::tls;
  11022. {
  11023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11024. ASSERT_TRUE(svr.is_valid());
  11025. svr.Get("/sni", [&](const Request &req, Response &res) {
  11026. std::string expected = req.sni();
  11027. EXPECT_EQ(expected, req.get_param_value("expected"));
  11028. res.set_content("ok", "text/plain");
  11029. });
  11030. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11031. auto se = detail::scope_exit([&] {
  11032. svr.stop();
  11033. listen_thread.join();
  11034. ASSERT_FALSE(svr.is_running());
  11035. });
  11036. svr.wait_until_ready();
  11037. {
  11038. SSLClient cli("localhost", PORT);
  11039. cli.enable_server_certificate_verification(false);
  11040. auto res = cli.Get("/sni?expected=localhost");
  11041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11042. }
  11043. {
  11044. SSLClient cli("::1", PORT);
  11045. cli.enable_server_certificate_verification(false);
  11046. auto res = cli.Get("/sni?expected=");
  11047. // NOTE: This may fail if the server is listening on IPv4 only
  11048. // (e.g., when localhost resolves to 127.0.0.1 only)
  11049. if (res) {
  11050. EXPECT_EQ(StatusCode::OK_200, res->status);
  11051. } else {
  11052. EXPECT_EQ(Error::Connection, res.error());
  11053. }
  11054. }
  11055. }
  11056. }
  11057. // The SNI of a failed handshake does not reach the next connection that the
  11058. // same worker thread serves
  11059. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11061. ASSERT_TRUE(svr.is_valid());
  11062. svr.new_task_queue = [] { return new ThreadPool(1); };
  11063. svr.Get("/sni", [](const Request &req, Response &res) {
  11064. res.set_content(req.sni(), "text/plain");
  11065. });
  11066. auto port = svr.bind_to_any_port("127.0.0.1");
  11067. ASSERT_LT(0, port);
  11068. thread t = thread([&] { svr.listen_after_bind(); });
  11069. auto se = detail::scope_exit([&] {
  11070. svr.stop();
  11071. t.join();
  11072. ASSERT_FALSE(svr.is_running());
  11073. });
  11074. svr.wait_until_ready();
  11075. {
  11076. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11077. SSLClient cli("localhost", port);
  11078. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11079. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11080. auto res = cli.Get("/sni");
  11081. ASSERT_FALSE(res);
  11082. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11083. }
  11084. // An IP host sends no SNI (RFC 6066)
  11085. SSLClient cli("127.0.0.1", port);
  11086. cli.enable_server_certificate_verification(false);
  11087. auto res = cli.Get("/sni");
  11088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11089. EXPECT_EQ("", res->body);
  11090. }
  11091. #endif
  11092. TEST(ClientProblemDetectionTest, ContentProvider) {
  11093. Server svr;
  11094. size_t content_length = 1024 * 1024;
  11095. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11096. res.set_content_provider(
  11097. content_length, "text/plain",
  11098. [&](size_t offset, size_t length, DataSink &sink) {
  11099. auto out_len = std::min(length, static_cast<size_t>(1024));
  11100. std::string out(out_len, '@');
  11101. sink.write(out.data(), out_len);
  11102. return offset < 4096;
  11103. },
  11104. [](bool success) { ASSERT_FALSE(success); });
  11105. });
  11106. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11107. res.set_content_provider(
  11108. 0, "text/plain",
  11109. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11110. EXPECT_TRUE(false);
  11111. return true;
  11112. },
  11113. [](bool success) { ASSERT_FALSE(success); });
  11114. });
  11115. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11116. auto se = detail::scope_exit([&] {
  11117. svr.stop();
  11118. listen_thread.join();
  11119. ASSERT_FALSE(svr.is_running());
  11120. });
  11121. svr.wait_until_ready();
  11122. Client cli("localhost", PORT);
  11123. {
  11124. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11125. size_t /*data_length*/) { return false; });
  11126. ASSERT_FALSE(res);
  11127. }
  11128. {
  11129. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11130. size_t /*data_length*/) { return false; });
  11131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11132. }
  11133. }
  11134. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11135. // A provider that reports success without writing anything and without
  11136. // calling done() used to be handed the same offset and length again on every
  11137. // pass, so it spun for as long as the peer stayed connected.
  11138. Server svr;
  11139. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11140. res.set_content("ok", "text/plain");
  11141. });
  11142. auto port = svr.bind_to_any_port(HOST);
  11143. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11144. auto se = detail::scope_exit([&] {
  11145. svr.stop();
  11146. listen_thread.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. std::atomic<int> call_count{0};
  11151. Client cli(HOST, port);
  11152. auto res = cli.Post(
  11153. "/", 1024,
  11154. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11155. // Give up after enough passes to show the spin, so that losing the
  11156. // check below fails this test instead of hanging it.
  11157. return ++call_count < 100;
  11158. },
  11159. "text/plain");
  11160. ASSERT_FALSE(res);
  11161. EXPECT_EQ(Error::Write, res.error());
  11162. EXPECT_EQ(1, call_count.load());
  11163. }
  11164. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11165. // A writer only has to assign `write`. The other three used to be left as
  11166. // empty std::functions, so a provider calling one threw
  11167. // std::bad_function_call out of the thread running it and took the whole
  11168. // process down.
  11169. DataSink sink;
  11170. std::string written;
  11171. sink.write = [&](const char *data, size_t data_len) {
  11172. written.append(data, data_len);
  11173. return true;
  11174. };
  11175. EXPECT_TRUE(sink.is_writable());
  11176. sink.done();
  11177. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11178. EXPECT_TRUE(written.empty());
  11179. }
  11180. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11181. // A sink that cannot carry trailers still has to finish.
  11182. DataSink sink;
  11183. auto done_count = 0;
  11184. sink.done = [&]() { done_count++; };
  11185. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11186. EXPECT_EQ(1, done_count);
  11187. }
  11188. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11189. Server svr;
  11190. const std::string body(4096, 'x');
  11191. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11192. res.set_content_provider(body.size(), "text/plain",
  11193. [&](size_t offset, size_t length, DataSink &sink) {
  11194. sink.write(body.data() + offset, length);
  11195. sink.done();
  11196. return true;
  11197. });
  11198. });
  11199. auto port = svr.bind_to_any_port(HOST);
  11200. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11201. auto se = detail::scope_exit([&] {
  11202. svr.stop();
  11203. listen_thread.join();
  11204. ASSERT_FALSE(svr.is_running());
  11205. });
  11206. svr.wait_until_ready();
  11207. Client cli(HOST, port);
  11208. auto res = cli.Get("/");
  11209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11210. EXPECT_EQ(StatusCode::OK_200, res->status);
  11211. EXPECT_EQ(body, res->body);
  11212. }
  11213. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11214. Server svr;
  11215. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11216. res.set_content_provider(
  11217. 1024, "text/plain",
  11218. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11219. sink.write("hello", 5);
  11220. sink.done(); // short of the 1024 bytes the response promised
  11221. return true;
  11222. });
  11223. });
  11224. auto port = svr.bind_to_any_port(HOST);
  11225. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11226. auto se = detail::scope_exit([&] {
  11227. svr.stop();
  11228. listen_thread.join();
  11229. ASSERT_FALSE(svr.is_running());
  11230. });
  11231. svr.wait_until_ready();
  11232. Client cli(HOST, port);
  11233. cli.set_read_timeout(5, 0);
  11234. // The response is short of its Content-Length, so the client cannot read a
  11235. // complete body. What matters is that this returns at all: a no-op done()
  11236. // would leave the writer looping over a provider that never makes progress.
  11237. auto res = cli.Get("/");
  11238. EXPECT_FALSE(res);
  11239. }
  11240. // Read as the next response by a peer that sees it after a framed body.
  11241. static const std::string smuggled_response =
  11242. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11243. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11244. Server svr;
  11245. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11246. res.set_content_provider(
  11247. 5, "text/plain",
  11248. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11249. auto data = "AAAAA" + smuggled_response;
  11250. sink.write(data.data(), data.size());
  11251. return true;
  11252. });
  11253. });
  11254. thread t = thread([&] { svr.listen(HOST, PORT); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. t.join();
  11258. ASSERT_FALSE(svr.is_running());
  11259. });
  11260. svr.wait_until_ready();
  11261. std::string resp;
  11262. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11263. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11264. resp.clear();
  11265. ASSERT_TRUE(send_request(
  11266. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11267. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11268. }
  11269. TEST(NoContentTest, BodyIsNotSent) {
  11270. Server svr;
  11271. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11272. res.status = StatusCode::NoContent_204;
  11273. res.set_content(smuggled_response, "text/plain");
  11274. });
  11275. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11276. res.status = StatusCode::NotModified_304;
  11277. res.set_chunked_content_provider(
  11278. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11279. sink.write(smuggled_response.data(), smuggled_response.size());
  11280. sink.done();
  11281. return true;
  11282. });
  11283. });
  11284. thread t = thread([&] { svr.listen(HOST, PORT); });
  11285. auto se = detail::scope_exit([&] {
  11286. svr.stop();
  11287. t.join();
  11288. ASSERT_FALSE(svr.is_running());
  11289. });
  11290. svr.wait_until_ready();
  11291. for (auto path : {"/204", "/304"}) {
  11292. std::string resp;
  11293. ASSERT_TRUE(send_request(
  11294. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11295. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11296. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11297. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11298. }
  11299. }
  11300. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11301. Server svr;
  11302. std::atomic<bool> smuggled(false);
  11303. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11304. res.set_content("ok", "text/plain");
  11305. });
  11306. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11307. smuggled = true;
  11308. });
  11309. auto port = svr.bind_to_any_port(HOST);
  11310. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11311. auto se = detail::scope_exit([&] {
  11312. svr.stop();
  11313. listen_thread.join();
  11314. ASSERT_FALSE(svr.is_running());
  11315. });
  11316. svr.wait_until_ready();
  11317. // What follows the body would be read as the next request.
  11318. Client cli(HOST, port);
  11319. auto res = cli.Post(
  11320. "/", 5,
  11321. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11322. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11323. sink.write(data.data(), data.size());
  11324. return true;
  11325. },
  11326. "text/plain");
  11327. ASSERT_FALSE(res);
  11328. EXPECT_EQ(Error::Write, res.error());
  11329. EXPECT_FALSE(smuggled);
  11330. }
  11331. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11332. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11333. // The compressed path builds the whole body before connecting, so this
  11334. // fails client-side and never reaches a server.
  11335. Client cli(HOST, PORT);
  11336. cli.set_compress(true);
  11337. auto res = cli.Post(
  11338. "/", 1024,
  11339. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11340. sink.write("hello", 5);
  11341. sink.done(); // short of the 1024 bytes the request announced
  11342. return true;
  11343. },
  11344. "text/plain");
  11345. ASSERT_FALSE(res);
  11346. EXPECT_EQ(Error::Write, res.error());
  11347. }
  11348. #endif
  11349. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11350. Server svr;
  11351. svr.set_error_handler([](Request const &, Response &res) -> void {
  11352. res.set_chunked_content_provider(
  11353. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11354. sink.os << "hello";
  11355. sink.os << "world";
  11356. sink.done();
  11357. return true;
  11358. });
  11359. });
  11360. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11361. auto se = detail::scope_exit([&] {
  11362. svr.stop();
  11363. listen_thread.join();
  11364. ASSERT_FALSE(svr.is_running());
  11365. });
  11366. svr.wait_until_ready();
  11367. Client cli("localhost", PORT);
  11368. auto res = cli.Get("/");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11371. EXPECT_EQ("helloworld", res->body);
  11372. }
  11373. // A body set after a content provider must replace it, not be sent through it.
  11374. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11375. Server svr;
  11376. svr.set_mount_point("/", "./www");
  11377. svr.set_file_request_handler([](const Request &req, Response &res) {
  11378. if (req.path == "/dir/test.html") {
  11379. res.status = StatusCode::Forbidden_403;
  11380. res.set_content(std::string(5000, 'D'), "text/plain");
  11381. } else if (req.path == "/file") {
  11382. res.status = StatusCode::Forbidden_403;
  11383. res.body = "Denied";
  11384. }
  11385. });
  11386. auto port = svr.bind_to_any_port(HOST);
  11387. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11388. auto se = detail::scope_exit([&] {
  11389. svr.stop();
  11390. t.join();
  11391. ASSERT_FALSE(svr.is_running());
  11392. });
  11393. svr.wait_until_ready();
  11394. Client cli(HOST, port);
  11395. {
  11396. auto res = cli.Get("/dir/test.html");
  11397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11398. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11399. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11400. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11401. }
  11402. {
  11403. auto res = cli.Get("/file");
  11404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11405. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11406. EXPECT_EQ("Denied", res->body);
  11407. }
  11408. {
  11409. auto res = cli.Get("/dir/index.html");
  11410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11411. EXPECT_EQ(StatusCode::OK_200, res->status);
  11412. EXPECT_EQ(0U, res->body.find("<html>"));
  11413. }
  11414. }
  11415. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11416. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11417. Server svr;
  11418. std::vector<bool> released;
  11419. std::mutex released_mutex;
  11420. auto releaser = [&](bool success) {
  11421. std::lock_guard<std::mutex> guard(released_mutex);
  11422. released.push_back(success);
  11423. };
  11424. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11425. return sink.write(&"hello"[offset], length);
  11426. };
  11427. svr.Get("/sized", [&](const Request &, Response &res) {
  11428. res.status = StatusCode::NotFound_404;
  11429. res.set_content_provider(5, "text/plain", provider, releaser);
  11430. });
  11431. svr.Get("/chunked", [&](const Request &, Response &res) {
  11432. res.status = StatusCode::ServiceUnavailable_503;
  11433. res.set_chunked_content_provider(
  11434. "text/plain",
  11435. [](size_t, DataSink &sink) {
  11436. sink.os << "chunk";
  11437. sink.done();
  11438. return true;
  11439. },
  11440. releaser);
  11441. });
  11442. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11443. res.set_content_provider(5, "text/plain", provider, releaser);
  11444. throw std::runtime_error("after the provider");
  11445. });
  11446. svr.set_error_handler([](const Request &req, Response &res) {
  11447. // Leave the exception handler's content to it.
  11448. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11449. res.set_content(std::string(1000, 'E'), "text/html");
  11450. return Server::HandlerResponse::Handled;
  11451. });
  11452. svr.set_exception_handler(
  11453. [](const Request &, Response &res, std::exception_ptr) {
  11454. res.status = StatusCode::InternalServerError_500;
  11455. res.set_content(std::string(1000, 'X'), "text/html");
  11456. });
  11457. auto port = svr.bind_to_any_port(HOST);
  11458. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11459. auto se = detail::scope_exit([&] {
  11460. svr.stop();
  11461. t.join();
  11462. ASSERT_FALSE(svr.is_running());
  11463. });
  11464. svr.wait_until_ready();
  11465. Client cli(HOST, port);
  11466. {
  11467. auto res = cli.Get("/sized");
  11468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11470. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11472. }
  11473. {
  11474. auto res = cli.Get("/chunked");
  11475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11476. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11477. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11478. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11479. }
  11480. {
  11481. auto res = cli.Get("/throw");
  11482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11483. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11484. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11485. }
  11486. std::lock_guard<std::mutex> guard(released_mutex);
  11487. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11488. }
  11489. #endif
  11490. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11491. Server svr;
  11492. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11493. return sink.write(&"abc"[offset], length);
  11494. };
  11495. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11496. res.set_file_content("./www/dir/test.html");
  11497. res.set_content("body", "text/plain");
  11498. });
  11499. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11500. res.set_content(std::string(100, 'B'), "text/plain");
  11501. res.set_file_content("./www/dir/test.html");
  11502. });
  11503. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11504. res.set_content(std::string(100, 'B'), "text/plain");
  11505. res.set_content_provider(3, "text/x-provider", abc);
  11506. });
  11507. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11508. res.set_content_provider(3, "text/x-provider", abc);
  11509. res.set_content(std::string(100, 'B'), "text/plain");
  11510. });
  11511. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11512. res.set_content_provider(3, "text/x-provider", abc);
  11513. res.set_file_content("./www/dir/test.html", "text/x-file");
  11514. });
  11515. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11516. res.set_file_content("./www/dir/test.html");
  11517. res.set_header("Content-Type", "text/x-handler");
  11518. });
  11519. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11520. res.set_content_provider(3, "text/plain", abc);
  11521. res.body = "direct";
  11522. });
  11523. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11524. res.set_file_content("./www/dir/test.html");
  11525. res.body = "direct";
  11526. });
  11527. auto port = svr.bind_to_any_port(HOST);
  11528. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11529. auto se = detail::scope_exit([&] {
  11530. svr.stop();
  11531. t.join();
  11532. ASSERT_FALSE(svr.is_running());
  11533. });
  11534. svr.wait_until_ready();
  11535. Client cli(HOST, port);
  11536. auto expect_body = [&](const char *path, const std::string &body,
  11537. const std::string &type) {
  11538. // Uncompressed, so Content-Length can be compared with the body.
  11539. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11540. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11541. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11542. EXPECT_EQ(body, res->body) << path;
  11543. EXPECT_EQ(std::to_string(body.size()),
  11544. res->get_header_value("Content-Length"))
  11545. << path;
  11546. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11547. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11548. };
  11549. expect_body("/file-then-body", "body", "text/plain");
  11550. expect_body("/body-then-file", "test.html", "text/html");
  11551. expect_body("/body-then-provider", "abc", "text/x-provider");
  11552. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11553. expect_body("/provider-then-file", "test.html", "text/x-file");
  11554. expect_body("/file-then-header", "test.html", "text/x-handler");
  11555. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11556. expect_body("/file-then-direct-body", "direct", "text/plain");
  11557. // Ranges are checked against the body, not the dropped provider.
  11558. {
  11559. auto res = cli.Get("/provider-then-direct-body",
  11560. Headers{{make_range_header({{1, 2}})}});
  11561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11562. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11563. EXPECT_EQ("ir", res->body);
  11564. }
  11565. {
  11566. auto res = cli.Get("/file-then-direct-body",
  11567. Headers{{make_range_header({{7, 8}})}});
  11568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11569. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11570. }
  11571. }
  11572. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11573. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11574. const char *path = "./truncated_while_served.txt";
  11575. const size_t size = 32 * 1024 * 1024;
  11576. {
  11577. std::ofstream f(path, std::ios::binary);
  11578. f << std::string(size, 'x');
  11579. }
  11580. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11581. // Over TLS, where the bytes are encrypted in this process rather than
  11582. // copied by send().
  11583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11584. svr.Get("/file", [&](const Request &, Response &res) {
  11585. res.set_file_content(path, "text/plain");
  11586. });
  11587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11588. auto se = detail::scope_exit([&] {
  11589. svr.stop();
  11590. thread.join();
  11591. ASSERT_FALSE(svr.is_running());
  11592. });
  11593. svr.wait_until_ready();
  11594. // The file shrinks once the first bytes are in, as a rewrite in place
  11595. // would, and reading the mapping past its new end used to raise SIGBUS.
  11596. SSLClient cli(HOST, PORT);
  11597. cli.enable_server_certificate_verification(false);
  11598. size_t received = 0;
  11599. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11600. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11601. received += len;
  11602. return true;
  11603. });
  11604. EXPECT_FALSE(res);
  11605. EXPECT_LT(received, size);
  11606. }
  11607. #endif
  11608. // Forward declaration (see the base64_encode note).
  11609. namespace httplib {
  11610. namespace detail {
  11611. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11612. const std::string &content_type,
  11613. EncodingType encoding);
  11614. } // namespace detail
  11615. } // namespace httplib
  11616. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11617. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11618. ASSERT_TRUE(mm->is_open());
  11619. Response res;
  11620. detail::set_file_content_provider(res, mm, "text/html",
  11621. detail::EncodingType::None);
  11622. std::string out;
  11623. DataSink sink;
  11624. sink.write = [&](const char *d, size_t l) {
  11625. out.append(d, l);
  11626. return true;
  11627. };
  11628. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11629. EXPECT_EQ("test.html", out);
  11630. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11631. EXPECT_EQ("test.html", out);
  11632. }
  11633. TEST(LongPollingTest, ClientCloseDetection) {
  11634. Server svr;
  11635. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11636. res.set_chunked_content_provider(
  11637. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11638. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11639. sink.os << "hello";
  11640. auto count = 10;
  11641. while (count > 0 && sink.is_writable()) {
  11642. this_thread::sleep_for(chrono::milliseconds(10));
  11643. count--;
  11644. }
  11645. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11646. return true;
  11647. });
  11648. });
  11649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11650. auto se = detail::scope_exit([&] {
  11651. svr.stop();
  11652. listen_thread.join();
  11653. ASSERT_FALSE(svr.is_running());
  11654. });
  11655. svr.wait_until_ready();
  11656. Client cli("localhost", PORT);
  11657. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11658. EXPECT_EQ("hello", string(data, data_length));
  11659. return false; // close the socket immediately.
  11660. });
  11661. ASSERT_FALSE(res);
  11662. }
  11663. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11664. Server svr;
  11665. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11666. res.set_chunked_content_provider(
  11667. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11668. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11669. sink.os << "hello";
  11670. EXPECT_TRUE(sink.os.good());
  11671. // Wait for the client to close the connection
  11672. auto count = 10;
  11673. while (count > 0 && sink.is_writable()) {
  11674. this_thread::sleep_for(chrono::milliseconds(10));
  11675. count--;
  11676. }
  11677. // After client disconnect, write repeatedly until the socket
  11678. // write actually fails (small writes may be absorbed by the
  11679. // kernel buffer)
  11680. std::string chunk(1024, 'x');
  11681. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11682. sink.os << chunk;
  11683. }
  11684. EXPECT_TRUE(sink.os.fail());
  11685. return true;
  11686. });
  11687. });
  11688. auto port = svr.bind_to_any_port("localhost");
  11689. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11690. auto se = detail::scope_exit([&] {
  11691. svr.stop();
  11692. listen_thread.join();
  11693. ASSERT_FALSE(svr.is_running());
  11694. });
  11695. svr.wait_until_ready();
  11696. Client cli("localhost", port);
  11697. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11698. EXPECT_EQ("hello", string(data, data_length));
  11699. return false; // close the socket immediately.
  11700. });
  11701. ASSERT_FALSE(res);
  11702. }
  11703. TEST(GetWithParametersTest, GetWithParameters) {
  11704. Server svr;
  11705. svr.Get("/", [&](const Request &req, Response &) {
  11706. EXPECT_EQ("world", req.get_param_value("hello"));
  11707. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11708. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11709. });
  11710. svr.Get("/params", [&](const Request &req, Response &) {
  11711. EXPECT_EQ("world", req.get_param_value("hello"));
  11712. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11713. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11714. });
  11715. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11716. EXPECT_EQ("resource-id", req.matches[1]);
  11717. EXPECT_EQ("foo", req.get_param_value("param1"));
  11718. EXPECT_EQ("bar", req.get_param_value("param2"));
  11719. });
  11720. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11721. EXPECT_EQ("user-id", req.path_params.at("id"));
  11722. EXPECT_EQ("foo", req.get_param_value("param1"));
  11723. EXPECT_EQ("bar", req.get_param_value("param2"));
  11724. });
  11725. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11726. auto se = detail::scope_exit([&] {
  11727. svr.stop();
  11728. listen_thread.join();
  11729. ASSERT_FALSE(svr.is_running());
  11730. });
  11731. svr.wait_until_ready();
  11732. {
  11733. Client cli(HOST, PORT);
  11734. Params params;
  11735. params.emplace("hello", "world");
  11736. params.emplace("hello2", "world2");
  11737. params.emplace("hello3", "world3");
  11738. auto res = cli.Get("/", params, Headers{});
  11739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11740. EXPECT_EQ(StatusCode::OK_200, res->status);
  11741. }
  11742. {
  11743. Client cli(HOST, PORT);
  11744. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11746. EXPECT_EQ(StatusCode::OK_200, res->status);
  11747. }
  11748. {
  11749. Client cli(HOST, PORT);
  11750. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11752. EXPECT_EQ(StatusCode::OK_200, res->status);
  11753. }
  11754. {
  11755. Client cli(HOST, PORT);
  11756. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11758. EXPECT_EQ(StatusCode::OK_200, res->status);
  11759. }
  11760. }
  11761. TEST(GetWithParametersTest, GetWithParameters2) {
  11762. Server svr;
  11763. svr.Get("/", [&](const Request &req, Response &res) {
  11764. auto text = req.get_param_value("hello");
  11765. res.set_content(text, "text/plain");
  11766. });
  11767. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11768. auto se = detail::scope_exit([&] {
  11769. svr.stop();
  11770. listen_thread.join();
  11771. ASSERT_FALSE(svr.is_running());
  11772. });
  11773. svr.wait_until_ready();
  11774. Client cli("localhost", PORT);
  11775. Params params;
  11776. params.emplace("hello", "world");
  11777. std::string body;
  11778. auto res = cli.Get("/", params, Headers{},
  11779. [&](const char *data, size_t data_length) {
  11780. body.append(data, data_length);
  11781. return true;
  11782. });
  11783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11784. EXPECT_EQ(StatusCode::OK_200, res->status);
  11785. EXPECT_EQ("world", body);
  11786. }
  11787. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11788. Server svr;
  11789. svr.Get("/search", [&](const Request &req, Response &res) {
  11790. auto q = req.get_param_value("q");
  11791. res.set_content(q, "text/plain");
  11792. });
  11793. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11794. auto se = detail::scope_exit([&] {
  11795. svr.stop();
  11796. listen_thread.join();
  11797. ASSERT_FALSE(svr.is_running());
  11798. });
  11799. svr.wait_until_ready();
  11800. Client cli("localhost", PORT);
  11801. // Verify that Get(path, params) works without requiring Headers argument
  11802. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. EXPECT_EQ(StatusCode::OK_200, res->status);
  11805. EXPECT_EQ("cpp-httplib", res->body);
  11806. }
  11807. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11808. auto host = "httpbingo.org";
  11809. auto path = std::string{"/range/32"};
  11810. #ifdef CPPHTTPLIB_SSL_ENABLED
  11811. SSLClient cli(host);
  11812. #else
  11813. Client cli(host);
  11814. #endif
  11815. cli.set_default_headers({make_range_header({{1, 10}})});
  11816. cli.set_connection_timeout(5);
  11817. {
  11818. auto res = cli.Get(path);
  11819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11820. EXPECT_EQ("bcdefghijk", res->body);
  11821. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11822. }
  11823. {
  11824. auto res = cli.Get(path);
  11825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11826. EXPECT_EQ("bcdefghijk", res->body);
  11827. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11828. }
  11829. }
  11830. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11831. Server svr;
  11832. svr.set_default_headers({{"Hello", "World"}});
  11833. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11834. res.set_content("ok", "text/plain");
  11835. });
  11836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11837. auto se = detail::scope_exit([&] {
  11838. svr.stop();
  11839. listen_thread.join();
  11840. ASSERT_FALSE(svr.is_running());
  11841. });
  11842. svr.wait_until_ready();
  11843. Client cli("localhost", PORT);
  11844. auto res = cli.Get("/");
  11845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11846. EXPECT_EQ(StatusCode::OK_200, res->status);
  11847. EXPECT_EQ("ok", res->body);
  11848. EXPECT_EQ("World", res->get_header_value("Hello"));
  11849. }
  11850. #ifdef CPPHTTPLIB_SSL_ENABLED
  11851. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11853. ASSERT_TRUE(svr.is_valid());
  11854. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11855. std::this_thread::sleep_for(std::chrono::seconds(2));
  11856. res.set_content("a", "text/plain");
  11857. });
  11858. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11859. res.set_content("b", "text/plain");
  11860. });
  11861. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11862. auto se = detail::scope_exit([&] {
  11863. svr.stop();
  11864. listen_thread.join();
  11865. ASSERT_FALSE(svr.is_running());
  11866. });
  11867. svr.wait_until_ready();
  11868. SSLClient cli("localhost", PORT);
  11869. cli.enable_server_certificate_verification(false);
  11870. cli.set_keep_alive(true);
  11871. cli.set_read_timeout(std::chrono::seconds(1));
  11872. auto resa = cli.Get("/a");
  11873. ASSERT_TRUE(!resa);
  11874. EXPECT_EQ(Error::Read, resa.error());
  11875. auto resb = cli.Get("/b");
  11876. ASSERT_TRUE(resb);
  11877. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11878. EXPECT_EQ("b", resb->body);
  11879. }
  11880. // Closing an idle keep-alive connection sends close_notify and returns. The
  11881. // server must not wait for the client's close_notify: an idle client never
  11882. // sends one, so the worker would be held until the read timeout expires, and
  11883. // stop() would wait for it.
  11884. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11886. ASSERT_TRUE(svr.is_valid());
  11887. svr.set_keep_alive_timeout(1);
  11888. svr.set_read_timeout(10, 0);
  11889. svr.Get("/", [](const Request &, Response &res) {
  11890. res.set_content("ok", "text/plain");
  11891. });
  11892. auto port = svr.bind_to_any_port(HOST);
  11893. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11894. auto se = detail::scope_exit([&] {
  11895. if (listen_thread.joinable()) {
  11896. svr.stop();
  11897. listen_thread.join();
  11898. }
  11899. });
  11900. svr.wait_until_ready();
  11901. SSLClient cli(HOST, port);
  11902. cli.enable_server_certificate_verification(false);
  11903. cli.set_keep_alive(true);
  11904. auto res = cli.Get("/");
  11905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11906. EXPECT_EQ(StatusCode::OK_200, res->status);
  11907. // Stay idle past the keep-alive timeout so the server closes the connection.
  11908. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11909. auto start = std::chrono::steady_clock::now();
  11910. svr.stop();
  11911. listen_thread.join();
  11912. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11913. std::chrono::steady_clock::now() - start)
  11914. .count();
  11915. EXPECT_LT(elapsed, 3000);
  11916. }
  11917. #endif
  11918. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11919. protected:
  11920. ServerTestWithAI_PASSIVE()
  11921. : cli_(HOST, PORT)
  11922. #ifdef CPPHTTPLIB_SSL_ENABLED
  11923. ,
  11924. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11925. #endif
  11926. {
  11927. #ifdef CPPHTTPLIB_SSL_ENABLED
  11928. cli_.enable_server_certificate_verification(false);
  11929. #endif
  11930. }
  11931. virtual void SetUp() {
  11932. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11933. res.set_content("Hello World!", "text/plain");
  11934. });
  11935. t_ = thread(
  11936. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11937. svr_.wait_until_ready();
  11938. }
  11939. virtual void TearDown() {
  11940. svr_.stop();
  11941. t_.join();
  11942. }
  11943. #ifdef CPPHTTPLIB_SSL_ENABLED
  11944. SSLClient cli_;
  11945. SSLServer svr_;
  11946. #else
  11947. Client cli_;
  11948. Server svr_;
  11949. #endif
  11950. thread t_;
  11951. };
  11952. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11953. auto res = cli_.Get("/hi");
  11954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11955. EXPECT_EQ(StatusCode::OK_200, res->status);
  11956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11957. EXPECT_EQ("Hello World!", res->body);
  11958. }
  11959. class ServerUpDownTest : public ::testing::Test {
  11960. protected:
  11961. ServerUpDownTest() : cli_(HOST, PORT) {}
  11962. virtual void SetUp() {
  11963. t_ = thread([&]() {
  11964. svr_.bind_to_any_port(HOST);
  11965. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11966. ASSERT_TRUE(svr_.listen_after_bind());
  11967. });
  11968. svr_.wait_until_ready();
  11969. }
  11970. virtual void TearDown() {
  11971. svr_.stop();
  11972. t_.join();
  11973. }
  11974. Client cli_;
  11975. Server svr_;
  11976. thread t_;
  11977. };
  11978. TEST_F(ServerUpDownTest, QuickStartStop) {
  11979. // Should not crash, especially when run with
  11980. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11981. }
  11982. class PayloadMaxLengthTest : public ::testing::Test {
  11983. protected:
  11984. PayloadMaxLengthTest()
  11985. : cli_(HOST, PORT)
  11986. #ifdef CPPHTTPLIB_SSL_ENABLED
  11987. ,
  11988. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11989. #endif
  11990. {
  11991. #ifdef CPPHTTPLIB_SSL_ENABLED
  11992. cli_.enable_server_certificate_verification(false);
  11993. #endif
  11994. }
  11995. virtual void SetUp() {
  11996. svr_.set_payload_max_length(8);
  11997. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11998. res.set_content("test", "text/plain");
  11999. });
  12000. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12001. svr_.wait_until_ready();
  12002. }
  12003. virtual void TearDown() {
  12004. svr_.stop();
  12005. t_.join();
  12006. }
  12007. #ifdef CPPHTTPLIB_SSL_ENABLED
  12008. SSLClient cli_;
  12009. SSLServer svr_;
  12010. #else
  12011. Client cli_;
  12012. Server svr_;
  12013. #endif
  12014. thread t_;
  12015. };
  12016. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12017. auto res = cli_.Post("/test", "123456789", "text/plain");
  12018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12019. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12020. res = cli_.Post("/test", "12345678", "text/plain");
  12021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12022. EXPECT_EQ(StatusCode::OK_200, res->status);
  12023. }
  12024. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12025. // Test chunked encoding with payload exceeding the 8-byte limit
  12026. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12027. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12029. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12030. }
  12031. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12032. // Test chunked encoding with payload within the 8-byte limit
  12033. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12034. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12036. EXPECT_EQ(StatusCode::OK_200, res->status);
  12037. }
  12038. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12039. // Test using send_request to send chunked data exceeding payload limit
  12040. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12041. "Host: " +
  12042. std::string(HOST) + ":" + std::to_string(PORT) +
  12043. "\r\n"
  12044. "Transfer-Encoding: chunked\r\n"
  12045. "Connection: close\r\n"
  12046. "\r\n"
  12047. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12048. "0123456789\r\n"
  12049. "0\r\n" // End chunk
  12050. "\r\n";
  12051. std::string response;
  12052. bool result = send_request(1, chunked_request, &response);
  12053. if (!result) {
  12054. // If send_request fails, it might be because the server closed the
  12055. // connection due to payload limit enforcement, which is acceptable
  12056. SUCCEED()
  12057. << "Server rejected oversized chunked request (connection closed)";
  12058. } else {
  12059. // If we got a response, check if it's an error response or connection was
  12060. // closed early Short response length indicates connection was closed due to
  12061. // payload limit
  12062. if (response.length() <= 10) {
  12063. SUCCEED() << "Server closed connection for oversized chunked request";
  12064. } else {
  12065. // Check for error status codes
  12066. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12067. response.find("Payload Too Large") != std::string::npos ||
  12068. response.find("400") != std::string::npos);
  12069. }
  12070. }
  12071. }
  12072. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12073. // Test request without Content-Length header exceeding payload limit
  12074. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12075. "Host: " +
  12076. std::string(HOST) + ":" +
  12077. std::to_string(PORT) +
  12078. "\r\n"
  12079. "Connection: close\r\n"
  12080. "\r\n";
  12081. // Add payload exceeding the 8-byte limit
  12082. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12083. request_without_content_length += large_payload;
  12084. std::string response;
  12085. bool result = send_request(1, request_without_content_length, &response);
  12086. if (!result) {
  12087. // If send_request fails, server likely closed connection due to payload
  12088. // limit
  12089. SUCCEED() << "Server rejected oversized request without Content-Length "
  12090. "(connection closed)";
  12091. } else {
  12092. // Check if server responded with error or closed connection early
  12093. if (response.length() <= 10) {
  12094. SUCCEED() << "Server closed connection for oversized request without "
  12095. "Content-Length";
  12096. } else {
  12097. // Check for error status codes
  12098. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12099. response.find("Payload Too Large") != std::string::npos ||
  12100. response.find("400") != std::string::npos);
  12101. }
  12102. }
  12103. }
  12104. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12105. // Test request without Content-Length header within payload limit
  12106. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12107. "Host: " +
  12108. std::string(HOST) + ":" +
  12109. std::to_string(PORT) +
  12110. "\r\n"
  12111. "Connection: close\r\n"
  12112. "\r\n";
  12113. // Add payload within the 8-byte limit
  12114. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12115. request_without_content_length += small_payload;
  12116. std::string response;
  12117. bool result = send_request(1, request_without_content_length, &response);
  12118. // For requests without Content-Length, the server may have different behavior
  12119. // The key is that it should not reject due to payload limit for small
  12120. // payloads
  12121. if (result) {
  12122. // Check for any HTTP response (success or error, but not connection closed)
  12123. if (response.length() > 10) {
  12124. SUCCEED()
  12125. << "Server processed request without Content-Length within limit";
  12126. } else {
  12127. // Short response might indicate connection closed, which is acceptable
  12128. SUCCEED() << "Server closed connection for request without "
  12129. "Content-Length (acceptable behavior)";
  12130. }
  12131. } else {
  12132. // Connection failure might be due to protocol requirements
  12133. SUCCEED() << "Connection issue with request without Content-Length "
  12134. "(environment-specific)";
  12135. }
  12136. }
  12137. class LargePayloadMaxLengthTest : public ::testing::Test {
  12138. protected:
  12139. LargePayloadMaxLengthTest()
  12140. : cli_(HOST, PORT)
  12141. #ifdef CPPHTTPLIB_SSL_ENABLED
  12142. ,
  12143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12144. #endif
  12145. {
  12146. #ifdef CPPHTTPLIB_SSL_ENABLED
  12147. cli_.enable_server_certificate_verification(false);
  12148. #endif
  12149. }
  12150. virtual void SetUp() {
  12151. // Set 10MB payload limit
  12152. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12153. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12154. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12155. res.set_content("Large payload test", "text/plain");
  12156. });
  12157. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12158. svr_.wait_until_ready();
  12159. }
  12160. virtual void TearDown() {
  12161. svr_.stop();
  12162. t_.join();
  12163. }
  12164. #ifdef CPPHTTPLIB_SSL_ENABLED
  12165. SSLClient cli_;
  12166. SSLServer svr_;
  12167. #else
  12168. Client cli_;
  12169. Server svr_;
  12170. #endif
  12171. thread t_;
  12172. };
  12173. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12174. // Test chunked encoding with payload within 10MB limit
  12175. std::string medium_payload(5 * 1024 * 1024,
  12176. 'A'); // 5MB payload, within 10MB limit
  12177. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12179. EXPECT_EQ(StatusCode::OK_200, res->status);
  12180. }
  12181. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12182. // Test chunked encoding with payload exceeding 10MB limit
  12183. std::string large_payload(12 * 1024 * 1024,
  12184. 'B'); // 12MB payload, exceeds 10MB limit
  12185. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12186. // Server may either return 413 or close the connection
  12187. if (res) {
  12188. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12189. } else {
  12190. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12191. }
  12192. }
  12193. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12194. // Test request without Content-Length header within 10MB limit
  12195. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12196. "Host: " +
  12197. std::string(HOST) + ":" +
  12198. std::to_string(PORT) +
  12199. "\r\n"
  12200. "Connection: close\r\n"
  12201. "\r\n";
  12202. // Add 1MB payload (within 10MB limit)
  12203. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12204. request_without_content_length += medium_payload;
  12205. std::string response;
  12206. bool result = send_request(5, request_without_content_length, &response);
  12207. if (result) {
  12208. // Should get a proper HTTP response for payloads within limit
  12209. if (response.length() > 10) {
  12210. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12211. "10MB limit";
  12212. } else {
  12213. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12214. "Content-Length)";
  12215. }
  12216. } else {
  12217. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12218. }
  12219. }
  12220. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12221. // Test request without Content-Length header exceeding 10MB limit
  12222. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12223. "Host: " +
  12224. std::string(HOST) + ":" +
  12225. std::to_string(PORT) +
  12226. "\r\n"
  12227. "Connection: close\r\n"
  12228. "\r\n";
  12229. // Add 12MB payload (exceeds 10MB limit)
  12230. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12231. request_without_content_length += large_payload;
  12232. std::string response;
  12233. bool result = send_request(10, request_without_content_length, &response);
  12234. if (!result) {
  12235. // Server should close connection due to payload limit
  12236. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12237. "(connection closed)";
  12238. } else {
  12239. // Check for error response
  12240. if (response.length() <= 10) {
  12241. SUCCEED()
  12242. << "Server closed connection for 12MB request exceeding 10MB limit";
  12243. } else {
  12244. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12245. response.find("Payload Too Large") != std::string::npos ||
  12246. response.find("400") != std::string::npos);
  12247. }
  12248. }
  12249. }
  12250. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12251. Server svr;
  12252. svr.Get("/", [](const Request &, Response &res) {
  12253. // Claims the most the client accepts, far more than it sends, then drops
  12254. // the connection.
  12255. res.set_content_provider(std::string().max_size(), "text/plain",
  12256. [](size_t, size_t, DataSink &sink) {
  12257. sink.write("abc", 3);
  12258. return false;
  12259. });
  12260. });
  12261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12262. auto se = detail::scope_exit([&] {
  12263. svr.stop();
  12264. thread.join();
  12265. ASSERT_FALSE(svr.is_running());
  12266. });
  12267. svr.wait_until_ready();
  12268. Client cli(HOST, PORT);
  12269. cli.set_payload_max_length(0);
  12270. EXPECT_FALSE(cli.Get("/"));
  12271. }
  12272. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12273. // Stream API does, not as a plain read failure
  12274. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12275. Server svr;
  12276. svr.Get("/big", [](const Request &, Response &res) {
  12277. res.set_content(std::string(100000, 'b'), "text/plain");
  12278. });
  12279. auto port = svr.bind_to_any_port(HOST);
  12280. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12281. auto se = detail::scope_exit([&] {
  12282. svr.stop();
  12283. thread.join();
  12284. });
  12285. svr.wait_until_ready();
  12286. Client cli(HOST, port);
  12287. cli.set_payload_max_length(1000);
  12288. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12289. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12290. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12291. [](const char *, size_t) { return true; });
  12292. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12293. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12294. // Small on the wire, over the limit once decompressed
  12295. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12296. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12297. #endif
  12298. }
  12299. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12300. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12301. // path.
  12302. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12303. Server svr;
  12304. const size_t LIMIT = 64 * 1024; // 64KB
  12305. svr.set_payload_max_length(LIMIT);
  12306. size_t total = 0;
  12307. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12308. const ContentReader &content_reader) {
  12309. content_reader([&](const char * /*data*/, size_t len) {
  12310. total += len;
  12311. return true;
  12312. });
  12313. res.status = 200;
  12314. res.set_content("stream_ok", "text/plain");
  12315. });
  12316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12317. auto se = detail::scope_exit([&] {
  12318. svr.stop();
  12319. thread.join();
  12320. ASSERT_FALSE(svr.is_running());
  12321. });
  12322. svr.wait_until_ready();
  12323. // Prepare 256KB raw data and gzip-compress it
  12324. std::string raw(256 * 1024, 'A');
  12325. std::string gz;
  12326. {
  12327. z_stream zs{};
  12328. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12329. Z_DEFAULT_STRATEGY);
  12330. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12331. zs.avail_in = static_cast<uInt>(raw.size());
  12332. char outbuf[4096];
  12333. int ret;
  12334. do {
  12335. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12336. zs.avail_out = sizeof(outbuf);
  12337. ret = deflate(&zs, Z_FINISH);
  12338. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12339. } while (ret != Z_STREAM_END);
  12340. deflateEnd(&zs);
  12341. }
  12342. Client cli(HOST, PORT);
  12343. cli.set_connection_timeout(std::chrono::seconds(5));
  12344. Headers headers = {{"Content-Encoding", "gzip"}};
  12345. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12346. "application/octet-stream");
  12347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12348. // Server must reject oversized decompressed payloads with 413.
  12349. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12350. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12351. EXPECT_LE(total, LIMIT);
  12352. }
  12353. #ifndef CPPHTTPLIB_SSL_ENABLED
  12354. // For a request with neither Content-Length nor Transfer-Encoding, the
  12355. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12356. // compressed wire bytes straight to the ContentReader without ever routing
  12357. // them through the decompressor, so payload_max_length_ only bounded the
  12358. // compressed size on the wire, not the decompressed size.
  12359. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12360. Server svr;
  12361. const size_t LIMIT = 64 * 1024; // 64KB
  12362. svr.set_payload_max_length(LIMIT);
  12363. size_t total = 0;
  12364. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12365. const ContentReader &content_reader) {
  12366. content_reader([&](const char * /*data*/, size_t len) {
  12367. total += len;
  12368. return true;
  12369. });
  12370. res.status = 200;
  12371. res.set_content("stream_ok", "text/plain");
  12372. });
  12373. auto port = svr.bind_to_any_port(HOST);
  12374. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12375. auto se = detail::scope_exit([&] {
  12376. svr.stop();
  12377. thread.join();
  12378. ASSERT_FALSE(svr.is_running());
  12379. });
  12380. svr.wait_until_ready();
  12381. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12382. // StreamingGzipDecompression test above.
  12383. std::string raw(256 * 1024, 'A');
  12384. std::string gz;
  12385. {
  12386. httplib::detail::gzip_compressor compressor;
  12387. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12388. [&](const char *chunk, size_t len) {
  12389. gz.append(chunk, len);
  12390. return true;
  12391. });
  12392. ASSERT_TRUE(result);
  12393. }
  12394. // Send the gzip body over raw TCP with neither Content-Length nor
  12395. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12396. // kicks in.
  12397. std::string req = "POST /stream HTTP/1.1\r\n"
  12398. "Host: " +
  12399. std::string(HOST) + ":" + std::to_string(port) +
  12400. "\r\n"
  12401. "Content-Encoding: gzip\r\n"
  12402. "Connection: close\r\n"
  12403. "\r\n" +
  12404. gz;
  12405. std::string response;
  12406. ASSERT_TRUE(send_request(5, req, &response, port));
  12407. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12408. EXPECT_LE(total, LIMIT);
  12409. }
  12410. #endif
  12411. #endif
  12412. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12413. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12414. // the payload must be passed through untouched instead of being rejected.
  12415. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12416. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12417. Server svr;
  12418. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12419. res.set_content(body, "image/jpeg");
  12420. res.set_header("Content-Encoding", "UTF-8");
  12421. });
  12422. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12423. res.set_content(body, "image/jpeg");
  12424. res.set_header("Content-Encoding", "identity");
  12425. });
  12426. svr.Post("/echo", [](const Request &req, Response &res) {
  12427. res.set_content(req.body, "image/jpeg");
  12428. });
  12429. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12430. auto se = detail::scope_exit([&] {
  12431. svr.stop();
  12432. t.join();
  12433. ASSERT_FALSE(svr.is_running());
  12434. });
  12435. svr.wait_until_ready();
  12436. Client cli(HOST, PORT);
  12437. {
  12438. auto res = cli.Get("/image");
  12439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12440. EXPECT_EQ(StatusCode::OK_200, res->status);
  12441. EXPECT_EQ(body, res->body);
  12442. }
  12443. {
  12444. auto res = cli.Get("/identity");
  12445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12446. EXPECT_EQ(StatusCode::OK_200, res->status);
  12447. EXPECT_EQ(body, res->body);
  12448. }
  12449. {
  12450. // The same applies to a request body reaching the server.
  12451. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12452. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12454. EXPECT_EQ(StatusCode::OK_200, res->status);
  12455. EXPECT_EQ(body, res->body);
  12456. }
  12457. }
  12458. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12459. // gzip-encoded response even when the build has no zlib support.
  12460. static const char GZIPPED_HELLO_WORLD[] = {
  12461. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12462. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12463. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12464. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12465. // A content coding is a whole token, not something the field value merely
  12466. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12467. // as "fibre" look like Brotli, and turned a multi-coding value like
  12468. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12469. // it was never meant to see.
  12470. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12471. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12472. Server svr;
  12473. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12474. res.set_content(body, "image/jpeg");
  12475. res.set_header("Content-Encoding", "fibre");
  12476. });
  12477. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12478. res.set_content(body, "image/jpeg");
  12479. res.set_header("Content-Encoding", "gzip, br");
  12480. });
  12481. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12482. res.set_content(body, "image/jpeg");
  12483. res.set_header("Content-Encoding", "x-zstd-ish");
  12484. });
  12485. auto port = svr.bind_to_any_port(HOST);
  12486. thread t = thread([&]() { svr.listen_after_bind(); });
  12487. auto se = detail::scope_exit([&] {
  12488. svr.stop();
  12489. t.join();
  12490. ASSERT_FALSE(svr.is_running());
  12491. });
  12492. svr.wait_until_ready();
  12493. Client cli(HOST, port);
  12494. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12495. auto res = cli.Get(path);
  12496. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12497. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12498. // Not a coding we recognize, so the payload comes back untouched
  12499. EXPECT_EQ(body, res->body) << path;
  12500. }
  12501. }
  12502. // A content coding cpp-httplib recognizes but was not built with must be
  12503. // reported as such. Handing the still-compressed payload back to the caller
  12504. // would silently corrupt it.
  12505. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12506. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12507. Server svr;
  12508. // "image/jpeg" keeps the server from applying a content coding of its own,
  12509. // so the hand-crafted Content-Encoding below survives.
  12510. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12511. res.set_content(gzipped, "image/jpeg");
  12512. res.set_header("Content-Encoding", "gzip");
  12513. });
  12514. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12515. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12516. res.set_content(gzipped, "image/jpeg");
  12517. res.set_header("Content-Encoding", "GZIP");
  12518. });
  12519. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12520. auto se = detail::scope_exit([&] {
  12521. svr.stop();
  12522. t.join();
  12523. ASSERT_FALSE(svr.is_running());
  12524. });
  12525. svr.wait_until_ready();
  12526. Client cli(HOST, PORT);
  12527. {
  12528. auto res = cli.Get("/gzipped");
  12529. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12531. EXPECT_EQ("Hello World!", res->body);
  12532. #else
  12533. ASSERT_FALSE(res);
  12534. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12535. #endif
  12536. }
  12537. {
  12538. // open_stream() must behave the same way.
  12539. auto handle = cli.open_stream("GET", "/gzipped");
  12540. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12541. ASSERT_TRUE(handle.is_valid());
  12542. std::string received;
  12543. char buf[256];
  12544. ssize_t n;
  12545. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12546. received.append(buf, static_cast<size_t>(n));
  12547. }
  12548. EXPECT_EQ("Hello World!", received);
  12549. #else
  12550. EXPECT_FALSE(handle.is_valid());
  12551. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12552. #endif
  12553. }
  12554. {
  12555. // A differently-cased coding must not be mistaken for an unknown one, or
  12556. // the body would be handed back still compressed.
  12557. auto res = cli.Get("/gzipped-uppercase");
  12558. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12560. EXPECT_EQ("Hello World!", res->body);
  12561. #else
  12562. ASSERT_FALSE(res);
  12563. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12564. #endif
  12565. }
  12566. }
  12567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12568. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12569. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12570. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12571. // body a second time and appending a second Content-Encoding field line, so
  12572. // clients that decode one coding per listed value handed back raw gzip bytes.
  12573. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12574. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12575. Server svr;
  12576. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12577. // keeps the server from applying a coding of its own.
  12578. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12579. res.set_content(gzipped, "text/plain");
  12580. res.set_header("Content-Encoding", "gzip");
  12581. });
  12582. auto port = svr.bind_to_any_port(HOST);
  12583. thread t = thread([&]() { svr.listen_after_bind(); });
  12584. auto se = detail::scope_exit([&] {
  12585. svr.stop();
  12586. t.join();
  12587. ASSERT_FALSE(svr.is_running());
  12588. });
  12589. svr.wait_until_ready();
  12590. Client cli(HOST, port);
  12591. Headers headers = {{"Accept-Encoding", "gzip"}};
  12592. auto res = cli.Get("/pre-gzipped", headers);
  12593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12594. EXPECT_EQ(StatusCode::OK_200, res->status);
  12595. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12596. EXPECT_EQ("Hello World!", res->body);
  12597. }
  12598. // A chunked provider settles its coding where the headers are written and
  12599. // reuses it at write time. Both ends of that have to hold: a handler's own
  12600. // Content-Encoding suppresses the coding, and a response without one is still
  12601. // compressed as it always was.
  12602. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12603. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12604. const std::string plain = "Hello World! Hello World! Hello World!";
  12605. Server svr;
  12606. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12607. res.set_header("Content-Encoding", "gzip");
  12608. res.set_chunked_content_provider(
  12609. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12610. sink.write(gzipped.data(), gzipped.size());
  12611. sink.done();
  12612. return true;
  12613. });
  12614. });
  12615. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12616. res.set_chunked_content_provider(
  12617. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12618. sink.write(plain.data(), plain.size());
  12619. sink.done();
  12620. return true;
  12621. });
  12622. });
  12623. auto port = svr.bind_to_any_port(HOST);
  12624. thread t = thread([&]() { svr.listen_after_bind(); });
  12625. auto se = detail::scope_exit([&] {
  12626. svr.stop();
  12627. t.join();
  12628. ASSERT_FALSE(svr.is_running());
  12629. });
  12630. svr.wait_until_ready();
  12631. Client cli(HOST, port);
  12632. Headers headers = {{"Accept-Encoding", "gzip"}};
  12633. {
  12634. auto res = cli.Get("/pre-gzipped", headers);
  12635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12636. EXPECT_EQ(StatusCode::OK_200, res->status);
  12637. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12638. EXPECT_EQ("Hello World!", res->body);
  12639. }
  12640. {
  12641. auto res = cli.Get("/negotiated", headers);
  12642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12643. EXPECT_EQ(StatusCode::OK_200, res->status);
  12644. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12645. EXPECT_EQ(plain, res->body);
  12646. }
  12647. }
  12648. #endif
  12649. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12650. // the same message as the comma-joined one, so both have to be read the same
  12651. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12652. // single gzip coding, and a body the sender says was encoded twice was handed
  12653. // back after one pass, still compressed but presented as decoded.
  12654. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12655. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12656. Server svr;
  12657. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12658. res.set_content(body, "image/jpeg");
  12659. res.headers.emplace("Content-Encoding", "gzip");
  12660. res.headers.emplace("Content-Encoding", "gzip");
  12661. });
  12662. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12663. res.set_content(body, "image/jpeg");
  12664. res.set_header("Content-Encoding", "gzip, gzip");
  12665. });
  12666. auto port = svr.bind_to_any_port(HOST);
  12667. thread t = thread([&]() { svr.listen_after_bind(); });
  12668. auto se = detail::scope_exit([&] {
  12669. svr.stop();
  12670. t.join();
  12671. ASSERT_FALSE(svr.is_running());
  12672. });
  12673. svr.wait_until_ready();
  12674. Client cli(HOST, port);
  12675. // Two codings is not something cpp-httplib decodes, so both representations
  12676. // take the pass-through path rather than one of them being gunzipped once.
  12677. for (const char *path : {"/split", "/joined"}) {
  12678. auto res = cli.Get(path);
  12679. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12680. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12681. EXPECT_EQ(body, res->body) << path;
  12682. }
  12683. }
  12684. // Regression test for DoS vulnerability: a malicious server sending a response
  12685. // without Content-Length header must not cause unbounded memory consumption on
  12686. // the client side. The client should stop reading after a reasonable limit,
  12687. // similar to the server-side set_payload_max_length protection.
  12688. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12689. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12690. #ifndef _WIN32
  12691. signal(SIGPIPE, SIG_IGN);
  12692. #endif
  12693. auto server_thread = std::thread([] {
  12694. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12695. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12696. default_socket_options(srv);
  12697. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12698. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12699. sockaddr_in addr{};
  12700. addr.sin_family = AF_INET;
  12701. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12702. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12703. int opt = 1;
  12704. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12705. #ifdef _WIN32
  12706. reinterpret_cast<const char *>(&opt),
  12707. #else
  12708. &opt,
  12709. #endif
  12710. sizeof(opt));
  12711. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12712. ::listen(srv, 1);
  12713. sockaddr_in cli_addr{};
  12714. socklen_t cli_len = sizeof(cli_addr);
  12715. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12716. if (cli != INVALID_SOCKET) {
  12717. char buf[4096];
  12718. ::recv(cli, buf, sizeof(buf), 0);
  12719. // Malicious response: no Content-Length, no chunked encoding
  12720. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12721. "Connection: close\r\n"
  12722. "\r\n";
  12723. ::send(cli,
  12724. #ifdef _WIN32
  12725. static_cast<const char *>(response_header.c_str()),
  12726. static_cast<int>(response_header.size()),
  12727. #else
  12728. response_header.c_str(), response_header.size(),
  12729. #endif
  12730. 0);
  12731. // Send 10MB of data
  12732. std::string chunk(64 * 1024, 'A');
  12733. size_t total_sent = 0;
  12734. while (total_sent < MALICIOUS_DATA_SIZE) {
  12735. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12736. auto sent = ::send(cli,
  12737. #ifdef _WIN32
  12738. static_cast<const char *>(chunk.c_str()),
  12739. static_cast<int>(to_send),
  12740. #else
  12741. chunk.c_str(), to_send,
  12742. #endif
  12743. 0);
  12744. if (sent <= 0) break;
  12745. total_sent += static_cast<size_t>(sent);
  12746. }
  12747. detail::close_socket(cli);
  12748. }
  12749. detail::close_socket(srv);
  12750. });
  12751. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12752. size_t total_read = 0;
  12753. {
  12754. Client cli("127.0.0.1", PORT + 2);
  12755. cli.set_read_timeout(5, 0);
  12756. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12757. auto stream = cli.open_stream("GET", "/malicious");
  12758. ASSERT_TRUE(stream.is_valid());
  12759. char buffer[64 * 1024];
  12760. ssize_t n;
  12761. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12762. total_read += static_cast<size_t>(n);
  12763. }
  12764. } // StreamHandle and Client destroyed here, closing the socket
  12765. server_thread.join();
  12766. // With set_payload_max_length, the client must stop reading before consuming
  12767. // all 10MB. The read loop should be cut off at or near the configured limit.
  12768. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12769. << "Client read " << total_read << " bytes, exceeding the configured "
  12770. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12771. }
  12772. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12773. // the entire response body without truncation.
  12774. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12775. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12776. #ifndef _WIN32
  12777. signal(SIGPIPE, SIG_IGN);
  12778. #endif
  12779. auto server_thread = std::thread([] {
  12780. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12781. default_socket_options(srv);
  12782. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12783. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12784. sockaddr_in addr{};
  12785. addr.sin_family = AF_INET;
  12786. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12787. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12788. int opt = 1;
  12789. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12790. #ifdef _WIN32
  12791. reinterpret_cast<const char *>(&opt),
  12792. #else
  12793. &opt,
  12794. #endif
  12795. sizeof(opt));
  12796. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12797. ::listen(srv, 1);
  12798. sockaddr_in cli_addr{};
  12799. socklen_t cli_len = sizeof(cli_addr);
  12800. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12801. if (cli != INVALID_SOCKET) {
  12802. char buf[4096];
  12803. ::recv(cli, buf, sizeof(buf), 0);
  12804. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12805. "Connection: close\r\n"
  12806. "\r\n";
  12807. ::send(cli,
  12808. #ifdef _WIN32
  12809. static_cast<const char *>(response_header.c_str()),
  12810. static_cast<int>(response_header.size()),
  12811. #else
  12812. response_header.c_str(), response_header.size(),
  12813. #endif
  12814. 0);
  12815. std::string chunk(64 * 1024, 'A');
  12816. size_t total_sent = 0;
  12817. while (total_sent < DATA_SIZE) {
  12818. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12819. auto sent = ::send(cli,
  12820. #ifdef _WIN32
  12821. static_cast<const char *>(chunk.c_str()),
  12822. static_cast<int>(to_send),
  12823. #else
  12824. chunk.c_str(), to_send,
  12825. #endif
  12826. 0);
  12827. if (sent <= 0) break;
  12828. total_sent += static_cast<size_t>(sent);
  12829. }
  12830. #ifdef _WIN32
  12831. ::shutdown(cli, SD_SEND);
  12832. #else
  12833. ::shutdown(cli, SHUT_WR);
  12834. #endif
  12835. // Drain until the client closes its end, ensuring all data is delivered
  12836. char drain[1024];
  12837. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12838. detail::close_socket(cli);
  12839. }
  12840. detail::close_socket(srv);
  12841. });
  12842. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12843. size_t total_read = 0;
  12844. {
  12845. Client cli("127.0.0.1", PORT + 2);
  12846. cli.set_read_timeout(5, 0);
  12847. cli.set_payload_max_length(0); // 0 means no limit
  12848. auto stream = cli.open_stream("GET", "/data");
  12849. ASSERT_TRUE(stream.is_valid());
  12850. char buffer[64 * 1024];
  12851. ssize_t n;
  12852. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12853. total_read += static_cast<size_t>(n);
  12854. }
  12855. }
  12856. server_thread.join();
  12857. EXPECT_EQ(total_read, DATA_SIZE)
  12858. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12859. << " bytes without truncation, but only read " << total_read << " bytes.";
  12860. }
  12861. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12862. // enormous Content-Length must not cause the client to pre-allocate a huge
  12863. // response body buffer. The reservation is capped at payload_max_length_, and
  12864. // the read itself fails when the body exceeds the limit.
  12865. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12866. #ifndef _WIN32
  12867. signal(SIGPIPE, SIG_IGN);
  12868. #endif
  12869. auto server_thread = std::thread([] {
  12870. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12871. default_socket_options(srv);
  12872. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12874. sockaddr_in addr{};
  12875. addr.sin_family = AF_INET;
  12876. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12877. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12878. int opt = 1;
  12879. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12880. #ifdef _WIN32
  12881. reinterpret_cast<const char *>(&opt),
  12882. #else
  12883. &opt,
  12884. #endif
  12885. sizeof(opt));
  12886. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12887. ::listen(srv, 1);
  12888. sockaddr_in cli_addr{};
  12889. socklen_t cli_len = sizeof(cli_addr);
  12890. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12891. if (cli != INVALID_SOCKET) {
  12892. char buf[4096];
  12893. ::recv(cli, buf, sizeof(buf), 0);
  12894. // Malicious response: claim a 20GB body but send only a tiny payload.
  12895. std::string response = "HTTP/1.1 200 OK\r\n"
  12896. "Content-Length: 20000000000\r\n"
  12897. "\r\n"
  12898. "abc";
  12899. ::send(cli,
  12900. #ifdef _WIN32
  12901. static_cast<const char *>(response.c_str()),
  12902. static_cast<int>(response.size()),
  12903. #else
  12904. response.c_str(), response.size(),
  12905. #endif
  12906. 0);
  12907. detail::close_socket(cli);
  12908. }
  12909. detail::close_socket(srv);
  12910. });
  12911. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12912. {
  12913. Client cli("127.0.0.1", PORT + 2);
  12914. cli.set_read_timeout(5, 0);
  12915. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12916. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12917. // (server claims more bytes than payload_max_length permits), but it must
  12918. // not exhaust memory before getting there.
  12919. auto res = cli.Get("/malicious");
  12920. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12921. }
  12922. server_thread.join();
  12923. }
  12924. // Verify that content_receiver bypasses the default payload_max_length,
  12925. // allowing streaming downloads larger than 100MB without requiring an explicit
  12926. // set_payload_max_length call.
  12927. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12928. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12929. #ifndef _WIN32
  12930. signal(SIGPIPE, SIG_IGN);
  12931. #endif
  12932. auto server_thread = std::thread([] {
  12933. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12934. default_socket_options(srv);
  12935. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12936. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12937. sockaddr_in addr{};
  12938. addr.sin_family = AF_INET;
  12939. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12940. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12941. int opt = 1;
  12942. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12943. #ifdef _WIN32
  12944. reinterpret_cast<const char *>(&opt),
  12945. #else
  12946. &opt,
  12947. #endif
  12948. sizeof(opt));
  12949. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12950. ::listen(srv, 1);
  12951. sockaddr_in cli_addr{};
  12952. socklen_t cli_len = sizeof(cli_addr);
  12953. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12954. if (cli != INVALID_SOCKET) {
  12955. char buf[4096];
  12956. ::recv(cli, buf, sizeof(buf), 0);
  12957. // Response with Content-Length larger than default 100MB limit
  12958. auto content_length = std::to_string(DATA_SIZE);
  12959. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12960. "Content-Length: " +
  12961. content_length +
  12962. "\r\n"
  12963. "Connection: close\r\n"
  12964. "\r\n";
  12965. ::send(cli,
  12966. #ifdef _WIN32
  12967. static_cast<const char *>(response_header.c_str()),
  12968. static_cast<int>(response_header.size()),
  12969. #else
  12970. response_header.c_str(), response_header.size(),
  12971. #endif
  12972. 0);
  12973. std::string chunk(64 * 1024, 'A');
  12974. size_t total_sent = 0;
  12975. while (total_sent < DATA_SIZE) {
  12976. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12977. auto sent = ::send(cli,
  12978. #ifdef _WIN32
  12979. static_cast<const char *>(chunk.c_str()),
  12980. static_cast<int>(to_send),
  12981. #else
  12982. chunk.c_str(), to_send,
  12983. #endif
  12984. 0);
  12985. if (sent <= 0) break;
  12986. total_sent += static_cast<size_t>(sent);
  12987. }
  12988. detail::close_socket(cli);
  12989. }
  12990. detail::close_socket(srv);
  12991. });
  12992. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12993. size_t total_received = 0;
  12994. {
  12995. Client cli("127.0.0.1", PORT + 2);
  12996. cli.set_read_timeout(10, 0);
  12997. // Do NOT call set_payload_max_length — use the default 100MB limit
  12998. auto res =
  12999. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13000. total_received += data_length;
  13001. return true;
  13002. });
  13003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13004. EXPECT_EQ(StatusCode::OK_200, res->status);
  13005. }
  13006. server_thread.join();
  13007. EXPECT_EQ(total_received, DATA_SIZE)
  13008. << "With content_receiver, the client should read all " << DATA_SIZE
  13009. << " bytes despite the default 100MB payload_max_length, but only read "
  13010. << total_received << " bytes.";
  13011. }
  13012. // Verify that an explicit set_payload_max_length smaller than the response is
  13013. // enforced even when a content_receiver is used.
  13014. TEST(ClientVulnerabilityTest,
  13015. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13016. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13017. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13018. #ifndef _WIN32
  13019. signal(SIGPIPE, SIG_IGN);
  13020. #endif
  13021. auto server_thread = std::thread([] {
  13022. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13023. default_socket_options(srv);
  13024. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13025. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13026. sockaddr_in addr{};
  13027. addr.sin_family = AF_INET;
  13028. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13029. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13030. int opt = 1;
  13031. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13032. #ifdef _WIN32
  13033. reinterpret_cast<const char *>(&opt),
  13034. #else
  13035. &opt,
  13036. #endif
  13037. sizeof(opt));
  13038. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13039. ::listen(srv, 1);
  13040. sockaddr_in cli_addr{};
  13041. socklen_t cli_len = sizeof(cli_addr);
  13042. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13043. if (cli != INVALID_SOCKET) {
  13044. char buf[4096];
  13045. ::recv(cli, buf, sizeof(buf), 0);
  13046. auto content_length = std::to_string(DATA_SIZE);
  13047. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13048. "Content-Length: " +
  13049. content_length +
  13050. "\r\n"
  13051. "Connection: close\r\n"
  13052. "\r\n";
  13053. ::send(cli,
  13054. #ifdef _WIN32
  13055. static_cast<const char *>(response_header.c_str()),
  13056. static_cast<int>(response_header.size()),
  13057. #else
  13058. response_header.c_str(), response_header.size(),
  13059. #endif
  13060. 0);
  13061. std::string chunk(64 * 1024, 'A');
  13062. size_t total_sent = 0;
  13063. while (total_sent < DATA_SIZE) {
  13064. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13065. auto sent = ::send(cli,
  13066. #ifdef _WIN32
  13067. static_cast<const char *>(chunk.c_str()),
  13068. static_cast<int>(to_send),
  13069. #else
  13070. chunk.c_str(), to_send,
  13071. #endif
  13072. 0);
  13073. if (sent <= 0) break;
  13074. total_sent += static_cast<size_t>(sent);
  13075. }
  13076. detail::close_socket(cli);
  13077. }
  13078. detail::close_socket(srv);
  13079. });
  13080. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13081. size_t total_received = 0;
  13082. {
  13083. Client cli("127.0.0.1", PORT + 2);
  13084. cli.set_read_timeout(10, 0);
  13085. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13086. auto res =
  13087. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13088. total_received += data_length;
  13089. return true;
  13090. });
  13091. // Should fail because 200MB exceeds the explicit 150MB limit
  13092. EXPECT_FALSE(res);
  13093. }
  13094. server_thread.join();
  13095. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13096. << "Client with content_receiver should respect the explicit "
  13097. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13098. << total_received << " bytes.";
  13099. }
  13100. // Verify that an explicit set_payload_max_length larger than the response
  13101. // allows the content_receiver to read all data successfully.
  13102. TEST(ClientVulnerabilityTest,
  13103. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13104. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13105. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13106. #ifndef _WIN32
  13107. signal(SIGPIPE, SIG_IGN);
  13108. #endif
  13109. auto server_thread = std::thread([] {
  13110. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13111. default_socket_options(srv);
  13112. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13113. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13114. sockaddr_in addr{};
  13115. addr.sin_family = AF_INET;
  13116. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13117. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13118. int opt = 1;
  13119. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13120. #ifdef _WIN32
  13121. reinterpret_cast<const char *>(&opt),
  13122. #else
  13123. &opt,
  13124. #endif
  13125. sizeof(opt));
  13126. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13127. ::listen(srv, 1);
  13128. sockaddr_in cli_addr{};
  13129. socklen_t cli_len = sizeof(cli_addr);
  13130. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13131. if (cli != INVALID_SOCKET) {
  13132. char buf[4096];
  13133. ::recv(cli, buf, sizeof(buf), 0);
  13134. auto content_length = std::to_string(DATA_SIZE);
  13135. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13136. "Content-Length: " +
  13137. content_length +
  13138. "\r\n"
  13139. "Connection: close\r\n"
  13140. "\r\n";
  13141. ::send(cli,
  13142. #ifdef _WIN32
  13143. static_cast<const char *>(response_header.c_str()),
  13144. static_cast<int>(response_header.size()),
  13145. #else
  13146. response_header.c_str(), response_header.size(),
  13147. #endif
  13148. 0);
  13149. std::string chunk(64 * 1024, 'A');
  13150. size_t total_sent = 0;
  13151. while (total_sent < DATA_SIZE) {
  13152. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13153. auto sent = ::send(cli,
  13154. #ifdef _WIN32
  13155. static_cast<const char *>(chunk.c_str()),
  13156. static_cast<int>(to_send),
  13157. #else
  13158. chunk.c_str(), to_send,
  13159. #endif
  13160. 0);
  13161. if (sent <= 0) break;
  13162. total_sent += static_cast<size_t>(sent);
  13163. }
  13164. #ifdef _WIN32
  13165. ::shutdown(cli, SD_SEND);
  13166. #else
  13167. ::shutdown(cli, SHUT_WR);
  13168. #endif
  13169. char drain[1024];
  13170. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13171. detail::close_socket(cli);
  13172. }
  13173. detail::close_socket(srv);
  13174. });
  13175. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13176. size_t total_received = 0;
  13177. {
  13178. Client cli("127.0.0.1", PORT + 2);
  13179. cli.set_read_timeout(10, 0);
  13180. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13181. auto res =
  13182. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13183. total_received += data_length;
  13184. return true;
  13185. });
  13186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13187. EXPECT_EQ(StatusCode::OK_200, res->status);
  13188. }
  13189. server_thread.join();
  13190. EXPECT_EQ(total_received, DATA_SIZE)
  13191. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13192. << " bytes (larger than " << DATA_SIZE
  13193. << " bytes response), content_receiver should read all data, but only "
  13194. "read "
  13195. << total_received << " bytes.";
  13196. }
  13197. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13198. // Regression test for "zip bomb" attack on the client side: a malicious server
  13199. // sends a small gzip-compressed response that decompresses to a huge payload.
  13200. // The client must enforce payload_max_length on the decompressed size.
  13201. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13202. constexpr size_t DECOMPRESSED_SIZE =
  13203. 10 * 1024 * 1024; // 10MB after decompression
  13204. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13205. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13206. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13207. std::string compressed;
  13208. {
  13209. httplib::detail::gzip_compressor compressor;
  13210. bool ok =
  13211. compressor.compress(uncompressed.data(), uncompressed.size(),
  13212. /*last=*/true, [&](const char *buf, size_t len) {
  13213. compressed.append(buf, len);
  13214. return true;
  13215. });
  13216. ASSERT_TRUE(ok);
  13217. }
  13218. // Sanity: compressed data should be much smaller than the decompressed size
  13219. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13220. #ifndef _WIN32
  13221. signal(SIGPIPE, SIG_IGN);
  13222. #endif
  13223. // Set up the listening socket in the main thread so the server is guaranteed
  13224. // to be ready before the client connects (eliminates race condition).
  13225. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13226. default_socket_options(srv);
  13227. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13228. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13229. sockaddr_in addr{};
  13230. addr.sin_family = AF_INET;
  13231. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13232. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13233. int opt = 1;
  13234. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13235. #ifdef _WIN32
  13236. reinterpret_cast<const char *>(&opt),
  13237. #else
  13238. &opt,
  13239. #endif
  13240. sizeof(opt));
  13241. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13242. ASSERT_EQ(0, ::listen(srv, 1));
  13243. auto server_thread = std::thread([&compressed, srv] {
  13244. sockaddr_in cli_addr{};
  13245. socklen_t cli_len = sizeof(cli_addr);
  13246. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13247. if (cli != INVALID_SOCKET) {
  13248. // Read the full HTTP request (until \r\n\r\n)
  13249. char buf[4096];
  13250. size_t total = 0;
  13251. while (total < sizeof(buf)) {
  13252. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13253. if (n <= 0) break;
  13254. total += static_cast<size_t>(n);
  13255. // Check for end of headers
  13256. if (total >= 4) {
  13257. std::string req(buf, total);
  13258. if (req.find("\r\n\r\n") != std::string::npos) break;
  13259. }
  13260. }
  13261. // Malicious response: gzip-compressed body, no Content-Length
  13262. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13263. "Content-Encoding: gzip\r\n"
  13264. "Connection: close\r\n"
  13265. "\r\n";
  13266. ::send(cli,
  13267. #ifdef _WIN32
  13268. static_cast<const char *>(response_header.c_str()),
  13269. static_cast<int>(response_header.size()),
  13270. #else
  13271. response_header.c_str(), response_header.size(),
  13272. #endif
  13273. 0);
  13274. // Send the compressed payload (small on the wire, huge when decompressed)
  13275. size_t total_sent = 0;
  13276. while (total_sent < compressed.size()) {
  13277. auto to_send = std::min(compressed.size() - total_sent,
  13278. static_cast<size_t>(64 * 1024));
  13279. auto sent =
  13280. ::send(cli,
  13281. #ifdef _WIN32
  13282. static_cast<const char *>(compressed.c_str() + total_sent),
  13283. static_cast<int>(to_send),
  13284. #else
  13285. compressed.c_str() + total_sent, to_send,
  13286. #endif
  13287. 0);
  13288. if (sent <= 0) break;
  13289. total_sent += static_cast<size_t>(sent);
  13290. }
  13291. detail::close_socket(cli);
  13292. }
  13293. });
  13294. auto se = detail::scope_exit([&] {
  13295. detail::close_socket(srv);
  13296. server_thread.join();
  13297. });
  13298. size_t total_decompressed = 0;
  13299. {
  13300. Client cli("127.0.0.1", PORT + 3);
  13301. cli.set_read_timeout(5, 0);
  13302. cli.set_decompress(true);
  13303. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13304. auto stream = cli.open_stream("GET", "/zipbomb");
  13305. ASSERT_TRUE(stream.is_valid());
  13306. char buffer[64 * 1024];
  13307. ssize_t n;
  13308. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13309. total_decompressed += static_cast<size_t>(n);
  13310. }
  13311. }
  13312. // The decompressed size must be capped by payload_max_length. Without
  13313. // protection, the client would decompress the full 10MB from a tiny
  13314. // compressed payload, enabling a zip bomb DoS attack.
  13315. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13316. << "Client decompressed " << total_decompressed
  13317. << " bytes from a gzip response. The decompressed size should be "
  13318. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13319. }
  13320. #endif
  13321. TEST(HostAndPortPropertiesTest, NoSSL) {
  13322. httplib::Client cli("www.google.com", 1234);
  13323. ASSERT_EQ("www.google.com", cli.host());
  13324. ASSERT_EQ(1234, cli.port());
  13325. }
  13326. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13327. httplib::Client cli("www.google.com:1234");
  13328. ASSERT_EQ("www.google.com", cli.host());
  13329. ASSERT_EQ(1234, cli.port());
  13330. }
  13331. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13332. // Port number that overflows int — should not crash, client becomes invalid
  13333. httplib::Client cli("http://www.google.com:99999999999999999999");
  13334. ASSERT_FALSE(cli.is_valid());
  13335. }
  13336. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13337. // Port 99999 exceeds valid range (1-65535) — should not crash
  13338. httplib::Client cli("http://www.google.com:99999");
  13339. ASSERT_FALSE(cli.is_valid());
  13340. auto res = cli.Get("/");
  13341. EXPECT_FALSE(res);
  13342. EXPECT_EQ(Error::Connection, res.error());
  13343. }
  13344. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13345. httplib::Client cli("http://user:pass@localhost:1234");
  13346. ASSERT_FALSE(cli.is_valid());
  13347. EXPECT_FALSE(cli.Get("/"));
  13348. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13349. }
  13350. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13351. httplib::Client cli("http://www.google.com:80abc");
  13352. ASSERT_FALSE(cli.is_valid());
  13353. }
  13354. #ifdef CPPHTTPLIB_SSL_ENABLED
  13355. TEST(HostAndPortPropertiesTest, SSL) {
  13356. httplib::SSLClient cli("www.google.com");
  13357. ASSERT_EQ("www.google.com", cli.host());
  13358. ASSERT_EQ(443, cli.port());
  13359. }
  13360. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13361. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13362. std::string cert;
  13363. read_file(CA_CERT_FILE, cert);
  13364. httplib::SSLClient httplib_client("www.google.com");
  13365. // Load CA store first time
  13366. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13367. // Load CA store second time (update)
  13368. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13369. // Verify client is still valid and can make connections
  13370. httplib_client.enable_server_certificate_verification(true);
  13371. auto res = httplib_client.Get("/");
  13372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13373. // Google may return 200 or 301 depending on various factors
  13374. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13375. res->status == StatusCode::MovedPermanently_301);
  13376. }
  13377. TEST(SSLClientTest, ServerNameIndication_Online) {
  13378. auto host = "httpbingo.org";
  13379. auto path = std::string{"/get"};
  13380. SSLClient cli(host, 443);
  13381. auto res = cli.Get(path);
  13382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13383. ASSERT_EQ(StatusCode::OK_200, res->status);
  13384. }
  13385. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13386. // Use a site that will cause SSL verification failure due to self-signed cert
  13387. SSLClient cli("self-signed.badssl.com", 443);
  13388. cli.enable_server_certificate_verification(true);
  13389. auto res = cli.Get("/");
  13390. ASSERT_TRUE(!res);
  13391. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13392. // Verify backend error is captured for SSLServerVerification
  13393. // This occurs when certificate verification fails
  13394. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13395. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13396. EXPECT_NE(0UL, res.ssl_backend_error());
  13397. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13398. res.ssl_error());
  13399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13400. #if !defined(_WIN32) || \
  13401. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13402. // On non-Windows or when Windows Schannel is disabled, the error comes
  13403. // from OpenSSL's verification
  13404. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13405. res.ssl_backend_error());
  13406. #endif
  13407. #endif
  13408. }
  13409. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13410. // Use a site where hostname doesn't match the certificate
  13411. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13412. SSLClient cli("wrong.host.badssl.com", 443);
  13413. cli.enable_server_certificate_verification(true);
  13414. cli.enable_server_hostname_verification(true);
  13415. auto res = cli.Get("/");
  13416. ASSERT_TRUE(!res);
  13417. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13418. // Verify backend error is captured for hostname verification failure
  13419. EXPECT_NE(0UL, res.ssl_backend_error());
  13420. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13421. res.ssl_error());
  13422. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13423. #if !defined(_WIN32) || \
  13424. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13425. // On non-Windows or when Windows Schannel is disabled, the error comes
  13426. // from OpenSSL's hostname verification
  13427. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13428. res.ssl_backend_error());
  13429. #endif
  13430. #endif
  13431. }
  13432. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13433. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13434. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13435. SSLClient cli("www.google.com", 443);
  13436. cli.enable_server_certificate_verification(true);
  13437. auto res = cli.Get("/");
  13438. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13439. }
  13440. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13441. SSLClient cli("www.google.com", 443);
  13442. cli.enable_server_certificate_verification(true);
  13443. cli.enable_windows_certificate_verification(false);
  13444. auto res = cli.Get("/");
  13445. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13446. }
  13447. // The server sends an intermediate cross-signed by a root Windows trusts,
  13448. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13449. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13450. SSLClient cli("accounts.spotify.com", 443);
  13451. auto res = cli.Get("/");
  13452. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13453. << " ssl_backend_error=" << res.ssl_backend_error();
  13454. }
  13455. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13456. // policy status, which no backend reports for a self-signed certificate.
  13457. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13458. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13459. ASSERT_TRUE(svr.is_valid());
  13460. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13461. auto se = detail::scope_exit([&] {
  13462. svr.stop();
  13463. t.join();
  13464. ASSERT_FALSE(svr.is_running());
  13465. });
  13466. svr.wait_until_ready();
  13467. SSLClient cli("127.0.0.1", PORT);
  13468. cli.set_connection_timeout(30);
  13469. auto res = cli.Get("/");
  13470. ASSERT_FALSE(res);
  13471. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13472. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13473. }
  13474. #endif
  13475. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13476. Client cli("https://google.com");
  13477. auto res = cli.Get("/");
  13478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13479. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13480. }
  13481. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13482. SSLClient cli("google.com");
  13483. cli.set_ca_cert_path(CA_CERT_FILE);
  13484. auto res = cli.Get("/");
  13485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13486. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13487. }
  13488. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13489. SSLClient cli("google.com");
  13490. cli.enable_server_certificate_verification(true);
  13491. cli.set_ca_cert_path("hello");
  13492. auto res = cli.Get("/");
  13493. ASSERT_TRUE(!res);
  13494. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13495. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13496. // should be set
  13497. EXPECT_EQ(0, res.ssl_error());
  13498. // Verify backend error is captured for SSLLoadingCerts
  13499. // This error occurs when loading CA certificates fails
  13500. EXPECT_NE(0UL, res.ssl_backend_error());
  13501. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13502. // OpenSSL specific error codes:
  13503. // > openssl errstr 0x80000002
  13504. // error:80000002:system library::No such file or directory
  13505. // > openssl errstr 0xA000126
  13506. // error:0A000126:SSL routines::unexpected eof while reading
  13507. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13508. res.ssl_backend_error() == 0xA000126);
  13509. #endif
  13510. }
  13511. TEST(SSLClientTest, ServerCertificateVerification4) {
  13512. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13513. ASSERT_TRUE(svr.is_valid());
  13514. svr.Get("/test", [&](const Request &, Response &res) {
  13515. res.set_content("test", "text/plain");
  13516. svr.stop();
  13517. ASSERT_TRUE(true);
  13518. });
  13519. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13520. auto se = detail::scope_exit([&] {
  13521. t.join();
  13522. ASSERT_FALSE(svr.is_running());
  13523. });
  13524. svr.wait_until_ready();
  13525. SSLClient cli("127.0.0.1", PORT);
  13526. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13527. cli.enable_server_certificate_verification(true);
  13528. cli.set_connection_timeout(30);
  13529. auto res = cli.Get("/test");
  13530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13531. ASSERT_EQ(StatusCode::OK_200, res->status);
  13532. }
  13533. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13534. std::string cert;
  13535. read_file(CA_CERT_FILE, cert);
  13536. SSLClient cli("google.com");
  13537. cli.load_ca_cert_store(cert.data(), cert.size());
  13538. const auto res = cli.Get("/");
  13539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13540. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13541. }
  13542. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13543. // clang-format off
  13544. static constexpr char cert[] =
  13545. "GlobalSign Root CA\n"
  13546. "==================\n"
  13547. "-----BEGIN CERTIFICATE-----\n"
  13548. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13549. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13550. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13551. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13552. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13553. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13554. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13555. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13556. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13557. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13558. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13559. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13560. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13561. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13562. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13563. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13564. "-----END CERTIFICATE-----\n";
  13565. // clang-format on
  13566. SSLClient cli("google.com");
  13567. cli.load_ca_cert_store(cert, sizeof(cert));
  13568. const auto res = cli.Get("/");
  13569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13570. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13571. }
  13572. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13573. SSLClient cli("www.youtube.com");
  13574. cli.set_ca_cert_path(CA_CERT_FILE);
  13575. cli.enable_server_certificate_verification(true);
  13576. cli.set_follow_location(true);
  13577. auto res = cli.Get("/");
  13578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13579. ASSERT_EQ(StatusCode::OK_200, res->status);
  13580. }
  13581. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13582. SSLClient cli("wWw.YouTube.Com");
  13583. cli.set_ca_cert_path(CA_CERT_FILE);
  13584. cli.enable_server_certificate_verification(true);
  13585. cli.enable_server_hostname_verification(true);
  13586. cli.set_follow_location(true);
  13587. auto res = cli.Get("/");
  13588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13589. ASSERT_EQ(StatusCode::OK_200, res->status);
  13590. }
  13591. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13592. SSLClient cli("gOoGlE.COm");
  13593. cli.enable_server_certificate_verification(true);
  13594. cli.enable_server_hostname_verification(true);
  13595. cli.set_follow_location(true);
  13596. auto res = cli.Get("/");
  13597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13598. ASSERT_EQ(StatusCode::OK_200, res->status);
  13599. }
  13600. TEST(SSLClientTest, Issue2004_Online) {
  13601. Client client("https://google.com");
  13602. client.set_follow_location(true);
  13603. auto res = client.Get("/");
  13604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13605. ASSERT_EQ(StatusCode::OK_200, res->status);
  13606. auto body = res->body;
  13607. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13608. }
  13609. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13610. // Create SSLClient with invalid cert/key to make is_valid() return false
  13611. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13612. "nonexistent_key.pem");
  13613. // is_valid() should be false due to cert loading failure
  13614. ASSERT_FALSE(cli.is_valid());
  13615. auto res = cli.Get("/");
  13616. ASSERT_FALSE(res);
  13617. EXPECT_EQ(Error::SSLConnection, res.error());
  13618. }
  13619. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13620. // Test for Issue #2251: SSL error not properly reported when client cert
  13621. // and key paths are swapped or mismatched
  13622. // This simulates the scenario where user accidentally swaps the cert and key
  13623. // files
  13624. // Using client cert file as private key and vice versa (completely wrong)
  13625. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13626. // Should fail validation due to cert/key mismatch
  13627. ASSERT_FALSE(cli.is_valid());
  13628. // Attempt to make a request should fail with proper error
  13629. auto res = cli.Get("/");
  13630. ASSERT_FALSE(res);
  13631. EXPECT_EQ(Error::SSLConnection, res.error());
  13632. // SSL error should be recorded in the Result object (this is the key fix for
  13633. // Issue #2251)
  13634. auto backend_error = res.ssl_backend_error();
  13635. EXPECT_NE(0u, backend_error);
  13636. }
  13637. // Tests cert/key mismatch detection at the TLS context level
  13638. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13639. // Test that using mismatched cert/key causes connection failure.
  13640. // We verify this at the SSLClient level rather than through internal
  13641. // TLS API functions.
  13642. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13643. cli.enable_server_certificate_verification(false);
  13644. cli.set_connection_timeout(2);
  13645. // The mismatch should cause a connection or handshake error
  13646. auto res = cli.Get("/test");
  13647. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13648. // Either way, the request should fail
  13649. EXPECT_FALSE(res);
  13650. }
  13651. #endif
  13652. #if 0
  13653. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13654. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13655. ASSERT_TRUE(cli != nullptr);
  13656. cli->set_address_family(AF_INET6);
  13657. cli->set_interface("en0");
  13658. auto res = cli->Get("/get");
  13659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13660. ASSERT_EQ(StatusCode::OK_200, res->status);
  13661. }
  13662. #endif
  13663. // Client certificate tests - work with all TLS backends
  13664. #ifdef CPPHTTPLIB_SSL_ENABLED
  13665. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13666. void ClientCertPresent(
  13667. const std::string &client_cert_file,
  13668. const std::string &client_private_key_file,
  13669. const std::string &client_encrypted_private_key_pass = std::string(),
  13670. const ClientCertServerSetup &setup = nullptr) {
  13671. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13672. ASSERT_TRUE(svr.is_valid());
  13673. if (setup) { setup(svr); }
  13674. svr.Get("/test", [&](const Request &req, Response &res) {
  13675. res.set_content("test", "text/plain");
  13676. auto cert = req.peer_cert();
  13677. ASSERT_TRUE(static_cast<bool>(cert));
  13678. std::string common_name = cert.subject_cn();
  13679. EXPECT_EQ("Common Name", common_name);
  13680. });
  13681. auto port = svr.bind_to_any_port(HOST);
  13682. ASSERT_LT(0, port);
  13683. thread t = thread([&]() { svr.listen_after_bind(); });
  13684. auto se = detail::scope_exit([&] {
  13685. svr.stop();
  13686. t.join();
  13687. ASSERT_FALSE(svr.is_running());
  13688. });
  13689. svr.wait_until_ready();
  13690. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13691. client_encrypted_private_key_pass);
  13692. cli.enable_server_certificate_verification(false);
  13693. cli.set_connection_timeout(30);
  13694. auto res = cli.Get("/test");
  13695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13696. ASSERT_EQ(StatusCode::OK_200, res->status);
  13697. }
  13698. TEST(SSLClientServerTest, ClientCertPresent) {
  13699. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13700. }
  13701. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13702. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13703. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13704. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13705. }
  13706. // Expects svr, which must require client certificates, to reject a client
  13707. // that has none
  13708. void RejectsClientWithoutCert(SSLServer &svr) {
  13709. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13710. auto port = svr.bind_to_any_port(HOST);
  13711. ASSERT_LT(0, port);
  13712. thread t = thread([&]() { svr.listen_after_bind(); });
  13713. auto se = detail::scope_exit([&] {
  13714. svr.stop();
  13715. t.join();
  13716. ASSERT_FALSE(svr.is_running());
  13717. });
  13718. svr.wait_until_ready();
  13719. SSLClient cli(HOST, port);
  13720. cli.set_connection_timeout(30);
  13721. // Skip the server certificate check, so that the request fails because the
  13722. // client certificate is missing rather than because cert.pem is not trusted
  13723. cli.enable_server_certificate_verification(false);
  13724. auto res = cli.Get("/test");
  13725. ASSERT_FALSE(res);
  13726. // The server rejects the client during the handshake, or on TLS 1.3 right
  13727. // after it, which the client notices on its first write or read
  13728. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13729. res.error() == Error::Write || res.error() == Error::Read)
  13730. << to_string(res.error());
  13731. if (res.error() == Error::SSLConnection) {
  13732. EXPECT_NE(0UL, res.ssl_backend_error());
  13733. }
  13734. // A rejection noticed on the write keeps the TLS error the write hit
  13735. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13736. }
  13737. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13739. ASSERT_TRUE(svr.is_valid());
  13740. if (setup) { setup(svr); }
  13741. RejectsClientWithoutCert(svr);
  13742. }
  13743. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13744. // A server that requires client certificates must keep requiring them after
  13745. // setup changes it, and keep accepting a client that has one
  13746. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13747. ClientCertMissing(setup);
  13748. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13749. setup);
  13750. }
  13751. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13752. ClientCertStillRequired([](SSLServer &svr) {
  13753. ASSERT_TRUE(tls::set_verify_callback(
  13754. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13755. });
  13756. }
  13757. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13758. ClientCertStillRequired([](SSLServer &svr) {
  13759. ASSERT_TRUE(tls::set_verify_callback(
  13760. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13761. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13762. });
  13763. }
  13764. // The client verifies the server certificate during the handshake, so a
  13765. // server that fails the check never gets the client certificate, even when a
  13766. // verifier of the client's own accepts it
  13767. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13768. struct Case {
  13769. const char *trusted_ca;
  13770. const char *host;
  13771. Error error;
  13772. };
  13773. // cert2.pem names localhost: the first client does not trust it, and the
  13774. // second trusts it but asks for another name
  13775. for (const auto &c :
  13776. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13777. Case{SERVER_CERT2_FILE, "example.com",
  13778. Error::SSLServerHostnameVerification}}) {
  13779. for (auto with_verifier : {false, true}) {
  13780. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13781. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13782. CLIENT_CA_CERT_FILE);
  13783. ASSERT_TRUE(svr.is_valid());
  13784. std::atomic<bool> got_client_cert{false};
  13785. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13786. [&](const tls::VerifyContext &) {
  13787. got_client_cert = true;
  13788. return true;
  13789. }));
  13790. auto port = svr.bind_to_any_port("127.0.0.1");
  13791. ASSERT_LT(0, port);
  13792. thread t = thread([&] { svr.listen_after_bind(); });
  13793. svr.wait_until_ready();
  13794. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13795. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13796. cli.set_ca_cert_path(c.trusted_ca);
  13797. if (with_verifier) {
  13798. cli.set_server_certificate_verifier(
  13799. [](const tls::VerifyContext &) { return true; });
  13800. }
  13801. auto res = cli.Get("/");
  13802. EXPECT_FALSE(res);
  13803. EXPECT_EQ(c.error, res.error());
  13804. svr.stop();
  13805. t.join();
  13806. EXPECT_FALSE(got_client_cert);
  13807. }
  13808. }
  13809. }
  13810. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13811. std::string cert_pem, key_pem, ca_pem;
  13812. read_file(SERVER_CERT_FILE, cert_pem);
  13813. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13814. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13815. ASSERT_TRUE(
  13816. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13817. }
  13818. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13820. ASSERT_TRUE(svr.is_valid());
  13821. UpdateCertsPemWithClientCA(svr);
  13822. RejectsClientWithoutCert(svr);
  13823. }
  13824. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13825. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13826. }
  13827. // A TLS error from one request must not show up in a later request's Result
  13828. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13830. ASSERT_TRUE(svr.is_valid());
  13831. svr.Get("/test", [](const Request &, Response &res) {
  13832. res.set_content("test", "text/plain");
  13833. });
  13834. auto port = svr.bind_to_any_port(HOST);
  13835. ASSERT_LT(0, port);
  13836. thread t = thread([&]() { svr.listen_after_bind(); });
  13837. auto se = detail::scope_exit([&] {
  13838. svr.stop();
  13839. t.join();
  13840. ASSERT_FALSE(svr.is_running());
  13841. });
  13842. svr.wait_until_ready();
  13843. SSLClient cli(HOST, port);
  13844. cli.set_connection_timeout(30);
  13845. cli.enable_server_hostname_verification(false);
  13846. // cert.pem is not trusted, so the handshake fails
  13847. ASSERT_FALSE(cli.Get("/test"));
  13848. cli.enable_server_certificate_verification(false);
  13849. auto res = cli.Get("/test");
  13850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13851. EXPECT_EQ(0, res.ssl_error());
  13852. EXPECT_EQ(0UL, res.ssl_backend_error());
  13853. }
  13854. // PEM memory-based constructor tests (works with all TLS backends).
  13855. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13856. // terminator after it.
  13857. void PemMemoryClientCertPresent(
  13858. const std::string &client_cert_file,
  13859. const std::string &client_private_key_file,
  13860. const std::string &client_encrypted_private_key_pass = std::string(),
  13861. bool exact_size = false) {
  13862. // Read PEM files into memory
  13863. std::string server_cert_pem, server_key_pem;
  13864. std::string client_ca_pem;
  13865. std::string client_cert_pem, client_key_pem;
  13866. read_file(SERVER_CERT_FILE, server_cert_pem);
  13867. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13868. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13869. read_file(client_cert_file, client_cert_pem);
  13870. read_file(client_private_key_file, client_key_pem);
  13871. std::list<std::vector<char>> exact_copies;
  13872. auto data = [&](const std::string &pem) -> const char * {
  13873. if (!exact_size) { return pem.c_str(); }
  13874. exact_copies.emplace_back(pem.begin(), pem.end());
  13875. return exact_copies.back().data();
  13876. };
  13877. // Create server with PEM memory
  13878. SSLServer::PemMemory server_pem = {
  13879. data(server_cert_pem),
  13880. server_cert_pem.size(),
  13881. data(server_key_pem),
  13882. server_key_pem.size(),
  13883. data(client_ca_pem),
  13884. client_ca_pem.size(),
  13885. nullptr // no password for server key
  13886. };
  13887. SSLServer svr(server_pem);
  13888. ASSERT_TRUE(svr.is_valid());
  13889. svr.Get("/test", [&](const Request &req, Response &res) {
  13890. res.set_content("test", "text/plain");
  13891. auto cert = req.peer_cert();
  13892. ASSERT_TRUE(static_cast<bool>(cert));
  13893. EXPECT_EQ("Common Name", cert.subject_cn());
  13894. });
  13895. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13896. auto se = detail::scope_exit([&] {
  13897. svr.stop();
  13898. t.join();
  13899. ASSERT_FALSE(svr.is_running());
  13900. });
  13901. svr.wait_until_ready();
  13902. // Create client with PEM memory
  13903. const char *password = client_encrypted_private_key_pass.empty()
  13904. ? nullptr
  13905. : client_encrypted_private_key_pass.c_str();
  13906. SSLClient::PemMemory client_pem = {
  13907. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13908. client_key_pem.size(), password};
  13909. SSLClient cli(HOST, PORT, client_pem);
  13910. cli.enable_server_certificate_verification(false);
  13911. cli.set_connection_timeout(30);
  13912. auto res = cli.Get("/test");
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. ASSERT_EQ(StatusCode::OK_200, res->status);
  13915. }
  13916. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13917. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13918. }
  13919. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13920. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13921. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13922. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13923. }
  13924. // A server built from PEM memory with a client CA requires client certificates,
  13925. // also when the CA is a NUL-terminated string passed with a length of 0
  13926. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13927. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13928. read_file(SERVER_CERT_FILE, server_cert_pem);
  13929. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13930. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13931. SSLServer::PemMemory server_pem = {
  13932. server_cert_pem.c_str(),
  13933. server_cert_pem.size(),
  13934. server_key_pem.c_str(),
  13935. server_key_pem.size(),
  13936. client_ca_pem.c_str(),
  13937. client_ca_pem.size(),
  13938. nullptr // no password for server key
  13939. };
  13940. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13941. SCOPED_TRACE(client_ca_pem_len);
  13942. server_pem.client_ca_pem_len = client_ca_pem_len;
  13943. SSLServer svr(server_pem);
  13944. ASSERT_TRUE(svr.is_valid());
  13945. RejectsClientWithoutCert(svr);
  13946. }
  13947. // An empty CA fails to load instead of turning the check off
  13948. server_pem.client_ca_pem = "";
  13949. server_pem.client_ca_pem_len = 0;
  13950. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13951. }
  13952. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13953. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13954. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13955. true);
  13956. }
  13957. // A length shorter than the PEM cuts it short, so it no longer loads
  13958. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13959. std::string cert, key;
  13960. read_file(SERVER_CERT_FILE, cert);
  13961. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13962. for (auto cut_cert : {true, false}) {
  13963. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13964. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13965. SSLServer::PemMemory server_pem = {
  13966. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13967. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13968. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13969. key_len, nullptr};
  13970. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13971. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13972. key.c_str(), key_len, nullptr};
  13973. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13974. }
  13975. }
  13976. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13977. class NoListenSSLServer : public SSLServer {
  13978. public:
  13979. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13980. const char *client_ca_cert_file_path,
  13981. const char *client_ca_cert_dir_path = nullptr)
  13982. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13983. client_ca_cert_dir_path),
  13984. stop_(false) {}
  13985. std::atomic_bool stop_;
  13986. private:
  13987. bool process_and_close_socket(socket_t /*sock*/) override {
  13988. // Don't create SSL context
  13989. while (!stop_.load()) {
  13990. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13991. }
  13992. return true;
  13993. }
  13994. };
  13995. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13996. CLIENT_CA_CERT_FILE);
  13997. ASSERT_TRUE(svr.is_valid());
  13998. svr.Get("/test", [&](const Request &, Response &res) {
  13999. res.set_content("test", "text/plain");
  14000. });
  14001. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14002. auto se = detail::scope_exit([&] {
  14003. svr.stop_ = true;
  14004. svr.stop();
  14005. t.join();
  14006. ASSERT_FALSE(svr.is_running());
  14007. });
  14008. svr.wait_until_ready();
  14009. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14010. cli.enable_server_certificate_verification(false);
  14011. cli.set_connection_timeout(1);
  14012. auto res = cli.Get("/test");
  14013. ASSERT_TRUE(!res);
  14014. EXPECT_EQ(Error::SSLConnection, res.error());
  14015. // Timeout results in WantRead error code (maps to backend-specific value)
  14016. EXPECT_NE(0, res.ssl_error());
  14017. }
  14018. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14019. // Test SSLServer with client certificate verification using the standard
  14020. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14021. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14022. CLIENT_CA_CERT_DIR);
  14023. ASSERT_TRUE(svr.is_valid());
  14024. svr.Get("/test", [&](const Request &req, Response &res) {
  14025. res.set_content("test", "text/plain");
  14026. auto cert = req.peer_cert();
  14027. ASSERT_TRUE(static_cast<bool>(cert));
  14028. auto common_name = cert.subject_cn();
  14029. EXPECT_EQ("Common Name", common_name);
  14030. });
  14031. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14032. auto se = detail::scope_exit([&] {
  14033. svr.stop();
  14034. t.join();
  14035. ASSERT_FALSE(svr.is_running());
  14036. });
  14037. svr.wait_until_ready();
  14038. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14039. cli.enable_server_certificate_verification(false);
  14040. cli.set_connection_timeout(30);
  14041. auto res = cli.Get("/test");
  14042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14043. ASSERT_EQ(StatusCode::OK_200, res->status);
  14044. }
  14045. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14046. // Verifies that wildcard matching and exact matching work consistently
  14047. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14048. using namespace httplib::tls;
  14049. // We need a running server to test against
  14050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14051. ASSERT_TRUE(svr.is_valid());
  14052. svr.Get("/test", [](const Request &, Response &res) {
  14053. res.set_content("ok", "text/plain");
  14054. });
  14055. thread t([&]() { svr.listen(HOST, PORT); });
  14056. auto se = detail::scope_exit([&] {
  14057. svr.stop();
  14058. t.join();
  14059. });
  14060. svr.wait_until_ready();
  14061. bool verify_callback_called = false;
  14062. bool verify_result_wrong = false;
  14063. SSLClient cli(HOST, PORT);
  14064. cli.enable_server_certificate_verification(true);
  14065. cli.set_ca_cert_path(CA_CERT_FILE);
  14066. cli.set_connection_timeout(5);
  14067. // Note: Test certificate has CN="Common Name", not "localhost"
  14068. bool verify_result_cn = false;
  14069. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14070. verify_callback_called = true;
  14071. if (!ctx.cert) return false;
  14072. // Test 1: "Common Name" should match (our test server cert CN)
  14073. verify_result_cn = ctx.check_hostname("Common Name");
  14074. // Test 2: wrong hostname should not match
  14075. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14076. return true; // Accept for the purpose of this test
  14077. });
  14078. auto res = cli.Get("/test");
  14079. // The request may succeed or fail depending on cert configuration
  14080. // but the callback should have been called
  14081. ASSERT_TRUE(verify_callback_called)
  14082. << "Verify callback should have been called";
  14083. // CN="Common Name" should match our test certificate
  14084. //
  14085. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14086. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14087. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14088. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14089. // <openssl/base.h>, which is included transitively when
  14090. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14091. #if defined(OPENSSL_IS_BORINGSSL)
  14092. EXPECT_FALSE(verify_result_cn)
  14093. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14094. #else
  14095. EXPECT_TRUE(verify_result_cn)
  14096. << "verify_hostname should match 'Common Name' (certificate CN)";
  14097. #endif
  14098. // Wrong hostname should not match
  14099. EXPECT_FALSE(verify_result_wrong)
  14100. << "verify_hostname should not match 'wronghost.example.com'";
  14101. }
  14102. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14103. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14104. // X509_check_ip behavior and must hold for every backend.
  14105. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14106. using namespace httplib::tls;
  14107. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14108. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14109. ASSERT_TRUE(svr.is_valid());
  14110. svr.Get("/test", [](const Request &, Response &res) {
  14111. res.set_content("ok", "text/plain");
  14112. });
  14113. thread t([&]() { svr.listen(HOST, PORT); });
  14114. auto se = detail::scope_exit([&] {
  14115. svr.stop();
  14116. t.join();
  14117. });
  14118. svr.wait_until_ready();
  14119. bool verify_callback_called = false;
  14120. bool ip_matched_via_cn = true;
  14121. SSLClient cli(HOST, PORT);
  14122. cli.enable_server_certificate_verification(true);
  14123. cli.set_ca_cert_path(CA_CERT_FILE);
  14124. cli.set_connection_timeout(5);
  14125. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14126. verify_callback_called = true;
  14127. if (!ctx.cert) return false;
  14128. // The IP appears only in the CN, so it must NOT be accepted.
  14129. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14130. return true; // Accept for the purpose of this test
  14131. });
  14132. cli.Get("/test");
  14133. ASSERT_TRUE(verify_callback_called)
  14134. << "Verify callback should have been called";
  14135. EXPECT_FALSE(ip_matched_via_cn)
  14136. << "An IP host must not be authenticated via the certificate CN";
  14137. }
  14138. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14139. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14140. using namespace httplib::tls;
  14141. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14142. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14143. ASSERT_TRUE(svr.is_valid());
  14144. svr.Get("/test", [](const Request &, Response &res) {
  14145. res.set_content("ok", "text/plain");
  14146. });
  14147. thread t([&]() { svr.listen(HOST, PORT); });
  14148. auto se = detail::scope_exit([&] {
  14149. svr.stop();
  14150. t.join();
  14151. });
  14152. svr.wait_until_ready();
  14153. bool verify_callback_called = false;
  14154. bool san_matched = false;
  14155. bool wrong_ipv6_matched = true;
  14156. bool cn_ipv6_matched = true;
  14157. SSLClient cli(HOST, PORT);
  14158. cli.enable_server_certificate_verification(true);
  14159. cli.set_ca_cert_path(CA_CERT_FILE);
  14160. cli.set_connection_timeout(5);
  14161. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14162. verify_callback_called = true;
  14163. if (!ctx.cert) return false;
  14164. // Matches the IPv6 iPAddress SAN.
  14165. san_matched = ctx.check_hostname("2001:db8::1");
  14166. // A different IPv6 address must not match.
  14167. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14168. // "::1" lives only in the CN, so it must not be accepted.
  14169. cn_ipv6_matched = ctx.check_hostname("::1");
  14170. return true; // Accept for the purpose of this test
  14171. });
  14172. cli.Get("/test");
  14173. ASSERT_TRUE(verify_callback_called)
  14174. << "Verify callback should have been called";
  14175. EXPECT_TRUE(san_matched)
  14176. << "verify_hostname should match an IPv6 iPAddress SAN";
  14177. EXPECT_FALSE(wrong_ipv6_matched)
  14178. << "verify_hostname should not match a non-matching IPv6 address";
  14179. EXPECT_FALSE(cn_ipv6_matched)
  14180. << "An IPv6 host must not be authenticated via the certificate CN";
  14181. }
  14182. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14183. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14184. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14185. using namespace httplib::tls;
  14186. // SANs: DNS:a.zz, IP:42.46.122.122
  14187. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14188. ASSERT_TRUE(svr.is_valid());
  14189. svr.Get("/test", [](const Request &, Response &res) {
  14190. res.set_content("ok", "text/plain");
  14191. });
  14192. auto port = svr.bind_to_any_port(HOST);
  14193. thread t([&]() { svr.listen_after_bind(); });
  14194. auto se = detail::scope_exit([&] {
  14195. svr.stop();
  14196. t.join();
  14197. });
  14198. svr.wait_until_ready();
  14199. bool verify_callback_called = false;
  14200. bool dns_san_matched = false;
  14201. bool ip_san_matched = false;
  14202. bool ip_matched_via_dns_san = true;
  14203. bool dns_matched_via_ip_san = true;
  14204. bool cn_matched_next_to_dns_san = true;
  14205. SSLClient cli(HOST, port);
  14206. cli.enable_server_certificate_verification(true);
  14207. cli.set_ca_cert_path(CA_CERT_FILE);
  14208. cli.set_connection_timeout(5);
  14209. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14210. verify_callback_called = true;
  14211. if (!ctx.cert) return false;
  14212. dns_san_matched = ctx.check_hostname("a.zz");
  14213. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14214. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14215. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14216. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14217. return true; // Accept for the purpose of this test
  14218. });
  14219. cli.Get("/test");
  14220. ASSERT_TRUE(verify_callback_called)
  14221. << "Verify callback should have been called";
  14222. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14223. EXPECT_TRUE(ip_san_matched)
  14224. << "verify_hostname should match an iPAddress SAN";
  14225. EXPECT_FALSE(ip_matched_via_dns_san)
  14226. << "An IP host must not be authenticated via a dNSName SAN";
  14227. EXPECT_FALSE(dns_matched_via_ip_san)
  14228. << "A DNS host must not be authenticated via an iPAddress SAN";
  14229. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14230. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14231. }
  14232. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14233. // "www.*.example.test" names one host and not every host under example.test.
  14234. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14235. using namespace httplib::tls;
  14236. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14237. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14238. ASSERT_TRUE(svr.is_valid());
  14239. svr.Get("/test", [](const Request &, Response &res) {
  14240. res.set_content("ok", "text/plain");
  14241. });
  14242. auto port = svr.bind_to_any_port(HOST);
  14243. thread t([&]() { svr.listen_after_bind(); });
  14244. auto se = detail::scope_exit([&] {
  14245. svr.stop();
  14246. t.join();
  14247. });
  14248. svr.wait_until_ready();
  14249. bool verify_callback_called = false;
  14250. bool leftmost_wildcard_matched = false;
  14251. bool wildcard_spanned_labels = true;
  14252. bool inner_wildcard_matched = true;
  14253. SSLClient cli(HOST, port);
  14254. cli.enable_server_certificate_verification(true);
  14255. cli.set_ca_cert_path(CA_CERT_FILE);
  14256. cli.set_connection_timeout(5);
  14257. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14258. verify_callback_called = true;
  14259. if (!ctx.cert) return false;
  14260. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14261. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14262. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14263. return true; // Accept for the purpose of this test
  14264. });
  14265. cli.Get("/test");
  14266. ASSERT_TRUE(verify_callback_called)
  14267. << "Verify callback should have been called";
  14268. EXPECT_TRUE(leftmost_wildcard_matched)
  14269. << "A leftmost wildcard should match a single label";
  14270. EXPECT_FALSE(wildcard_spanned_labels)
  14271. << "A wildcard label must not match more than one label";
  14272. EXPECT_FALSE(inner_wildcard_matched)
  14273. << "A wildcard outside the leftmost label must not be honoured";
  14274. }
  14275. // sans() must report each SAN entry under its own type.
  14276. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14277. using namespace httplib::tls;
  14278. // SANs: DNS:a.zz, IP:42.46.122.122
  14279. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14280. ASSERT_TRUE(svr.is_valid());
  14281. svr.Get("/test", [](const Request &, Response &res) {
  14282. res.set_content("ok", "text/plain");
  14283. });
  14284. auto port = svr.bind_to_any_port(HOST);
  14285. thread t([&]() { svr.listen_after_bind(); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. });
  14290. svr.wait_until_ready();
  14291. bool verify_callback_called = false;
  14292. std::vector<SanEntry> sans;
  14293. SSLClient cli(HOST, port);
  14294. cli.enable_server_certificate_verification(true);
  14295. cli.set_ca_cert_path(CA_CERT_FILE);
  14296. cli.set_connection_timeout(5);
  14297. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14298. verify_callback_called = true;
  14299. if (!ctx.cert) return false;
  14300. sans = ctx.sans();
  14301. return true; // Accept for the purpose of this test
  14302. });
  14303. cli.Get("/test");
  14304. ASSERT_TRUE(verify_callback_called)
  14305. << "Verify callback should have been called";
  14306. auto has_san = [&](SanType type, const std::string &value) {
  14307. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14308. return san.type == type && san.value == value;
  14309. });
  14310. };
  14311. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14312. << "sans() should report the dNSName SAN";
  14313. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14314. << "sans() should report the iPAddress SAN";
  14315. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14316. << "sans() must not report the dNSName SAN as an address";
  14317. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14318. << "sans() must not report the iPAddress SAN as a DNS name";
  14319. }
  14320. #endif
  14321. // mbedTLS-specific callback constructor test
  14322. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14323. #ifdef CPPHTTPLIB_SSL_ENABLED
  14324. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14326. ASSERT_TRUE(svr.is_valid());
  14327. // Set up a handler to verify client certificate is present
  14328. bool client_cert_verified = false;
  14329. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14330. // Verify that client certificate was provided
  14331. client_cert_verified = true;
  14332. res.set_content("success", "text/plain");
  14333. });
  14334. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14335. auto se = detail::scope_exit([&] {
  14336. svr.stop();
  14337. t.join();
  14338. ASSERT_FALSE(svr.is_running());
  14339. });
  14340. svr.wait_until_ready();
  14341. // Client with certificate
  14342. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14343. cli.enable_server_certificate_verification(false);
  14344. cli.set_connection_timeout(30);
  14345. auto res = cli.Get("/test");
  14346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14347. ASSERT_EQ(StatusCode::OK_200, res->status);
  14348. ASSERT_TRUE(client_cert_verified);
  14349. EXPECT_EQ("success", res->body);
  14350. }
  14351. #endif
  14352. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14353. // backends
  14354. #ifdef CPPHTTPLIB_SSL_ENABLED
  14355. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14356. using namespace httplib::tls;
  14357. // Test that when client CA cert file is provided,
  14358. // the server properly requests and validates client certificates
  14359. // Create a server with client authentication
  14360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14361. ASSERT_TRUE(svr.is_valid());
  14362. bool handler_called = false;
  14363. svr.Get("/test", [&](const Request &req, Response &res) {
  14364. handler_called = true;
  14365. // Verify that a client certificate was provided
  14366. auto cert = req.peer_cert();
  14367. ASSERT_TRUE(static_cast<bool>(cert));
  14368. // Get the issuer name
  14369. std::string issuer_str = cert.issuer_name();
  14370. ASSERT_FALSE(issuer_str.empty());
  14371. // The client certificate should be issued by our test CA
  14372. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14373. res.set_content("authenticated", "text/plain");
  14374. });
  14375. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14376. auto se = detail::scope_exit([&] {
  14377. svr.stop();
  14378. t.join();
  14379. ASSERT_FALSE(svr.is_running());
  14380. });
  14381. svr.wait_until_ready();
  14382. // Connect with a client certificate issued by the CA
  14383. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14384. cli.enable_server_certificate_verification(false);
  14385. cli.set_connection_timeout(30);
  14386. auto res = cli.Get("/test");
  14387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14388. ASSERT_EQ(StatusCode::OK_200, res->status);
  14389. ASSERT_TRUE(handler_called);
  14390. EXPECT_EQ("authenticated", res->body);
  14391. }
  14392. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14393. using namespace httplib::tls;
  14394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14395. ASSERT_TRUE(svr.is_valid());
  14396. svr.Get("/test", [](const Request &, Response &res) {
  14397. res.set_content("ok", "text/plain");
  14398. });
  14399. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14400. auto se = detail::scope_exit([&] {
  14401. svr.stop();
  14402. t.join();
  14403. });
  14404. svr.wait_until_ready();
  14405. SSLClient cli(HOST, PORT);
  14406. cli.enable_server_certificate_verification(false);
  14407. cli.set_connection_timeout(30);
  14408. bool cert_checked = false;
  14409. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14410. if (ctx.cert) {
  14411. auto sans = ctx.sans();
  14412. // Test certificate may or may not have SANs - just verify the API
  14413. // works If SANs exist, verify the types are valid
  14414. for (const auto &san : sans) {
  14415. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14416. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14417. san.type == SanType::OTHER);
  14418. EXPECT_FALSE(san.value.empty());
  14419. }
  14420. cert_checked = true;
  14421. }
  14422. return true;
  14423. });
  14424. auto res = cli.Get("/test");
  14425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14426. EXPECT_TRUE(cert_checked);
  14427. }
  14428. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14429. using namespace httplib::tls;
  14430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14431. ASSERT_TRUE(svr.is_valid());
  14432. svr.Get("/test", [](const Request &, Response &res) {
  14433. res.set_content("ok", "text/plain");
  14434. });
  14435. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14436. auto se = detail::scope_exit([&] {
  14437. svr.stop();
  14438. t.join();
  14439. });
  14440. svr.wait_until_ready();
  14441. SSLClient cli(HOST, PORT);
  14442. cli.enable_server_certificate_verification(false);
  14443. cli.set_connection_timeout(30);
  14444. bool validity_checked = false;
  14445. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14446. if (ctx.cert) {
  14447. time_t not_before = 0, not_after = 0;
  14448. bool result = ctx.validity(not_before, not_after);
  14449. EXPECT_TRUE(result);
  14450. // Verify that not_before < now < not_after for a valid cert
  14451. time_t now = time(nullptr);
  14452. EXPECT_LT(not_before, now);
  14453. EXPECT_GT(not_after, now);
  14454. validity_checked = true;
  14455. }
  14456. return true;
  14457. });
  14458. auto res = cli.Get("/test");
  14459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14460. EXPECT_TRUE(validity_checked);
  14461. }
  14462. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14463. using namespace httplib::tls;
  14464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14465. ASSERT_TRUE(svr.is_valid());
  14466. svr.Get("/test", [](const Request &, Response &res) {
  14467. res.set_content("ok", "text/plain");
  14468. });
  14469. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14470. auto se = detail::scope_exit([&] {
  14471. svr.stop();
  14472. t.join();
  14473. });
  14474. svr.wait_until_ready();
  14475. SSLClient cli(HOST, PORT);
  14476. cli.enable_server_certificate_verification(false);
  14477. cli.set_connection_timeout(30);
  14478. bool serial_checked = false;
  14479. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14480. if (ctx.cert) {
  14481. std::string serial = ctx.serial();
  14482. EXPECT_FALSE(serial.empty());
  14483. // Serial should be a hex string
  14484. for (char c : serial) {
  14485. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14486. (c >= 'a' && c <= 'f'));
  14487. }
  14488. serial_checked = true;
  14489. }
  14490. return true;
  14491. });
  14492. auto res = cli.Get("/test");
  14493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14494. EXPECT_TRUE(serial_checked);
  14495. }
  14496. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14497. // Test 1: Valid CA file - no error should be recorded
  14498. {
  14499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14500. CLIENT_CA_CERT_FILE);
  14501. ASSERT_TRUE(svr.is_valid());
  14502. // With valid setup, last_ssl_error should be 0
  14503. EXPECT_EQ(0, svr.ssl_last_error());
  14504. }
  14505. // Test 2: Invalid CA file content
  14506. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14507. {
  14508. // Create a temporary file with completely invalid content
  14509. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14510. {
  14511. std::ofstream ofs(temp_invalid_ca);
  14512. ofs << "This is not a certificate file at all\n";
  14513. ofs << "Just plain text content\n";
  14514. }
  14515. // Create server with invalid CA file
  14516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14517. // Clean up temporary file
  14518. std::remove(temp_invalid_ca);
  14519. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14520. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14521. // Note: SSL_CTX_load_verify_locations typically fails first,
  14522. // but our error handling code path is still exercised
  14523. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14524. }
  14525. }
  14526. TEST(VerifyCallbackTest, VerifyContextFields) {
  14527. using namespace httplib::tls;
  14528. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14529. ASSERT_TRUE(svr.is_valid());
  14530. svr.Get("/test", [](const Request &, Response &res) {
  14531. res.set_content("ok", "text/plain");
  14532. });
  14533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14534. auto se = detail::scope_exit([&] {
  14535. svr.stop();
  14536. t.join();
  14537. });
  14538. svr.wait_until_ready();
  14539. SSLClient cli(HOST, PORT);
  14540. cli.enable_server_certificate_verification(false);
  14541. cli.set_connection_timeout(30);
  14542. int callback_count = 0;
  14543. bool saw_leaf_cert = false;
  14544. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14545. if (ctx.cert) {
  14546. callback_count++;
  14547. // We should see at least one certificate (the leaf)
  14548. std::string cn = ctx.subject_cn();
  14549. if (!cn.empty()) { saw_leaf_cert = true; }
  14550. // Verify context fields are populated
  14551. EXPECT_NE(ctx.session, nullptr);
  14552. EXPECT_GE(ctx.depth, 0);
  14553. }
  14554. return true;
  14555. });
  14556. auto res = cli.Get("/test");
  14557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14558. EXPECT_GT(callback_count, 0);
  14559. EXPECT_TRUE(saw_leaf_cert);
  14560. }
  14561. // A verifier that accepts runs alongside the built-in verification, and is the
  14562. // only check once that is turned off.
  14563. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14564. using namespace httplib::tls;
  14565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14566. ASSERT_TRUE(svr.is_valid());
  14567. svr.Get("/test", [](const Request &, Response &res) {
  14568. res.set_content("ok", "text/plain");
  14569. });
  14570. auto port = svr.bind_to_any_port(HOST);
  14571. thread t([&]() { svr.listen_after_bind(); });
  14572. auto se = detail::scope_exit([&] {
  14573. svr.stop();
  14574. t.join();
  14575. });
  14576. svr.wait_until_ready();
  14577. SSLClient cli(HOST, port);
  14578. cli.enable_server_hostname_verification(false);
  14579. auto calls = 0;
  14580. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14581. calls++;
  14582. return true;
  14583. });
  14584. // cert.pem is not trusted
  14585. auto res = cli.Get("/test");
  14586. ASSERT_FALSE(res);
  14587. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14588. EXPECT_GT(calls, 0);
  14589. cli.enable_server_certificate_verification(false);
  14590. res = cli.Get("/test");
  14591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14592. EXPECT_EQ("ok", res->body);
  14593. }
  14594. // A verifier belongs to the client that set it, not to the thread that set it.
  14595. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14596. using namespace httplib::tls;
  14597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14598. ASSERT_TRUE(svr.is_valid());
  14599. svr.Get("/test", [](const Request &, Response &res) {
  14600. res.set_content("ok", "text/plain");
  14601. });
  14602. auto port = svr.bind_to_any_port(HOST);
  14603. thread t([&]() { svr.listen_after_bind(); });
  14604. auto se = detail::scope_exit([&] {
  14605. svr.stop();
  14606. t.join();
  14607. });
  14608. svr.wait_until_ready();
  14609. auto rejecting_calls = 0;
  14610. SSLClient rejecting(HOST, port);
  14611. rejecting.enable_server_certificate_verification(false);
  14612. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14613. rejecting_calls++;
  14614. return false;
  14615. });
  14616. auto accepting_calls = 0;
  14617. SSLClient accepting(HOST, port);
  14618. accepting.enable_server_certificate_verification(false);
  14619. // Set on another thread than the requests below.
  14620. thread([&]() {
  14621. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14622. accepting_calls++;
  14623. return true;
  14624. });
  14625. }).join();
  14626. // Requested on another thread than the verifier was set on.
  14627. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14628. EXPECT_GT(rejecting_calls, 0);
  14629. auto res = accepting.Get("/test");
  14630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14631. EXPECT_GT(accepting_calls, 0);
  14632. }
  14633. // A verifier replaced while a handshake runs it lives until it returns.
  14634. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14635. using namespace httplib::tls;
  14636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14637. ASSERT_TRUE(svr.is_valid());
  14638. svr.Get("/test", [](const Request &, Response &res) {
  14639. res.set_content("ok", "text/plain");
  14640. });
  14641. auto port = svr.bind_to_any_port(HOST);
  14642. thread t([&]() { svr.listen_after_bind(); });
  14643. auto se = detail::scope_exit([&] {
  14644. svr.stop();
  14645. t.join();
  14646. });
  14647. svr.wait_until_ready();
  14648. SSLClient cli(HOST, port);
  14649. cli.enable_server_certificate_verification(false);
  14650. std::promise<void> entered;
  14651. std::promise<void> replaced;
  14652. auto replaced_future = replaced.get_future();
  14653. auto first_call = true;
  14654. // Long enough to live on the heap
  14655. std::string expected(64, 'v');
  14656. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14657. if (first_call) {
  14658. first_call = false;
  14659. entered.set_value();
  14660. replaced_future.wait();
  14661. }
  14662. return expected == std::string(64, 'v');
  14663. });
  14664. thread request([&]() {
  14665. auto res = cli.Get("/test");
  14666. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14667. });
  14668. entered.get_future().wait();
  14669. cli.set_server_certificate_verifier(
  14670. [](const VerifyContext &) { return true; });
  14671. replaced.set_value();
  14672. request.join();
  14673. }
  14674. // VerifyContext::session is the same handle the other tls:: functions take.
  14675. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14676. using namespace httplib::tls;
  14677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14678. ASSERT_TRUE(svr.is_valid());
  14679. svr.Get("/test", [](const Request &, Response &res) {
  14680. res.set_content("ok", "text/plain");
  14681. });
  14682. auto port = svr.bind_to_any_port(HOST);
  14683. thread t([&]() { svr.listen_after_bind(); });
  14684. auto se = detail::scope_exit([&] {
  14685. svr.stop();
  14686. t.join();
  14687. });
  14688. svr.wait_until_ready();
  14689. SSLClient cli(HOST, port);
  14690. cli.enable_server_certificate_verification(false);
  14691. session_t verifier_session = nullptr;
  14692. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14693. verifier_session = ctx.session;
  14694. return true;
  14695. });
  14696. session_t session_verifier_session = nullptr;
  14697. cli.set_session_verifier([&](session_t session) {
  14698. session_verifier_session = session;
  14699. return SSLVerifierResponse::NoDecisionMade;
  14700. });
  14701. auto res = cli.Get("/test");
  14702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14703. EXPECT_NE(nullptr, verifier_session);
  14704. EXPECT_EQ(session_verifier_session, verifier_session);
  14705. }
  14706. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14707. using httplib::tls::TlsError;
  14708. // Test that verify_error_to_string returns empty for success
  14709. std::string success_str = TlsError::verify_error_to_string(0);
  14710. EXPECT_TRUE(success_str.empty());
  14711. // Test that verify_error_to_string returns non-empty for error codes
  14712. // Using a common error code (certificate expired)
  14713. std::string error_str =
  14714. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14715. EXPECT_FALSE(error_str.empty());
  14716. }
  14717. TEST(SessionVerifierTest, CertificateAccepted) {
  14718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14719. ASSERT_TRUE(svr.is_valid());
  14720. svr.Get("/test", [](const Request &, Response &res) {
  14721. res.set_content("ok", "text/plain");
  14722. });
  14723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14724. auto se = detail::scope_exit([&] {
  14725. svr.stop();
  14726. t.join();
  14727. });
  14728. svr.wait_until_ready();
  14729. SSLClient cli(HOST, PORT);
  14730. cli.enable_server_certificate_verification(false);
  14731. cli.set_connection_timeout(30);
  14732. bool callback_called = false;
  14733. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14734. EXPECT_NE(session, nullptr);
  14735. callback_called = true;
  14736. return SSLVerifierResponse::CertificateAccepted;
  14737. });
  14738. auto res = cli.Get("/test");
  14739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14740. EXPECT_EQ(200, res->status);
  14741. EXPECT_TRUE(callback_called);
  14742. }
  14743. TEST(SessionVerifierTest, CertificateRejected) {
  14744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14745. ASSERT_TRUE(svr.is_valid());
  14746. svr.Get("/test", [](const Request &, Response &res) {
  14747. res.set_content("ok", "text/plain");
  14748. });
  14749. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14750. auto se = detail::scope_exit([&] {
  14751. svr.stop();
  14752. t.join();
  14753. });
  14754. svr.wait_until_ready();
  14755. SSLClient cli(HOST, PORT);
  14756. cli.enable_server_certificate_verification(false);
  14757. cli.set_connection_timeout(30);
  14758. bool callback_called = false;
  14759. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14760. EXPECT_NE(session, nullptr);
  14761. callback_called = true;
  14762. return SSLVerifierResponse::CertificateRejected;
  14763. });
  14764. auto res = cli.Get("/test");
  14765. EXPECT_FALSE(res);
  14766. EXPECT_TRUE(callback_called);
  14767. }
  14768. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14770. ASSERT_TRUE(svr.is_valid());
  14771. svr.Get("/test", [](const Request &, Response &res) {
  14772. res.set_content("ok", "text/plain");
  14773. });
  14774. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14775. auto se = detail::scope_exit([&] {
  14776. svr.stop();
  14777. t.join();
  14778. });
  14779. svr.wait_until_ready();
  14780. // NoDecisionMade with verification disabled should succeed (no default check)
  14781. SSLClient cli(HOST, PORT);
  14782. cli.enable_server_certificate_verification(false);
  14783. cli.set_connection_timeout(30);
  14784. bool callback_called = false;
  14785. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14786. EXPECT_NE(session, nullptr);
  14787. callback_called = true;
  14788. return SSLVerifierResponse::NoDecisionMade;
  14789. });
  14790. auto res = cli.Get("/test");
  14791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14792. EXPECT_EQ(200, res->status);
  14793. EXPECT_TRUE(callback_called);
  14794. }
  14795. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14797. ASSERT_TRUE(svr.is_valid());
  14798. svr.Get("/test", [](const Request &, Response &res) {
  14799. res.set_content("ok", "text/plain");
  14800. });
  14801. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14802. auto se = detail::scope_exit([&] {
  14803. svr.stop();
  14804. t.join();
  14805. });
  14806. svr.wait_until_ready();
  14807. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14808. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14809. // so we only check that the request fails, not whether the callback was
  14810. // called.
  14811. SSLClient cli(HOST, PORT);
  14812. cli.enable_server_certificate_verification(true);
  14813. cli.set_connection_timeout(30);
  14814. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14815. EXPECT_NE(session, nullptr);
  14816. return SSLVerifierResponse::NoDecisionMade;
  14817. });
  14818. auto res = cli.Get("/test");
  14819. EXPECT_FALSE(res);
  14820. }
  14821. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14822. // Test SSL server using PemMemory constructor with client CA certificates
  14823. // Read PEM files
  14824. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14825. read_file(SERVER_CERT_FILE, server_cert_pem);
  14826. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14827. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14828. // Create SSLServer with PemMemory constructor including client CA
  14829. SSLServer::PemMemory server_pem = {
  14830. server_cert_pem.c_str(),
  14831. server_cert_pem.size(),
  14832. server_key_pem.c_str(),
  14833. server_key_pem.size(),
  14834. client_ca_pem.c_str(),
  14835. client_ca_pem.size(),
  14836. nullptr // no password for server key
  14837. };
  14838. SSLServer svr(server_pem);
  14839. ASSERT_TRUE(svr.is_valid());
  14840. // No SSL error should be recorded for valid setup
  14841. EXPECT_EQ(0, svr.ssl_last_error());
  14842. // Set up server endpoints
  14843. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14844. res.set_content("ok", "text/plain");
  14845. });
  14846. // Start server in a thread
  14847. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14848. svr.wait_until_ready();
  14849. // Connect with client certificate (using constructor with paths)
  14850. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14851. cli.enable_server_certificate_verification(false);
  14852. auto res = cli.Get("/test-pem-ca");
  14853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14854. EXPECT_EQ(200, res->status);
  14855. EXPECT_EQ("ok", res->body);
  14856. svr.stop();
  14857. server_thread.join();
  14858. }
  14859. #endif
  14860. #ifdef _WIN32
  14861. TEST(CleanupTest, WSACleanup) {
  14862. int ret = WSACleanup();
  14863. ASSERT_EQ(0, ret);
  14864. }
  14865. #endif
  14866. #ifndef CPPHTTPLIB_SSL_ENABLED
  14867. TEST(NoSSLSupport, SimpleInterface) {
  14868. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14869. }
  14870. #endif
  14871. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14872. TEST(InvalidScheme, SimpleInterface) {
  14873. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14874. }
  14875. #endif
  14876. TEST(NoScheme, SimpleInterface) {
  14877. Client cli("yahoo.com:80");
  14878. ASSERT_TRUE(cli.is_valid());
  14879. }
  14880. TEST(SendAPI, SimpleInterface_Online) {
  14881. Client cli("http://yahoo.com");
  14882. Request req;
  14883. req.method = "GET";
  14884. req.path = "/";
  14885. auto res = cli.send(req);
  14886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14887. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14888. }
  14889. TEST(SendAPI, WithParamsInRequest) {
  14890. Server svr;
  14891. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14892. EXPECT_TRUE(req.has_param("test"));
  14893. EXPECT_EQ("test_value", req.get_param_value("test"));
  14894. });
  14895. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14896. auto se = detail::scope_exit([&] {
  14897. svr.stop();
  14898. t.join();
  14899. ASSERT_FALSE(svr.is_running());
  14900. });
  14901. svr.wait_until_ready();
  14902. Client cli(HOST, PORT);
  14903. {
  14904. Request req;
  14905. req.method = "GET";
  14906. req.path = "/";
  14907. req.params.emplace("test", "test_value");
  14908. auto res = cli.send(req);
  14909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14910. }
  14911. {
  14912. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14914. }
  14915. }
  14916. TEST(ClientImplMethods, GetSocketTest) {
  14917. httplib::Server svr;
  14918. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14919. res.status = StatusCode::OK_200;
  14920. });
  14921. auto port = svr.bind_to_any_port("127.0.0.1");
  14922. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14923. auto se = detail::scope_exit([&] {
  14924. svr.stop();
  14925. thread.join();
  14926. ASSERT_FALSE(svr.is_running());
  14927. });
  14928. svr.wait_until_ready();
  14929. {
  14930. httplib::Client cli("127.0.0.1", port);
  14931. cli.set_keep_alive(true);
  14932. // Use the behavior of cpp-httplib of opening the connection
  14933. // only when the first request happens. If that changes,
  14934. // this test would be obsolete.
  14935. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14936. // This also implicitly tests the server. But other tests would fail much
  14937. // earlier than this one to be considered.
  14938. auto res = cli.Get("/");
  14939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14940. EXPECT_EQ(StatusCode::OK_200, res->status);
  14941. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14942. }
  14943. }
  14944. #ifdef CPPHTTPLIB_SSL_ENABLED
  14945. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14946. Client cli("http://yahoo.com");
  14947. auto res = cli.Get("/");
  14948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14949. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14950. cli.set_follow_location(true);
  14951. res = cli.Get("/");
  14952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14953. EXPECT_EQ(StatusCode::OK_200, res->status);
  14954. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14955. }
  14956. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14957. Client cli("https://yahoo.com");
  14958. auto res = cli.Get("/");
  14959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14960. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14961. cli.set_follow_location(true);
  14962. res = cli.Get("/");
  14963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14964. EXPECT_EQ(StatusCode::OK_200, res->status);
  14965. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14966. }
  14967. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14968. Client cli("https://yahoo.com");
  14969. auto res = cli.Get("/");
  14970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14971. ASSERT_FALSE(!res);
  14972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14973. ASSERT_FALSE(res == nullptr);
  14974. ASSERT_TRUE(res != nullptr);
  14975. EXPECT_EQ(Error::Success, res.error());
  14976. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14977. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14978. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14979. cli.set_follow_location(true);
  14980. res = cli.Get("/");
  14981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14982. EXPECT_EQ(Error::Success, res.error());
  14983. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14984. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14985. EXPECT_EQ(StatusCode::OK_200, res->status);
  14986. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14987. }
  14988. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14989. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14990. Client cli("https://cdnjs.cloudflare.com");
  14991. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14992. Headers{{"Accept-Encoding", "br"}});
  14993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14994. EXPECT_EQ(StatusCode::OK_200, res->status);
  14995. EXPECT_EQ(287630U, res->body.size());
  14996. EXPECT_EQ("application/javascript; charset=utf-8",
  14997. res->get_header_value("Content-Type"));
  14998. }
  14999. #endif
  15000. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15001. #undef REDIR_HOST // Silence compiler warning
  15002. #define REDIR_HOST "https://httpbingo.org"
  15003. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15004. Client cli(REDIR_HOST);
  15005. cli.set_follow_location(true);
  15006. auto res =
  15007. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15009. EXPECT_EQ(StatusCode::OK_200, res->status);
  15010. }
  15011. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15012. Client cli(REDIR_HOST);
  15013. cli.set_follow_location(true);
  15014. Params params;
  15015. params.emplace("url", "http://example.com");
  15016. params.emplace("status_code", "302");
  15017. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15019. EXPECT_EQ(StatusCode::OK_200, res->status);
  15020. }
  15021. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15022. Client cli(REDIR_HOST);
  15023. cli.set_follow_location(true);
  15024. Params params;
  15025. params.emplace("url", "http://example.com");
  15026. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15028. EXPECT_EQ(StatusCode::OK_200, res->status);
  15029. }
  15030. TEST(HttpToHttpsRedirectTest, CertFile) {
  15031. auto ssl_port = PORT + 1;
  15032. Server svr;
  15033. ASSERT_TRUE(svr.is_valid());
  15034. svr.Get("/index", [&](const Request &, Response &res) {
  15035. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15036. "/index");
  15037. svr.stop();
  15038. });
  15039. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15040. ASSERT_TRUE(ssl_svr.is_valid());
  15041. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15042. res.set_content("test", "text/plain");
  15043. ssl_svr.stop();
  15044. });
  15045. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15046. thread t2 =
  15047. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15048. auto se = detail::scope_exit([&] {
  15049. t2.join();
  15050. t.join();
  15051. ASSERT_FALSE(svr.is_running());
  15052. });
  15053. svr.wait_until_ready();
  15054. ssl_svr.wait_until_ready();
  15055. Client cli("127.0.0.1", PORT);
  15056. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15057. cli.enable_server_certificate_verification(true);
  15058. cli.set_follow_location(true);
  15059. cli.set_connection_timeout(30);
  15060. auto res = cli.Get("/index");
  15061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15062. ASSERT_EQ(StatusCode::OK_200, res->status);
  15063. }
  15064. TEST(SSLClientRedirectTest, CertFile) {
  15065. auto ssl_port = PORT + 1;
  15066. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15067. ASSERT_TRUE(ssl_svr1.is_valid());
  15068. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15069. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15070. "/index");
  15071. ssl_svr1.stop();
  15072. });
  15073. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15074. ASSERT_TRUE(ssl_svr2.is_valid());
  15075. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15076. res.set_content("test", "text/plain");
  15077. ssl_svr2.stop();
  15078. });
  15079. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15080. thread t2 =
  15081. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15082. auto se = detail::scope_exit([&] {
  15083. t2.join();
  15084. t.join();
  15085. ASSERT_FALSE(ssl_svr1.is_running());
  15086. });
  15087. ssl_svr1.wait_until_ready();
  15088. ssl_svr2.wait_until_ready();
  15089. SSLClient cli("127.0.0.1", PORT);
  15090. std::string cert;
  15091. read_file(SERVER_CERT2_FILE, cert);
  15092. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15093. cli.enable_server_certificate_verification(true);
  15094. cli.set_follow_location(true);
  15095. cli.set_connection_timeout(30);
  15096. auto res = cli.Get("/index");
  15097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15098. ASSERT_EQ(StatusCode::OK_200, res->status);
  15099. }
  15100. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15101. // another port, so the client follows it with a new client.
  15102. static Result GetThroughTlsRedirectToDifferentPort(
  15103. const std::function<void(SSLClient &)> &setup,
  15104. const char *target_cert = SERVER_CERT2_FILE,
  15105. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15106. auto ssl_port = PORT + 1;
  15107. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15108. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15109. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15110. "/index");
  15111. });
  15112. SSLServer ssl_svr2(target_cert, target_key);
  15113. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15114. res.set_content("test", "text/plain");
  15115. });
  15116. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15117. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15118. auto se = detail::scope_exit([&] {
  15119. ssl_svr2.stop();
  15120. ssl_svr1.stop();
  15121. t2.join();
  15122. t.join();
  15123. });
  15124. ssl_svr1.wait_until_ready();
  15125. ssl_svr2.wait_until_ready();
  15126. SSLClient cli("127.0.0.1", PORT);
  15127. cli.set_follow_location(true);
  15128. cli.set_connection_timeout(30);
  15129. setup(cli);
  15130. return cli.Get("/index");
  15131. }
  15132. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15133. auto calls = 0;
  15134. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15135. cli.enable_server_certificate_verification(false);
  15136. // Accept the first server only.
  15137. cli.set_session_verifier([&](tls::session_t) {
  15138. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15139. : SSLVerifierResponse::CertificateRejected;
  15140. });
  15141. });
  15142. ASSERT_FALSE(res);
  15143. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15144. EXPECT_EQ(2, calls);
  15145. }
  15146. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15147. std::string pinned;
  15148. auto res = GetThroughTlsRedirectToDifferentPort(
  15149. [&](SSLClient &cli) {
  15150. cli.enable_server_certificate_verification(false);
  15151. // Pin the first certificate seen.
  15152. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15153. if (pinned.empty()) { pinned = ctx.serial(); }
  15154. return ctx.serial() == pinned;
  15155. });
  15156. },
  15157. // A certificate other than the first server's.
  15158. SERVER_CERT_FILE);
  15159. EXPECT_FALSE(res);
  15160. EXPECT_FALSE(pinned.empty());
  15161. }
  15162. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15163. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15164. std::string cert;
  15165. read_file(SERVER_CERT2_FILE, cert);
  15166. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15167. });
  15168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15169. EXPECT_EQ(StatusCode::OK_200, res->status);
  15170. }
  15171. // The target's certificate is signed by the root CA, which the first server's
  15172. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15173. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15174. auto res = GetThroughTlsRedirectToDifferentPort(
  15175. [](SSLClient &cli) {
  15176. std::string root_ca, cert;
  15177. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15178. read_file(SERVER_CERT2_FILE, cert);
  15179. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15180. cli.load_ca_cert_store(cert.data(), cert.size());
  15181. cli.enable_server_hostname_verification(false);
  15182. },
  15183. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15185. EXPECT_EQ(StatusCode::OK_200, res->status);
  15186. }
  15187. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15188. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15189. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15190. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  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.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15198. cli.enable_server_hostname_verification(false);
  15199. },
  15200. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15201. ASSERT_FALSE(res);
  15202. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15203. }
  15204. #endif
  15205. #endif
  15206. #ifdef CPPHTTPLIB_SSL_ENABLED
  15207. // Test that set_ca_cert_store() skips system certs (consistent with
  15208. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15209. // should be trusted - system certs should NOT be loaded.
  15210. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15211. // Load a specific cert that is NOT a system CA cert
  15212. std::string cert;
  15213. read_file(SERVER_CERT2_FILE, cert);
  15214. SSLClient cli("google.com");
  15215. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15216. cli.enable_server_certificate_verification(true);
  15217. // This should FAIL because:
  15218. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15219. // 2. System certs should NOT be loaded when custom store is set
  15220. // If system certs WERE loaded, this would succeed
  15221. auto res = cli.Get("/");
  15222. ASSERT_FALSE(res);
  15223. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15224. }
  15225. // Same as above, but through the native store handle path. Regression test:
  15226. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15227. // merged system certs into the user-provided store.
  15228. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15229. std::string cert;
  15230. read_file(SERVER_CERT2_FILE, cert);
  15231. SSLClient cli("google.com");
  15232. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15233. cli.enable_server_certificate_verification(true);
  15234. auto res = cli.Get("/");
  15235. ASSERT_FALSE(res);
  15236. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15237. }
  15238. // A custom store set via the native handle must still verify a server whose
  15239. // cert it does contain.
  15240. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15241. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15242. ASSERT_TRUE(svr.is_valid());
  15243. svr.Get("/test", [&](const Request &, Response &res) {
  15244. res.set_content("test", "text/plain");
  15245. });
  15246. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15247. auto se = detail::scope_exit([&] {
  15248. svr.stop();
  15249. t.join();
  15250. ASSERT_FALSE(svr.is_running());
  15251. });
  15252. svr.wait_until_ready();
  15253. SSLClient cli("127.0.0.1", PORT);
  15254. std::string cert;
  15255. read_file(SERVER_CERT2_FILE, cert);
  15256. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15257. cli.enable_server_certificate_verification(true);
  15258. cli.set_connection_timeout(30);
  15259. auto res = cli.Get("/test");
  15260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15261. ASSERT_EQ(StatusCode::OK_200, res->status);
  15262. }
  15263. // CA certs loaded through the universal Client must be transferred to the
  15264. // client created internally for following an HTTPS redirect. Regression test:
  15265. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15266. // the CA data for redirect transfer.
  15267. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15268. auto ssl_port = PORT + 1;
  15269. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15270. ASSERT_TRUE(ssl_svr1.is_valid());
  15271. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15272. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15273. "/index");
  15274. });
  15275. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15276. ASSERT_TRUE(ssl_svr2.is_valid());
  15277. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15278. res.set_content("test", "text/plain");
  15279. });
  15280. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15281. thread t2 =
  15282. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15283. auto se = detail::scope_exit([&] {
  15284. ssl_svr2.stop();
  15285. ssl_svr1.stop();
  15286. t2.join();
  15287. t.join();
  15288. ASSERT_FALSE(ssl_svr1.is_running());
  15289. });
  15290. ssl_svr1.wait_until_ready();
  15291. ssl_svr2.wait_until_ready();
  15292. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15293. std::string cert;
  15294. read_file(SERVER_CERT2_FILE, cert);
  15295. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15296. cli.enable_server_certificate_verification(true);
  15297. cli.set_follow_location(true);
  15298. cli.set_connection_timeout(30);
  15299. auto res = cli.Get("/index");
  15300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15301. ASSERT_EQ(StatusCode::OK_200, res->status);
  15302. }
  15303. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15304. // so a host signed by a system CA verifies even though a custom CA is set
  15305. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15306. std::string cert;
  15307. read_file(SERVER_CERT2_FILE, cert);
  15308. SSLClient cli("google.com");
  15309. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15310. cli.enable_system_ca(true);
  15311. cli.enable_server_certificate_verification(true);
  15312. auto res = cli.Get("/");
  15313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15314. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15315. }
  15316. // The custom CA remains effective when combined with the system CA
  15317. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15318. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15319. ASSERT_TRUE(svr.is_valid());
  15320. svr.Get("/test", [&](const Request &, Response &res) {
  15321. res.set_content("test", "text/plain");
  15322. });
  15323. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15324. auto se = detail::scope_exit([&] {
  15325. svr.stop();
  15326. t.join();
  15327. ASSERT_FALSE(svr.is_running());
  15328. });
  15329. svr.wait_until_ready();
  15330. SSLClient cli("127.0.0.1", PORT);
  15331. std::string cert;
  15332. read_file(SERVER_CERT2_FILE, cert);
  15333. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15334. cli.enable_system_ca(true);
  15335. cli.enable_server_certificate_verification(true);
  15336. cli.set_connection_timeout(30);
  15337. auto res = cli.Get("/test");
  15338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15339. ASSERT_EQ(StatusCode::OK_200, res->status);
  15340. }
  15341. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15342. // skip chain verification entirely (only the certificate identity was
  15343. // checked), so a server presenting an untrusted certificate with a matching
  15344. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15345. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15346. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15347. ASSERT_TRUE(svr.is_valid());
  15348. svr.Get("/test", [&](const Request &, Response &res) {
  15349. res.set_content("test", "text/plain");
  15350. });
  15351. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15352. auto se = detail::scope_exit([&] {
  15353. svr.stop();
  15354. t.join();
  15355. ASSERT_FALSE(svr.is_running());
  15356. });
  15357. svr.wait_until_ready();
  15358. SSLClient cli("127.0.0.1", PORT);
  15359. std::string cert;
  15360. // A trusted CA that did not sign the server certificate. The server cert
  15361. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15362. // this connection.
  15363. read_file(CLIENT_CA_CERT_FILE, cert);
  15364. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15365. cli.enable_server_certificate_verification(true);
  15366. cli.set_connection_timeout(30);
  15367. auto res = cli.Get("/test");
  15368. ASSERT_FALSE(res);
  15369. }
  15370. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15371. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15372. // CA that failed to come through fails verification instead of trusting them.
  15373. // (wolfSSL does not list the system CAs it loaded.)
  15374. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15375. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15376. ASSERT_TRUE(svr.is_valid());
  15377. auto port = svr.bind_to_any_port("127.0.0.1");
  15378. ASSERT_LT(0, port);
  15379. thread t = thread([&] { svr.listen_after_bind(); });
  15380. auto se = detail::scope_exit([&] {
  15381. svr.stop();
  15382. t.join();
  15383. ASSERT_FALSE(svr.is_running());
  15384. });
  15385. svr.wait_until_ready();
  15386. // The CAs a client trusts once its first request has loaded them
  15387. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15388. Client cli("https://127.0.0.1:" + std::to_string(port));
  15389. setup(cli);
  15390. cli.Get("/");
  15391. return tls::get_ca_names(cli.tls_context()).size();
  15392. };
  15393. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15394. EXPECT_EQ(0u,
  15395. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15396. }
  15397. #endif
  15398. // enable_system_ca(false) prevents system CA loading entirely
  15399. TEST(SSLClientTest, DisableSystemCa_Online) {
  15400. SSLClient cli("google.com");
  15401. cli.enable_system_ca(false);
  15402. cli.enable_server_certificate_verification(true);
  15403. auto res = cli.Get("/");
  15404. ASSERT_FALSE(res);
  15405. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15406. // itself when the CA chain is empty
  15407. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15408. res.error() == Error::SSLConnection);
  15409. }
  15410. // The universal Client forwards enable_system_ca()
  15411. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15412. std::string cert;
  15413. read_file(SERVER_CERT2_FILE, cert);
  15414. Client cli("https://google.com");
  15415. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15416. cli.enable_system_ca(true);
  15417. cli.enable_server_certificate_verification(true);
  15418. auto res = cli.Get("/");
  15419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15420. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15421. }
  15422. // The system CA policy must carry over to the client created internally for
  15423. // following a cross-host HTTPS redirect
  15424. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15425. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15426. ASSERT_TRUE(svr.is_valid());
  15427. svr.Get("/index", [&](const Request &, Response &res) {
  15428. res.set_redirect("https://www.google.com/");
  15429. });
  15430. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15431. auto se = detail::scope_exit([&] {
  15432. svr.stop();
  15433. t.join();
  15434. ASSERT_FALSE(svr.is_running());
  15435. });
  15436. svr.wait_until_ready();
  15437. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15438. std::string cert;
  15439. read_file(SERVER_CERT2_FILE, cert);
  15440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15441. cli.enable_system_ca(true);
  15442. cli.enable_server_certificate_verification(true);
  15443. cli.set_follow_location(true);
  15444. cli.set_connection_timeout(30);
  15445. // Receiving any response proves the redirect client completed the TLS
  15446. // handshake with a system-CA-signed host
  15447. auto res = cli.Get("/index");
  15448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15449. }
  15450. TEST(MultipartFormDataTest, LargeData) {
  15451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15452. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15453. const ContentReader &content_reader) {
  15454. if (req.is_multipart_form_data()) {
  15455. std::vector<FormData> items;
  15456. content_reader(
  15457. [&](const FormData &file) {
  15458. items.push_back(file);
  15459. return true;
  15460. },
  15461. [&](const char *data, size_t data_length) {
  15462. items.back().content.append(data, data_length);
  15463. return true;
  15464. });
  15465. EXPECT_TRUE(std::string(items[0].name) == "document");
  15466. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15467. EXPECT_TRUE(items[0].filename == "2MB_data");
  15468. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15469. EXPECT_TRUE(items[1].name == "hello");
  15470. EXPECT_TRUE(items[1].content == "world");
  15471. EXPECT_TRUE(items[1].filename == "");
  15472. EXPECT_TRUE(items[1].content_type == "");
  15473. } else {
  15474. std::string body;
  15475. content_reader([&](const char *data, size_t data_length) {
  15476. body.append(data, data_length);
  15477. return true;
  15478. });
  15479. }
  15480. });
  15481. auto port = svr.bind_to_any_port(HOST);
  15482. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15483. auto se = detail::scope_exit([&] {
  15484. svr.stop();
  15485. t.join();
  15486. ASSERT_FALSE(svr.is_running());
  15487. });
  15488. svr.wait_until_ready();
  15489. {
  15490. std::string data(1024 * 1024 * 2, '.');
  15491. std::stringstream buffer;
  15492. buffer << data;
  15493. SSLClient cli(HOST, port);
  15494. cli.enable_server_certificate_verification(false);
  15495. UploadFormDataItems items{
  15496. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15497. {"hello", "world", "", ""},
  15498. };
  15499. auto res = cli.Post("/post", items);
  15500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15501. ASSERT_EQ(StatusCode::OK_200, res->status);
  15502. }
  15503. }
  15504. TEST(MultipartFormDataTest, DataProviderItems) {
  15505. std::random_device seed_gen;
  15506. std::mt19937 random(seed_gen());
  15507. std::string rand1;
  15508. rand1.resize(1000);
  15509. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15510. std::string rand2;
  15511. rand2.resize(3000);
  15512. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15514. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15515. const ContentReader &content_reader) {
  15516. ASSERT_FALSE(req.is_multipart_form_data());
  15517. std::string body;
  15518. content_reader([&](const char *data, size_t data_length) {
  15519. body.append(data, data_length);
  15520. return true;
  15521. });
  15522. EXPECT_EQ(body, "");
  15523. });
  15524. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15525. const ContentReader &content_reader) {
  15526. ASSERT_TRUE(req.is_multipart_form_data());
  15527. std::vector<FormData> items;
  15528. content_reader(
  15529. [&](const FormData &file) {
  15530. items.push_back(file);
  15531. return true;
  15532. },
  15533. [&](const char *data, size_t data_length) {
  15534. items.back().content.append(data, data_length);
  15535. return true;
  15536. });
  15537. ASSERT_TRUE(items.size() == 2);
  15538. EXPECT_EQ(std::string(items[0].name), "name1");
  15539. EXPECT_EQ(items[0].content, "Testing123");
  15540. EXPECT_EQ(items[0].filename, "filename1");
  15541. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15542. EXPECT_EQ(items[1].name, "name2");
  15543. EXPECT_EQ(items[1].content, "Testing456");
  15544. EXPECT_EQ(items[1].filename, "");
  15545. EXPECT_EQ(items[1].content_type, "");
  15546. });
  15547. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15548. const ContentReader &content_reader) {
  15549. ASSERT_TRUE(req.is_multipart_form_data());
  15550. std::vector<FormData> items;
  15551. content_reader(
  15552. [&](const FormData &file) {
  15553. items.push_back(file);
  15554. return true;
  15555. },
  15556. [&](const char *data, size_t data_length) {
  15557. items.back().content.append(data, data_length);
  15558. return true;
  15559. });
  15560. ASSERT_TRUE(items.size() == 2);
  15561. EXPECT_EQ(items[0].name, "name3");
  15562. EXPECT_EQ(items[0].content, rand1);
  15563. EXPECT_EQ(items[0].filename, "filename3");
  15564. EXPECT_EQ(items[0].content_type, "");
  15565. EXPECT_EQ(items[1].name, "name4");
  15566. EXPECT_EQ(items[1].content, rand2);
  15567. EXPECT_EQ(items[1].filename, "filename4");
  15568. EXPECT_EQ(items[1].content_type, "");
  15569. });
  15570. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15571. const ContentReader &content_reader) {
  15572. ASSERT_TRUE(req.is_multipart_form_data());
  15573. std::vector<FormData> items;
  15574. content_reader(
  15575. [&](const FormData &file) {
  15576. items.push_back(file);
  15577. return true;
  15578. },
  15579. [&](const char *data, size_t data_length) {
  15580. items.back().content.append(data, data_length);
  15581. return true;
  15582. });
  15583. ASSERT_TRUE(items.size() == 4);
  15584. EXPECT_EQ(std::string(items[0].name), "name1");
  15585. EXPECT_EQ(items[0].content, "Testing123");
  15586. EXPECT_EQ(items[0].filename, "filename1");
  15587. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15588. EXPECT_EQ(items[1].name, "name2");
  15589. EXPECT_EQ(items[1].content, "Testing456");
  15590. EXPECT_EQ(items[1].filename, "");
  15591. EXPECT_EQ(items[1].content_type, "");
  15592. EXPECT_EQ(items[2].name, "name3");
  15593. EXPECT_EQ(items[2].content, rand1);
  15594. EXPECT_EQ(items[2].filename, "filename3");
  15595. EXPECT_EQ(items[2].content_type, "");
  15596. EXPECT_EQ(items[3].name, "name4");
  15597. EXPECT_EQ(items[3].content, rand2);
  15598. EXPECT_EQ(items[3].filename, "filename4");
  15599. EXPECT_EQ(items[3].content_type, "");
  15600. });
  15601. auto port = svr.bind_to_any_port("localhost");
  15602. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15603. auto se = detail::scope_exit([&] {
  15604. svr.stop();
  15605. t.join();
  15606. ASSERT_FALSE(svr.is_running());
  15607. });
  15608. svr.wait_until_ready();
  15609. {
  15610. SSLClient cli("localhost", port);
  15611. cli.enable_server_certificate_verification(false);
  15612. UploadFormDataItems items{
  15613. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15614. {"name2", "Testing456", "", ""}, // not a file
  15615. };
  15616. {
  15617. auto res = cli.Post("/post-none", {}, {}, {});
  15618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15619. ASSERT_EQ(StatusCode::OK_200, res->status);
  15620. }
  15621. FormDataProviderItems providers;
  15622. {
  15623. auto res =
  15624. cli.Post("/post-items", {}, items, providers); // empty providers
  15625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15626. ASSERT_EQ(StatusCode::OK_200, res->status);
  15627. }
  15628. providers.push_back({"name3",
  15629. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15630. // test the offset is given correctly at each step
  15631. if (!offset)
  15632. sink.os.write(rand1.data(), 30);
  15633. else if (offset == 30)
  15634. sink.os.write(rand1.data() + 30, 300);
  15635. else if (offset == 330)
  15636. sink.os.write(rand1.data() + 330, 670);
  15637. else if (offset == rand1.size())
  15638. sink.done();
  15639. return true;
  15640. },
  15641. "filename3",
  15642. {}});
  15643. providers.push_back({"name4",
  15644. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15645. // test the offset is given correctly at each step
  15646. if (!offset)
  15647. sink.os.write(rand2.data(), 2000);
  15648. else if (offset == 2000)
  15649. sink.os.write(rand2.data() + 2000, 1);
  15650. else if (offset == 2001)
  15651. sink.os.write(rand2.data() + 2001, 999);
  15652. else if (offset == rand2.size())
  15653. sink.done();
  15654. return true;
  15655. },
  15656. "filename4",
  15657. {}});
  15658. {
  15659. auto res = cli.Post("/post-providers", {}, {}, providers);
  15660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15661. ASSERT_EQ(StatusCode::OK_200, res->status);
  15662. }
  15663. {
  15664. auto res = cli.Post("/post-both", {}, items, providers);
  15665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15666. ASSERT_EQ(StatusCode::OK_200, res->status);
  15667. }
  15668. }
  15669. }
  15670. TEST(MultipartFormDataTest, BadHeader) {
  15671. Server svr;
  15672. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15673. res.set_content("ok", "text/plain");
  15674. });
  15675. thread t = thread([&] { svr.listen(HOST, PORT); });
  15676. auto se = detail::scope_exit([&] {
  15677. svr.stop();
  15678. t.join();
  15679. ASSERT_FALSE(svr.is_running());
  15680. });
  15681. svr.wait_until_ready();
  15682. const std::string body =
  15683. "This is the preamble. It is to be ignored, though it\r\n"
  15684. "is a handy place for composition agents to include an\r\n"
  15685. "explanatory note to non-MIME conformant readers.\r\n"
  15686. "\r\n"
  15687. "\r\n"
  15688. "--simple boundary\r\n"
  15689. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15690. ": BAD...\r\n"
  15691. "\r\n"
  15692. "value1\r\n"
  15693. "--simple boundary\r\n"
  15694. "Content-Disposition: form-data; name=\"field2\"; "
  15695. "filename=\"example.txt\"\r\n"
  15696. "\r\n"
  15697. "value2\r\n"
  15698. "--simple boundary--\r\n"
  15699. "This is the epilogue. It is also to be ignored.\r\n";
  15700. std::string content_type =
  15701. R"(multipart/form-data; boundary="simple boundary")";
  15702. Client cli(HOST, PORT);
  15703. auto res = cli.Post("/post", body, content_type.c_str());
  15704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15705. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15706. }
  15707. TEST(MultipartFormDataTest, WithPreamble) {
  15708. Server svr;
  15709. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15710. res.set_content("ok", "text/plain");
  15711. });
  15712. thread t = thread([&] { svr.listen(HOST, PORT); });
  15713. auto se = detail::scope_exit([&] {
  15714. svr.stop();
  15715. t.join();
  15716. ASSERT_FALSE(svr.is_running());
  15717. });
  15718. svr.wait_until_ready();
  15719. const std::string body =
  15720. "This is the preamble. It is to be ignored, though it\r\n"
  15721. "is a handy place for composition agents to include an\r\n"
  15722. "explanatory note to non-MIME conformant readers.\r\n"
  15723. "\r\n"
  15724. "\r\n"
  15725. "--simple boundary\r\n"
  15726. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15727. "\r\n"
  15728. "value1\r\n"
  15729. "--simple boundary\r\n"
  15730. "Content-Disposition: form-data; name=\"field2\"; "
  15731. "filename=\"example.txt\"\r\n"
  15732. "\r\n"
  15733. "value2\r\n"
  15734. "--simple boundary--\r\n"
  15735. "This is the epilogue. It is also to be ignored.\r\n";
  15736. std::string content_type =
  15737. R"(multipart/form-data; boundary="simple boundary")";
  15738. Client cli(HOST, PORT);
  15739. auto res = cli.Post("/post", body, content_type.c_str());
  15740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15741. EXPECT_EQ(StatusCode::OK_200, res->status);
  15742. }
  15743. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15745. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15746. const ContentReader &content_reader) {
  15747. if (req.is_multipart_form_data()) {
  15748. std::vector<FormData> items;
  15749. content_reader(
  15750. [&](const FormData &file) {
  15751. items.push_back(file);
  15752. return true;
  15753. },
  15754. [&](const char *data, size_t data_length) {
  15755. items.back().content.append(data, data_length);
  15756. return true;
  15757. });
  15758. EXPECT_TRUE(std::string(items[0].name) == "document");
  15759. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15760. EXPECT_TRUE(items[0].filename == "2MB_data");
  15761. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15762. EXPECT_TRUE(items[1].name == "hello");
  15763. EXPECT_TRUE(items[1].content == "world");
  15764. EXPECT_TRUE(items[1].filename == "");
  15765. EXPECT_TRUE(items[1].content_type == "");
  15766. } else {
  15767. std::string body;
  15768. content_reader([&](const char *data, size_t data_length) {
  15769. body.append(data, data_length);
  15770. return true;
  15771. });
  15772. }
  15773. });
  15774. auto port = svr.bind_to_any_port("localhost");
  15775. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15776. auto se = detail::scope_exit([&] {
  15777. svr.stop();
  15778. t.join();
  15779. ASSERT_FALSE(svr.is_running());
  15780. });
  15781. svr.wait_until_ready();
  15782. {
  15783. std::string data(1024 * 1024 * 2, '.');
  15784. std::stringstream buffer;
  15785. buffer << data;
  15786. SSLClient cli("localhost", port);
  15787. cli.enable_server_certificate_verification(false);
  15788. UploadFormDataItems items{
  15789. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15790. {"hello", "world", "", ""},
  15791. };
  15792. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15794. ASSERT_EQ(StatusCode::OK_200, res->status);
  15795. }
  15796. }
  15797. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15798. std::string data(1024 * 1024 * 2, '&');
  15799. std::stringstream buffer;
  15800. buffer << data;
  15801. Client cli("https://localhost:8080");
  15802. UploadFormDataItems items{
  15803. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15804. {"hello", "world", "", ""},
  15805. };
  15806. for (const char &c : " \t\r\n") {
  15807. auto res =
  15808. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15809. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15810. ASSERT_FALSE(res);
  15811. }
  15812. }
  15813. TEST(MultipartFormDataTest, PutFormData) {
  15814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15815. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15816. const ContentReader &content_reader) {
  15817. if (req.is_multipart_form_data()) {
  15818. std::vector<FormData> items;
  15819. content_reader(
  15820. [&](const FormData &file) {
  15821. items.push_back(file);
  15822. return true;
  15823. },
  15824. [&](const char *data, size_t data_length) {
  15825. items.back().content.append(data, data_length);
  15826. return true;
  15827. });
  15828. EXPECT_TRUE(std::string(items[0].name) == "document");
  15829. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15830. EXPECT_TRUE(items[0].filename == "2MB_data");
  15831. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15832. EXPECT_TRUE(items[1].name == "hello");
  15833. EXPECT_TRUE(items[1].content == "world");
  15834. EXPECT_TRUE(items[1].filename == "");
  15835. EXPECT_TRUE(items[1].content_type == "");
  15836. } else {
  15837. std::string body;
  15838. content_reader([&](const char *data, size_t data_length) {
  15839. body.append(data, data_length);
  15840. return true;
  15841. });
  15842. }
  15843. });
  15844. auto port = svr.bind_to_any_port("localhost");
  15845. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15846. auto se = detail::scope_exit([&] {
  15847. svr.stop();
  15848. t.join();
  15849. ASSERT_FALSE(svr.is_running());
  15850. });
  15851. svr.wait_until_ready();
  15852. {
  15853. std::string data(1024 * 1024 * 2, '&');
  15854. std::stringstream buffer;
  15855. buffer << data;
  15856. SSLClient cli("localhost", port);
  15857. cli.enable_server_certificate_verification(false);
  15858. UploadFormDataItems items{
  15859. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15860. {"hello", "world", "", ""},
  15861. };
  15862. auto res = cli.Put("/put", items);
  15863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15864. ASSERT_EQ(StatusCode::OK_200, res->status);
  15865. }
  15866. }
  15867. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15869. svr.Put("/put_customboundary",
  15870. [&](const Request &req, const Response & /*res*/,
  15871. const ContentReader &content_reader) {
  15872. if (req.is_multipart_form_data()) {
  15873. std::vector<FormData> items;
  15874. content_reader(
  15875. [&](const FormData &file) {
  15876. items.push_back(file);
  15877. return true;
  15878. },
  15879. [&](const char *data, size_t data_length) {
  15880. items.back().content.append(data, data_length);
  15881. return true;
  15882. });
  15883. EXPECT_TRUE(std::string(items[0].name) == "document");
  15884. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15885. EXPECT_TRUE(items[0].filename == "2MB_data");
  15886. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15887. EXPECT_TRUE(items[1].name == "hello");
  15888. EXPECT_TRUE(items[1].content == "world");
  15889. EXPECT_TRUE(items[1].filename == "");
  15890. EXPECT_TRUE(items[1].content_type == "");
  15891. } else {
  15892. std::string body;
  15893. content_reader([&](const char *data, size_t data_length) {
  15894. body.append(data, data_length);
  15895. return true;
  15896. });
  15897. }
  15898. });
  15899. auto port = svr.bind_to_any_port("localhost");
  15900. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15901. auto se = detail::scope_exit([&] {
  15902. svr.stop();
  15903. t.join();
  15904. ASSERT_FALSE(svr.is_running());
  15905. });
  15906. svr.wait_until_ready();
  15907. {
  15908. std::string data(1024 * 1024 * 2, '&');
  15909. std::stringstream buffer;
  15910. buffer << data;
  15911. SSLClient cli("localhost", port);
  15912. cli.enable_server_certificate_verification(false);
  15913. UploadFormDataItems items{
  15914. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15915. {"hello", "world", "", ""},
  15916. };
  15917. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15919. ASSERT_EQ(StatusCode::OK_200, res->status);
  15920. }
  15921. }
  15922. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15923. std::string data(1024 * 1024 * 2, '&');
  15924. std::stringstream buffer;
  15925. buffer << data;
  15926. Client cli("https://localhost:8080");
  15927. cli.enable_server_certificate_verification(false);
  15928. UploadFormDataItems items{
  15929. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15930. {"hello", "world", "", ""},
  15931. };
  15932. for (const char &c : " \t\r\n") {
  15933. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15934. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15935. ASSERT_FALSE(res);
  15936. }
  15937. }
  15938. TEST(MultipartFormDataTest, AlternateFilename) {
  15939. auto handled = false;
  15940. Server svr;
  15941. svr.Post("/test", [&](const Request &req, Response &res) {
  15942. ASSERT_EQ(2u, req.form.files.size());
  15943. ASSERT_EQ(1u, req.form.fields.size());
  15944. // Test files
  15945. const auto &file1 = req.form.get_file("file1");
  15946. ASSERT_EQ("file1", file1.name);
  15947. ASSERT_EQ("A.txt", file1.filename);
  15948. ASSERT_EQ("text/plain", file1.content_type);
  15949. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15950. const auto &file2 = req.form.get_file("file2");
  15951. ASSERT_EQ("file2", file2.name);
  15952. ASSERT_EQ("a.html", file2.filename);
  15953. ASSERT_EQ("text/html", file2.content_type);
  15954. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15955. file2.content);
  15956. // Test text field
  15957. const auto &text = req.form.get_field("text");
  15958. ASSERT_EQ("text default", text);
  15959. res.set_content("ok", "text/plain");
  15960. handled = true;
  15961. });
  15962. thread t = thread([&] { svr.listen(HOST, PORT); });
  15963. auto se = detail::scope_exit([&] {
  15964. svr.stop();
  15965. t.join();
  15966. ASSERT_FALSE(svr.is_running());
  15967. ASSERT_TRUE(handled);
  15968. });
  15969. svr.wait_until_ready();
  15970. auto req = "POST /test HTTP/1.1\r\n"
  15971. "Host: localhost\r\n"
  15972. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15973. "Content-Length: 399\r\n"
  15974. "\r\n"
  15975. "----------\r\n"
  15976. "Content-Disposition: form-data; name=\"text\"\r\n"
  15977. "\r\n"
  15978. "text default\r\n"
  15979. "----------\r\n"
  15980. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15981. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15982. "Content-Type: text/plain\r\n"
  15983. "\r\n"
  15984. "Content of a.txt.\r\n"
  15985. "\r\n"
  15986. "----------\r\n"
  15987. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15988. "\"a.html\"\r\n"
  15989. "Content-Type: text/html\r\n"
  15990. "\r\n"
  15991. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15992. "\r\n"
  15993. "------------\r\n";
  15994. ASSERT_TRUE(send_request(1, req));
  15995. }
  15996. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15997. auto handled = false;
  15998. Server svr;
  15999. svr.Post("/test", [&](const Request &req, Response &res) {
  16000. // Case-insensitive "utf-8''" prefix with a long value
  16001. const auto &file = req.form.get_file("file1");
  16002. ASSERT_EQ("file1", file.name);
  16003. // 8000 chars exercises both the Content-Disposition parser and the
  16004. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16005. // Prior to the fix, std::regex_match on this header would cause O(N)
  16006. // stack recursion in libstdc++, leading to SIGSEGV.
  16007. std::string expected_filename(8000, 'A');
  16008. ASSERT_EQ(expected_filename, file.filename);
  16009. res.set_content("ok", "text/plain");
  16010. handled = true;
  16011. });
  16012. thread t = thread([&] { svr.listen(HOST, PORT); });
  16013. auto se = detail::scope_exit([&] {
  16014. svr.stop();
  16015. t.join();
  16016. ASSERT_FALSE(svr.is_running());
  16017. ASSERT_TRUE(handled);
  16018. });
  16019. svr.wait_until_ready();
  16020. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16021. // Regression test for GHSA-qq6v-r583-3h69
  16022. std::string long_filename(8000, 'A');
  16023. std::string body = "----------\r\n"
  16024. "Content-Disposition: form-data; name=\"file1\"; "
  16025. "filename*=\"Utf-8''" +
  16026. long_filename +
  16027. "\"\r\n"
  16028. "\r\n"
  16029. "hello\r\n"
  16030. "------------\r\n";
  16031. auto req = "POST /test HTTP/1.1\r\n"
  16032. "Host: localhost\r\n"
  16033. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16034. "Content-Length: " +
  16035. std::to_string(body.size()) + "\r\n\r\n" + body;
  16036. ASSERT_TRUE(send_request(1, req));
  16037. }
  16038. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16039. auto handled = false;
  16040. Server svr;
  16041. svr.Post("/test", [&](const Request &req, Response &) {
  16042. ASSERT_EQ(2u, req.form.fields.size());
  16043. const auto &text1 = req.form.get_field("text1");
  16044. ASSERT_EQ("text1", text1);
  16045. const auto &text2 = req.form.get_field("text2");
  16046. ASSERT_EQ("text2", text2);
  16047. handled = true;
  16048. });
  16049. thread t = thread([&] { svr.listen(HOST, PORT); });
  16050. auto se = detail::scope_exit([&] {
  16051. svr.stop();
  16052. t.join();
  16053. ASSERT_FALSE(svr.is_running());
  16054. ASSERT_TRUE(handled);
  16055. });
  16056. svr.wait_until_ready();
  16057. auto req = "POST /test HTTP/1.1\r\n"
  16058. "Host: localhost\r\n"
  16059. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16060. "Content-Length: 146\r\n"
  16061. "\r\n----------\r\n"
  16062. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16063. "\r\n"
  16064. "text1"
  16065. "\r\n----------\r\n"
  16066. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16067. "\r\n"
  16068. "text2"
  16069. "\r\n------------";
  16070. std::string response;
  16071. ASSERT_TRUE(send_request(1, req, &response));
  16072. ASSERT_EQ("200", response.substr(9, 3));
  16073. }
  16074. TEST(MultipartFormDataTest, ContentLength) {
  16075. auto handled = false;
  16076. Server svr;
  16077. svr.Post("/test", [&](const Request &req, Response &) {
  16078. ASSERT_EQ(2u, req.form.fields.size());
  16079. const auto &text1 = req.form.get_field("text1");
  16080. ASSERT_EQ("text1", text1);
  16081. const auto &text2 = req.form.get_field("text2");
  16082. ASSERT_EQ("text2", text2);
  16083. handled = true;
  16084. });
  16085. thread t = thread([&] { svr.listen(HOST, PORT); });
  16086. auto se = detail::scope_exit([&] {
  16087. svr.stop();
  16088. t.join();
  16089. ASSERT_FALSE(svr.is_running());
  16090. ASSERT_TRUE(handled);
  16091. });
  16092. svr.wait_until_ready();
  16093. auto req = "POST /test HTTP/1.1\r\n"
  16094. "Host: localhost\r\n"
  16095. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16096. "Content-Length: 167\r\n"
  16097. "\r\n----------\r\n"
  16098. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16099. "Content-Length: 5\r\n"
  16100. "\r\n"
  16101. "text1"
  16102. "\r\n----------\r\n"
  16103. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16104. "\r\n"
  16105. "text2"
  16106. "\r\n------------\r\n";
  16107. std::string response;
  16108. ASSERT_TRUE(send_request(1, req, &response));
  16109. ASSERT_EQ("200", response.substr(9, 3));
  16110. }
  16111. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16112. auto handled = false;
  16113. Server svr;
  16114. svr.Post("/test", [&](const Request &req, Response &) {
  16115. ASSERT_EQ(2u, req.form.fields.size());
  16116. const auto &text1 = req.form.get_field("text1");
  16117. ASSERT_EQ("text1", text1);
  16118. // TODO: Add header access for text fields if needed
  16119. const auto &text2 = req.form.get_field("text2");
  16120. ASSERT_EQ("text2", text2);
  16121. // TODO: Header access for text fields needs to be implemented
  16122. // auto &headers = it->second.headers;
  16123. // ASSERT_EQ(3U, headers.size());
  16124. // auto custom_header = headers.find("x-whatever");
  16125. // ASSERT_TRUE(custom_header != headers.end());
  16126. // ASSERT_NE("customvalue", custom_header->second);
  16127. // ASSERT_EQ("CustomValue", custom_header->second);
  16128. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16129. handled = true;
  16130. });
  16131. thread t = thread([&] { svr.listen(HOST, PORT); });
  16132. auto se = detail::scope_exit([&] {
  16133. svr.stop();
  16134. t.join();
  16135. ASSERT_FALSE(svr.is_running());
  16136. ASSERT_TRUE(handled);
  16137. });
  16138. svr.wait_until_ready();
  16139. auto req = "POST /test HTTP/1.1\r\n"
  16140. "Host: localhost\r\n"
  16141. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16142. "Content-Length: 232\r\n"
  16143. "\r\n----------\r\n"
  16144. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16145. "Content-Length: 5\r\n"
  16146. "X-Test: 1\r\n"
  16147. "\r\n"
  16148. "text1"
  16149. "\r\n----------\r\n"
  16150. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16151. "Content-Type: text/plain\r\n"
  16152. "X-Whatever: CustomValue\r\n"
  16153. "\r\n"
  16154. "text2"
  16155. "\r\n------------\r\n"
  16156. "That should be disregarded. Not even read";
  16157. std::string response;
  16158. ASSERT_TRUE(send_request(1, req, &response));
  16159. ASSERT_EQ("200", response.substr(9, 3));
  16160. }
  16161. TEST(MultipartFormDataTest, LargeHeader) {
  16162. auto handled = false;
  16163. Server svr;
  16164. svr.Post("/test", [&](const Request &req, Response &) {
  16165. ASSERT_EQ(1u, req.form.fields.size());
  16166. const auto &text = req.form.get_field("name1");
  16167. ASSERT_EQ("text1", text);
  16168. handled = true;
  16169. });
  16170. thread t = thread([&] { svr.listen(HOST, PORT); });
  16171. auto se = detail::scope_exit([&] {
  16172. svr.stop();
  16173. t.join();
  16174. ASSERT_FALSE(svr.is_running());
  16175. ASSERT_TRUE(handled);
  16176. });
  16177. svr.wait_until_ready();
  16178. auto boundary = std::string("cpp-httplib-multipart-data");
  16179. std::string content = "--" + boundary +
  16180. "\r\n"
  16181. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16182. "\r\n"
  16183. "text1\r\n"
  16184. "--" +
  16185. boundary + "--\r\n";
  16186. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16187. "Host: localhost\r\n"
  16188. "Content-Type: multipart/form-data;boundary=" +
  16189. boundary +
  16190. "\r\n"
  16191. "Content-Length: " +
  16192. std::to_string(content.size()) +
  16193. "\r\n"
  16194. "Dummy-Header: ";
  16195. std::string header_suffix = "\r\n"
  16196. "\r\n";
  16197. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16198. size_t header_dummy_size =
  16199. read_buff_size -
  16200. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16201. auto header_dummy = std::string(header_dummy_size, '@');
  16202. auto req = header_prefix + header_dummy + header_suffix + content;
  16203. std::string response;
  16204. ASSERT_TRUE(send_request(1, req, &response));
  16205. ASSERT_EQ("200", response.substr(9, 3));
  16206. }
  16207. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16208. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16209. // (not chunked Transfer-Encoding) after the streaming refactor.
  16210. auto handled = false;
  16211. Server svr;
  16212. svr.Post("/upload", [&](const Request &req, Response &res) {
  16213. auto cl_it = req.headers.find("Content-Length");
  16214. EXPECT_TRUE(cl_it != req.headers.end());
  16215. auto te_it = req.headers.find("Transfer-Encoding");
  16216. EXPECT_TRUE(te_it == req.headers.end());
  16217. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16218. res.set_content("ok", "text/plain");
  16219. handled = true;
  16220. });
  16221. auto port = svr.bind_to_any_port(HOST);
  16222. auto t = thread([&] { svr.listen_after_bind(); });
  16223. auto se = detail::scope_exit([&] {
  16224. svr.stop();
  16225. t.join();
  16226. ASSERT_FALSE(svr.is_running());
  16227. ASSERT_TRUE(handled);
  16228. });
  16229. svr.wait_until_ready();
  16230. UploadFormDataItems items = {
  16231. {"field1", "hello", "", "text/plain"},
  16232. {"file1", "world", "test.txt", "application/octet-stream"},
  16233. };
  16234. Client cli(HOST, port);
  16235. auto res = cli.Post("/upload", {}, items);
  16236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16237. EXPECT_EQ(StatusCode::OK_200, res->status);
  16238. }
  16239. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16240. // Verify that make_multipart_content_provider coalesces many small segments
  16241. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16242. constexpr size_t kItemCount = 1000;
  16243. UploadFormDataItems items;
  16244. items.reserve(kItemCount);
  16245. for (size_t i = 0; i < kItemCount; i++) {
  16246. items.push_back(
  16247. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16248. }
  16249. const std::string boundary = "----test-boundary";
  16250. auto content_length = detail::get_multipart_content_length(items, boundary);
  16251. auto provider = detail::make_multipart_content_provider(items, boundary);
  16252. // Drive the provider the same way write_content_with_progress does
  16253. size_t write_count = 0;
  16254. size_t total_bytes = 0;
  16255. DataSink sink;
  16256. size_t offset = 0;
  16257. sink.write = [&](const char *d, size_t l) -> bool {
  16258. (void)d;
  16259. write_count++;
  16260. total_bytes += l;
  16261. offset += l;
  16262. return true;
  16263. };
  16264. sink.is_writable = []() -> bool { return true; };
  16265. while (offset < content_length) {
  16266. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16267. }
  16268. EXPECT_EQ(content_length, total_bytes);
  16269. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16270. // With buffering into 64KB blocks, write_count should be much smaller.
  16271. auto segment_count = 3 * kItemCount + 1;
  16272. EXPECT_LT(write_count, segment_count / 10);
  16273. }
  16274. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16275. // Integration test: send many UploadFormDataItems and verify the server
  16276. // receives all of them correctly (#2410).
  16277. constexpr size_t kItemCount = 500;
  16278. auto handled = false;
  16279. Server svr;
  16280. svr.Post("/upload", [&](const Request &req, Response &res) {
  16281. EXPECT_EQ(kItemCount, req.form.fields.size());
  16282. for (size_t i = 0; i < kItemCount; i++) {
  16283. auto key = "field" + std::to_string(i);
  16284. auto val = "value" + std::to_string(i);
  16285. auto it = req.form.fields.find(key);
  16286. if (it != req.form.fields.end()) {
  16287. EXPECT_EQ(val, it->second.content);
  16288. } else {
  16289. ADD_FAILURE() << "Missing field: " << key;
  16290. }
  16291. }
  16292. res.set_content("ok", "text/plain");
  16293. handled = true;
  16294. });
  16295. auto port = svr.bind_to_any_port(HOST);
  16296. auto t = thread([&] { svr.listen_after_bind(); });
  16297. auto se = detail::scope_exit([&] {
  16298. svr.stop();
  16299. t.join();
  16300. ASSERT_FALSE(svr.is_running());
  16301. ASSERT_TRUE(handled);
  16302. });
  16303. svr.wait_until_ready();
  16304. UploadFormDataItems items;
  16305. items.reserve(kItemCount);
  16306. for (size_t i = 0; i < kItemCount; i++) {
  16307. items.push_back(
  16308. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16309. }
  16310. Client cli(HOST, port);
  16311. auto res = cli.Post("/upload", items);
  16312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16313. EXPECT_EQ(StatusCode::OK_200, res->status);
  16314. }
  16315. TEST(MultipartFormDataTest, MakeFileProvider) {
  16316. // Verify make_file_provider sends a file's contents correctly.
  16317. const std::string file_content(4096, 'Z');
  16318. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16319. {
  16320. std::ofstream ofs(tmp_path, std::ios::binary);
  16321. ofs.write(file_content.data(),
  16322. static_cast<std::streamsize>(file_content.size()));
  16323. }
  16324. auto handled = false;
  16325. Server svr;
  16326. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16327. const ContentReader &content_reader) {
  16328. ASSERT_TRUE(req.is_multipart_form_data());
  16329. std::vector<FormData> items;
  16330. content_reader(
  16331. [&](const FormData &file) {
  16332. items.push_back(file);
  16333. return true;
  16334. },
  16335. [&](const char *data, size_t data_length) {
  16336. items.back().content.append(data, data_length);
  16337. return true;
  16338. });
  16339. ASSERT_EQ(1u, items.size());
  16340. EXPECT_EQ("myfile", items[0].name);
  16341. EXPECT_EQ("data.bin", items[0].filename);
  16342. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16343. EXPECT_EQ(file_content, items[0].content);
  16344. handled = true;
  16345. });
  16346. auto port = svr.bind_to_any_port(HOST);
  16347. auto t = thread([&] { svr.listen_after_bind(); });
  16348. auto se = detail::scope_exit([&] {
  16349. svr.stop();
  16350. t.join();
  16351. ASSERT_FALSE(svr.is_running());
  16352. ASSERT_TRUE(handled);
  16353. std::remove(tmp_path.c_str());
  16354. });
  16355. svr.wait_until_ready();
  16356. FormDataProviderItems providers;
  16357. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16358. "application/octet-stream"));
  16359. Client cli(HOST, port);
  16360. auto res = cli.Post("/upload", {}, {}, providers);
  16361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16362. EXPECT_EQ(StatusCode::OK_200, res->status);
  16363. }
  16364. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16365. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16366. // (100) headers is rejected with a 400 Bad Request response.
  16367. Server svr;
  16368. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16369. res.set_content("ok", "text/plain");
  16370. });
  16371. thread t = thread([&] { svr.listen(HOST, PORT); });
  16372. auto se = detail::scope_exit([&] {
  16373. svr.stop();
  16374. t.join();
  16375. ASSERT_FALSE(svr.is_running());
  16376. });
  16377. svr.wait_until_ready();
  16378. // Build a multipart part with 101 custom headers (exceeding
  16379. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16380. std::stringstream body;
  16381. body << "--simpleboundary\r\n"
  16382. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16383. for (int i = 0; i < 101; i++) {
  16384. body << "X-Custom-Header-" << i << ": value\r\n";
  16385. }
  16386. body << "\r\n"
  16387. << "value1\r\n"
  16388. << "--simpleboundary--\r\n";
  16389. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16390. Client cli(HOST, PORT);
  16391. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16393. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16394. }
  16395. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16396. // A body that never contains the declared boundary must not be accumulated
  16397. // while the parser waits for it. Buffering it would also make every read
  16398. // rescan everything seen so far, which is quadratic in the body size.
  16399. Server svr;
  16400. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16401. res.set_content("ok", "text/plain");
  16402. });
  16403. auto port = svr.bind_to_any_port(HOST);
  16404. thread t = thread([&] { svr.listen_after_bind(); });
  16405. auto se = detail::scope_exit([&] {
  16406. svr.stop();
  16407. t.join();
  16408. ASSERT_FALSE(svr.is_running());
  16409. });
  16410. svr.wait_until_ready();
  16411. Client cli(HOST, port);
  16412. cli.set_read_timeout(60, 0);
  16413. cli.set_write_timeout(60, 0);
  16414. // '-' is the worst case: it matches the first character of the boundary, so
  16415. // every position has to be checked against it.
  16416. auto post_dashes = [&](size_t size) {
  16417. const std::string body(size, '-');
  16418. auto start = std::chrono::steady_clock::now();
  16419. auto res =
  16420. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16421. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16422. std::chrono::steady_clock::now() - start)
  16423. .count();
  16424. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16425. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16426. return ms;
  16427. };
  16428. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16429. // Windows.
  16430. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16431. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16432. // Comparing the two sizes rather than checking an absolute duration keeps
  16433. // this meaningful across build types and CI load, both of which move the
  16434. // absolute numbers by more than an order of magnitude. Four times the bytes
  16435. // costs about four times the time when parsing is linear, and about sixteen
  16436. // times when the body is buffered and rescanned.
  16437. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16438. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16439. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16440. << "ms, which suggests the body is being buffered and rescanned";
  16441. }
  16442. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16443. // A boundary can only be followed by CRLF or by "--", so anything else is
  16444. // malformed no matter what comes next. The parser must say so right away
  16445. // instead of buffering the rest of the declared body.
  16446. Server svr;
  16447. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16448. res.set_content("ok", "text/plain");
  16449. });
  16450. auto port = svr.bind_to_any_port(HOST);
  16451. thread t = thread([&] { svr.listen_after_bind(); });
  16452. auto se = detail::scope_exit([&] {
  16453. svr.stop();
  16454. t.join();
  16455. ASSERT_FALSE(svr.is_running());
  16456. });
  16457. svr.wait_until_ready();
  16458. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16459. // buffers instead of failing would still be waiting for the remaining bytes.
  16460. const std::string body = "--zzzz\r\n"
  16461. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16462. "\r\n"
  16463. "text1"
  16464. "\r\n--zzzzXX";
  16465. const std::string req = "POST /post HTTP/1.1\r\n"
  16466. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16467. "Content-Length: 1048576\r\n"
  16468. "\r\n" +
  16469. body;
  16470. std::string response;
  16471. ASSERT_TRUE(send_request(3, req, &response, port));
  16472. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16473. EXPECT_EQ("400", response.substr(9, 3));
  16474. }
  16475. // Posts a multipart body split into two writes, so that the server sees the
  16476. // split at whatever offset the caller chose, and expects the single "text1"
  16477. // field to come through.
  16478. static void expect_split_multipart_ok(const std::string &body1,
  16479. const std::string &body2) {
  16480. auto handled = false;
  16481. Server svr;
  16482. svr.Post("/post", [&](const Request &req, Response &) {
  16483. EXPECT_EQ(1u, req.form.fields.size());
  16484. EXPECT_EQ("text1", req.form.get_field("text1"));
  16485. handled = true;
  16486. });
  16487. auto port = svr.bind_to_any_port(HOST);
  16488. thread t = thread([&] { svr.listen_after_bind(); });
  16489. auto se = detail::scope_exit([&] {
  16490. svr.stop();
  16491. t.join();
  16492. ASSERT_FALSE(svr.is_running());
  16493. ASSERT_TRUE(handled);
  16494. });
  16495. svr.wait_until_ready();
  16496. // "Connection: close" makes the server close once it has answered, so the
  16497. // response drain ends immediately instead of idling until the read timeout.
  16498. const std::string head =
  16499. "POST /post HTTP/1.1\r\n"
  16500. "Host: localhost\r\n"
  16501. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16502. "Connection: close\r\n"
  16503. "Content-Length: " +
  16504. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16505. std::string response;
  16506. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16507. ASSERT_GE(response.size(), 12u) << "no response";
  16508. EXPECT_EQ("200", response.substr(9, 3));
  16509. }
  16510. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16511. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16512. // ignored, including when it does not arrive in the same read as the
  16513. // close-delimiter itself.
  16514. expect_split_multipart_ok("--zzzz\r\n"
  16515. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16516. "\r\n"
  16517. "text1"
  16518. "\r\n--zzzz--",
  16519. "\r\nthis epilogue must be ignored\r\n");
  16520. }
  16521. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16522. // The initial boundary may be preceded by a preamble of any length and may
  16523. // straddle a read boundary. Discarding data while waiting for it must not
  16524. // throw away a partial boundary sitting at the end of the buffer.
  16525. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16526. "zz\r\n"
  16527. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16528. "\r\n"
  16529. "text1"
  16530. "\r\n--zzzz--\r\n");
  16531. }
  16532. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16533. // The received boundary was only checked for being non-empty, so it could be
  16534. // as long as a header is allowed to be. The parser scans the body for
  16535. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16536. // costs a nearly full comparison at nearly every position, making the
  16537. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16538. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16539. Server svr;
  16540. svr.Post("/post", [](const Request &req, Response &res) {
  16541. EXPECT_EQ(1u, req.form.fields.size());
  16542. EXPECT_EQ("text1", req.form.get_field("text1"));
  16543. res.set_content("ok", "text/plain");
  16544. });
  16545. auto port = svr.bind_to_any_port(HOST);
  16546. thread t = thread([&] { svr.listen_after_bind(); });
  16547. auto se = detail::scope_exit([&] {
  16548. svr.stop();
  16549. t.join();
  16550. ASSERT_FALSE(svr.is_running());
  16551. });
  16552. svr.wait_until_ready();
  16553. Client cli(HOST, port);
  16554. auto post_with_boundary_of_length = [&](size_t len) {
  16555. const std::string boundary(len, 'a');
  16556. const std::string body =
  16557. "--" + boundary +
  16558. "\r\n"
  16559. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16560. "\r\n"
  16561. "text1"
  16562. "\r\n--" +
  16563. boundary + "--\r\n";
  16564. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16565. };
  16566. auto res = post_with_boundary_of_length(70);
  16567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16568. EXPECT_EQ(StatusCode::OK_200, res->status);
  16569. res = post_with_boundary_of_length(71);
  16570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16571. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16572. }
  16573. TEST(MakeFileBodyTest, Basic) {
  16574. const std::string file_content(4096, 'Z');
  16575. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16576. {
  16577. std::ofstream ofs(tmp_path, std::ios::binary);
  16578. ofs.write(file_content.data(),
  16579. static_cast<std::streamsize>(file_content.size()));
  16580. }
  16581. auto handled = false;
  16582. Server svr;
  16583. svr.Post("/upload", [&](const Request &req, Response &res) {
  16584. EXPECT_EQ(file_content, req.body);
  16585. handled = true;
  16586. res.status = StatusCode::OK_200;
  16587. });
  16588. auto port = svr.bind_to_any_port(HOST);
  16589. auto t = thread([&] { svr.listen_after_bind(); });
  16590. auto se = detail::scope_exit([&] {
  16591. svr.stop();
  16592. t.join();
  16593. ASSERT_FALSE(svr.is_running());
  16594. ASSERT_TRUE(handled);
  16595. std::remove(tmp_path.c_str());
  16596. });
  16597. svr.wait_until_ready();
  16598. auto fb = make_file_body(tmp_path);
  16599. ASSERT_GT(fb.first, 0u);
  16600. Client cli(HOST, port);
  16601. auto res =
  16602. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16604. EXPECT_EQ(StatusCode::OK_200, res->status);
  16605. }
  16606. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16607. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16608. {
  16609. std::ofstream ofs(path, std::ios::binary);
  16610. const std::string content(100, 'A');
  16611. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16612. }
  16613. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16614. auto body = make_file_body(path);
  16615. ASSERT_EQ(100u, body.first);
  16616. ASSERT_TRUE(static_cast<bool>(body.second));
  16617. // Rewritten shorter after its length was measured - and, on a server, after
  16618. // that length has already gone out as Content-Length.
  16619. {
  16620. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16621. const std::string content(10, 'A');
  16622. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16623. }
  16624. std::string written;
  16625. DataSink sink;
  16626. sink.write = [&](const char *d, size_t l) {
  16627. written.append(d, l);
  16628. return true;
  16629. };
  16630. // The provider has to report failure. write_content_with_progress() advances
  16631. // its offset only by what was written, so a provider that returns true
  16632. // without completing the length it promised is called again straight away,
  16633. // and again.
  16634. EXPECT_FALSE(body.second(0, body.first, sink));
  16635. EXPECT_EQ(std::string(10, 'A'), written);
  16636. }
  16637. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16638. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16639. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16640. {
  16641. std::ofstream ofs(path, std::ios::binary);
  16642. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16643. }
  16644. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16645. auto body = make_file_body(path);
  16646. ASSERT_EQ(content.size(), body.first);
  16647. ASSERT_TRUE(static_cast<bool>(body.second));
  16648. std::string written;
  16649. DataSink sink;
  16650. sink.write = [&](const char *d, size_t l) {
  16651. written.append(d, l);
  16652. return true;
  16653. };
  16654. EXPECT_TRUE(body.second(0, body.first, sink));
  16655. EXPECT_EQ(content, written);
  16656. }
  16657. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16658. static constexpr unsigned int number_of_tasks{1000000};
  16659. std::atomic_uint count{0};
  16660. std::unique_ptr<TaskQueue> task_queue{
  16661. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16662. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16663. auto queued = task_queue->enqueue(
  16664. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16665. EXPECT_TRUE(queued);
  16666. }
  16667. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16668. task_queue->shutdown();
  16669. #else
  16670. EXPECT_NO_THROW(task_queue->shutdown());
  16671. #endif
  16672. EXPECT_EQ(number_of_tasks, count.load());
  16673. }
  16674. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16675. static constexpr unsigned int number_of_tasks{1000000};
  16676. static constexpr unsigned int qlimit{2};
  16677. unsigned int queued_count{0};
  16678. std::atomic_uint count{0};
  16679. std::unique_ptr<TaskQueue> task_queue{
  16680. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16681. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16682. if (task_queue->enqueue(
  16683. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16684. queued_count++;
  16685. }
  16686. }
  16687. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16688. task_queue->shutdown();
  16689. #else
  16690. EXPECT_NO_THROW(task_queue->shutdown());
  16691. #endif
  16692. EXPECT_EQ(queued_count, count.load());
  16693. EXPECT_TRUE(queued_count <= number_of_tasks);
  16694. EXPECT_TRUE(queued_count >= qlimit);
  16695. }
  16696. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16697. // Use a short idle timeout so a dynamic thread spawns, times out and
  16698. // exits during the test, and the pool keeps working afterwards.
  16699. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16700. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16701. /*idle_timeout_sec=*/1}};
  16702. std::atomic_uint count{0};
  16703. std::condition_variable cv;
  16704. std::mutex mtx;
  16705. bool release = false;
  16706. // Block the base thread so the second task spawns a dynamic thread.
  16707. EXPECT_TRUE(task_queue->enqueue([&] {
  16708. std::unique_lock<std::mutex> lock(mtx);
  16709. while (!release) {
  16710. cv.wait(lock);
  16711. }
  16712. count++;
  16713. }));
  16714. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16715. // Let the dynamic thread finish its task and exceed the idle timeout.
  16716. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16717. {
  16718. std::unique_lock<std::mutex> lock(mtx);
  16719. release = true;
  16720. }
  16721. cv.notify_all();
  16722. // The pool must still accept and run tasks after the dynamic thread exited.
  16723. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16724. task_queue->shutdown();
  16725. EXPECT_EQ(3u, count.load());
  16726. }
  16727. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16728. static constexpr size_t number_of_tasks{32};
  16729. std::unique_ptr<TaskQueue> task_queue{
  16730. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16731. // Let the base threads go idle so the burst below finds them waiting.
  16732. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16733. std::mutex mtx;
  16734. std::condition_variable cv;
  16735. size_t running = 0;
  16736. bool release = false;
  16737. for (size_t i = 0; i < number_of_tasks; i++) {
  16738. EXPECT_TRUE(task_queue->enqueue([&] {
  16739. std::unique_lock<std::mutex> lock(mtx);
  16740. running++;
  16741. cv.notify_all();
  16742. cv.wait(lock, [&] { return release; });
  16743. }));
  16744. }
  16745. {
  16746. std::unique_lock<std::mutex> lock(mtx);
  16747. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16748. [&] { return running == number_of_tasks; }));
  16749. release = true;
  16750. }
  16751. cv.notify_all();
  16752. task_queue->shutdown();
  16753. }
  16754. TEST(TaskQueueTest, MaxQueuedRequests) {
  16755. static constexpr unsigned int qlimit{3};
  16756. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16757. std::condition_variable sem_cv;
  16758. std::mutex sem_mtx;
  16759. int credits = 0;
  16760. bool queued;
  16761. /* Fill up the queue with tasks that will block until we give them credits to
  16762. * complete. */
  16763. for (unsigned int n = 0; n <= qlimit;) {
  16764. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16765. std::unique_lock<std::mutex> lock(sem_mtx);
  16766. while (credits <= 0) {
  16767. sem_cv.wait(lock);
  16768. }
  16769. /* Consume the credit and signal the test code if they are all gone. */
  16770. if (--credits == 0) { sem_cv.notify_one(); }
  16771. });
  16772. if (n < qlimit) {
  16773. /* The first qlimit enqueues must succeed. */
  16774. EXPECT_TRUE(queued);
  16775. } else {
  16776. /* The last one will succeed only when the worker thread
  16777. * starts and dequeues the first blocking task. Although
  16778. * not necessary for the correctness of this test, we sleep for
  16779. * a short while to avoid busy waiting. */
  16780. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16781. }
  16782. if (queued) { n++; }
  16783. }
  16784. /* Further enqueues must fail since the queue is full. */
  16785. for (auto i = 0; i < 4; i++) {
  16786. queued = task_queue->enqueue([] {});
  16787. EXPECT_FALSE(queued);
  16788. }
  16789. /* Give the credits to allow the previous tasks to complete. */
  16790. {
  16791. std::unique_lock<std::mutex> lock(sem_mtx);
  16792. credits += qlimit + 1;
  16793. }
  16794. sem_cv.notify_all();
  16795. /* Wait for all the credits to be consumed. */
  16796. {
  16797. std::unique_lock<std::mutex> lock(sem_mtx);
  16798. while (credits > 0) {
  16799. sem_cv.wait(lock);
  16800. }
  16801. }
  16802. /* Check that we are able again to enqueue at least qlimit tasks. */
  16803. for (unsigned int i = 0; i < qlimit; i++) {
  16804. queued = task_queue->enqueue([] {});
  16805. EXPECT_TRUE(queued);
  16806. }
  16807. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16808. task_queue->shutdown();
  16809. #else
  16810. EXPECT_NO_THROW(task_queue->shutdown());
  16811. #endif
  16812. }
  16813. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16814. Server svr;
  16815. std::string method;
  16816. std::string body;
  16817. auto has_content_length = false;
  16818. auto has_transfer_encoding = false;
  16819. std::atomic<int> bad_requests{0};
  16820. // Leftover body bytes get parsed as a malformed request and answered with
  16821. // 400
  16822. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16823. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16824. });
  16825. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16826. res.set_redirect("/down", StatusCode::SeeOther_303);
  16827. });
  16828. svr.Get("/down", [&](const Request &req, Response &res) {
  16829. method = req.method;
  16830. body = req.body;
  16831. has_content_length = req.has_header("Content-Length");
  16832. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16833. res.set_content("ok", "text/plain");
  16834. });
  16835. auto port = svr.bind_to_any_port(HOST);
  16836. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16837. auto se = detail::scope_exit([&] {
  16838. svr.stop();
  16839. thread.join();
  16840. ASSERT_FALSE(svr.is_running());
  16841. });
  16842. svr.wait_until_ready();
  16843. const std::string payload = "SECRET-BODY";
  16844. auto check = [&](Client &cli, const Result &res) {
  16845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16846. EXPECT_EQ(StatusCode::OK_200, res->status);
  16847. EXPECT_EQ("ok", res->body);
  16848. EXPECT_EQ("GET", method);
  16849. EXPECT_TRUE(body.empty());
  16850. EXPECT_FALSE(has_content_length);
  16851. EXPECT_FALSE(has_transfer_encoding);
  16852. // Nothing of the original body may be left on the connection
  16853. auto res2 = cli.Get("/down");
  16854. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16855. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16856. EXPECT_EQ("ok", res2->body);
  16857. EXPECT_EQ(0, bad_requests);
  16858. };
  16859. // With content length
  16860. {
  16861. Client cli(HOST, port);
  16862. cli.set_keep_alive(true);
  16863. cli.set_follow_location(true);
  16864. auto res = cli.Post(
  16865. "/up", payload.size(),
  16866. [&](size_t offset, size_t length, DataSink &sink) {
  16867. return sink.write(payload.data() + offset, length);
  16868. },
  16869. "text/plain");
  16870. check(cli, res);
  16871. }
  16872. // Without content length (chunked)
  16873. {
  16874. Client cli(HOST, port);
  16875. cli.set_keep_alive(true);
  16876. cli.set_follow_location(true);
  16877. auto res = cli.Post(
  16878. "/up",
  16879. [&](size_t /*offset*/, DataSink &sink) {
  16880. sink.write(payload.data(), payload.size());
  16881. sink.done();
  16882. return true;
  16883. },
  16884. "text/plain");
  16885. check(cli, res);
  16886. }
  16887. }
  16888. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16889. Server svr;
  16890. std::string target;
  16891. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16892. // Echo the still-encoded name back in the Location
  16893. const std::string prefix = "/start/";
  16894. res.status = StatusCode::Found_302;
  16895. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16896. });
  16897. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16898. target = req.target;
  16899. res.set_content("ok", "text/plain");
  16900. });
  16901. auto port = svr.bind_to_any_port(HOST);
  16902. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16903. auto se = detail::scope_exit([&] {
  16904. svr.stop();
  16905. thread.join();
  16906. ASSERT_FALSE(svr.is_running());
  16907. });
  16908. svr.wait_until_ready();
  16909. // Decoding the Location path would turn the first four into a path
  16910. // separator, a query delimiter, a fragment delimiter and a different
  16911. // percent-encoded octet. The rest must keep reaching the server as they are.
  16912. const std::vector<std::string> names = {
  16913. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16914. };
  16915. for (auto path_encode : {true, false}) {
  16916. Client cli(HOST, port);
  16917. cli.set_follow_location(true);
  16918. cli.set_path_encode(path_encode);
  16919. for (const auto &name : names) {
  16920. target.clear();
  16921. auto res = cli.Get("/start/" + name);
  16922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16923. EXPECT_EQ(StatusCode::OK_200, res->status);
  16924. EXPECT_EQ("/dest/" + name, target);
  16925. }
  16926. }
  16927. }
  16928. TEST(RedirectTest, NotModifiedIsReturned) {
  16929. Server svr;
  16930. svr.Get("/cached", [](const Request &, Response &res) {
  16931. res.status = StatusCode::NotModified_304;
  16932. });
  16933. auto port = svr.bind_to_any_port(HOST);
  16934. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16935. auto se = detail::scope_exit([&] {
  16936. svr.stop();
  16937. thread.join();
  16938. ASSERT_FALSE(svr.is_running());
  16939. });
  16940. svr.wait_until_ready();
  16941. Client cli(HOST, port);
  16942. cli.set_follow_location(true);
  16943. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16945. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16946. }
  16947. TEST(RedirectTest, NoLocationIsReturned) {
  16948. Server svr;
  16949. svr.Get("/no-location", [](const Request &, Response &res) {
  16950. res.status = StatusCode::Found_302;
  16951. res.set_content("no location", "text/plain");
  16952. });
  16953. auto port = svr.bind_to_any_port(HOST);
  16954. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16955. auto se = detail::scope_exit([&] {
  16956. svr.stop();
  16957. thread.join();
  16958. ASSERT_FALSE(svr.is_running());
  16959. });
  16960. svr.wait_until_ready();
  16961. Client cli(HOST, port);
  16962. cli.set_follow_location(true);
  16963. auto res = cli.Get("/no-location");
  16964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16965. EXPECT_EQ(StatusCode::Found_302, res->status);
  16966. EXPECT_EQ("no location", res->body);
  16967. // The callbacks see the body of the response that is returned
  16968. auto handler_called = false;
  16969. auto progress_called = false;
  16970. std::string body;
  16971. auto res2 = cli.Get(
  16972. "/no-location",
  16973. [&](const Response &) {
  16974. handler_called = true;
  16975. return true;
  16976. },
  16977. [&](const char *data, size_t data_length) {
  16978. body.append(data, data_length);
  16979. return true;
  16980. },
  16981. [&](size_t, size_t) {
  16982. progress_called = true;
  16983. return true;
  16984. });
  16985. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16986. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16987. EXPECT_TRUE(handler_called);
  16988. EXPECT_TRUE(progress_called);
  16989. EXPECT_EQ("no location", body);
  16990. }
  16991. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16992. Server svr;
  16993. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16994. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16995. });
  16996. svr.Get("/hello", [](const Request &req, Response &res) {
  16997. res.set_content(req.get_param_value("key"), "text/plain");
  16998. });
  16999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17000. auto se = detail::scope_exit([&] {
  17001. svr.stop();
  17002. thread.join();
  17003. ASSERT_FALSE(svr.is_running());
  17004. });
  17005. svr.wait_until_ready();
  17006. {
  17007. Client cli(HOST, PORT);
  17008. cli.set_follow_location(true);
  17009. auto res = cli.Get("/");
  17010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17011. EXPECT_EQ(StatusCode::OK_200, res->status);
  17012. EXPECT_EQ("val&key2=val2", res->body);
  17013. }
  17014. }
  17015. #endif
  17016. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17017. Server svr;
  17018. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17019. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17020. });
  17021. svr.Get("/hello", [](const Request &req, Response &res) {
  17022. res.set_content(req.get_param_value("key"), "text/plain");
  17023. });
  17024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17025. auto se = detail::scope_exit([&] {
  17026. svr.stop();
  17027. thread.join();
  17028. ASSERT_FALSE(svr.is_running());
  17029. });
  17030. svr.wait_until_ready();
  17031. {
  17032. Client cli(HOST, PORT);
  17033. cli.set_follow_location(true);
  17034. auto res = cli.Get("/");
  17035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17036. EXPECT_EQ(StatusCode::OK_200, res->status);
  17037. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17038. }
  17039. }
  17040. TEST(RedirectTest, RedirectWithPlusInPath) {
  17041. Server svr;
  17042. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17043. res.set_redirect("/a+b");
  17044. });
  17045. // Route pattern uses regex; escape + as \\+
  17046. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17047. res.set_content(req.path, "text/plain");
  17048. });
  17049. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17050. auto se = detail::scope_exit([&] {
  17051. svr.stop();
  17052. thread.join();
  17053. ASSERT_FALSE(svr.is_running());
  17054. });
  17055. svr.wait_until_ready();
  17056. {
  17057. Client cli(HOST, PORT);
  17058. cli.set_follow_location(true);
  17059. auto res = cli.Get("/");
  17060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17061. EXPECT_EQ(StatusCode::OK_200, res->status);
  17062. EXPECT_EQ("/a+b", res->body);
  17063. }
  17064. }
  17065. TEST(RedirectTest, ResolveRelativeLocation) {
  17066. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17067. const std::vector<std::pair<std::string, std::string>> cases = {
  17068. {"g", "/b/c/g"},
  17069. {"./g", "/b/c/g"},
  17070. {"g/", "/b/c/g/"},
  17071. {"?y", "/b/c/d;p?y"},
  17072. {"g?y", "/b/c/g?y"},
  17073. {"#s", "/b/c/d;p?q#s"},
  17074. {"g#s", "/b/c/g#s"},
  17075. {"g?y#s", "/b/c/g?y#s"},
  17076. {";x", "/b/c/;x"},
  17077. {"g;x", "/b/c/g;x"},
  17078. {".", "/b/c/"},
  17079. {"./", "/b/c/"},
  17080. {"..", "/b/"},
  17081. {"../", "/b/"},
  17082. {"../g", "/b/g"},
  17083. {"../..", "/"},
  17084. {"../../", "/"},
  17085. {"../../g", "/g"},
  17086. {"../../../g", "/g"},
  17087. {"g.", "/b/c/g."},
  17088. {".g", "/b/c/.g"},
  17089. {"g..", "/b/c/g.."},
  17090. {"..g", "/b/c/..g"},
  17091. {"./../g", "/b/g"},
  17092. {"./g/.", "/b/c/g/"},
  17093. {"g/./h", "/b/c/g/h"},
  17094. {"g/../h", "/b/c/h"},
  17095. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17096. {"g;x=1/../y", "/b/c/y"},
  17097. {"g?y/./x", "/b/c/g?y/./x"},
  17098. {"g#s/../x", "/b/c/g#s/../x"},
  17099. // Not relative-path references, so left for parse_url.
  17100. {"/g", "/g"},
  17101. {"//g", "//g"},
  17102. {"http://g/x", "http://g/x"},
  17103. {"g:h", "g:h"},
  17104. };
  17105. for (const auto &c : cases) {
  17106. EXPECT_EQ(c.second,
  17107. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17108. << c.first;
  17109. }
  17110. }
  17111. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17112. Server svr;
  17113. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17114. res.set_redirect(req.get_param_value("to"));
  17115. });
  17116. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17117. res.set_content(req.target, "text/plain");
  17118. });
  17119. svr.Get("/other", [](const Request &req, Response &res) {
  17120. res.set_content(req.target, "text/plain");
  17121. });
  17122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17123. auto se = detail::scope_exit([&] {
  17124. svr.stop();
  17125. thread.join();
  17126. ASSERT_FALSE(svr.is_running());
  17127. });
  17128. svr.wait_until_ready();
  17129. const std::vector<std::pair<std::string, std::string>> cases = {
  17130. {"next", "/dir/next"},
  17131. {"./next?x=1", "/dir/next?x=1"},
  17132. {"../other", "/other"},
  17133. };
  17134. for (const auto &c : cases) {
  17135. Client cli(HOST, PORT);
  17136. cli.set_follow_location(true);
  17137. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17138. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17139. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17140. EXPECT_EQ(c.second, res->body) << c.first;
  17141. }
  17142. }
  17143. #ifdef CPPHTTPLIB_SSL_ENABLED
  17144. TEST(RedirectTest, Issue2185_Online) {
  17145. SSLClient client("github.com");
  17146. client.set_follow_location(true);
  17147. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17148. "Coollab-Windows.zip");
  17149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17150. EXPECT_EQ(StatusCode::OK_200, res->status);
  17151. EXPECT_EQ(9920427U, res->body.size());
  17152. }
  17153. #endif
  17154. TEST(VulnerabilityTest, CRLFInjection) {
  17155. Server svr;
  17156. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17157. res.set_content("Hello 1", "text/plain");
  17158. });
  17159. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17160. res.set_content("Hello 2", "text/plain");
  17161. });
  17162. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17163. res.set_content("Hello 3", "text/plain");
  17164. });
  17165. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17166. res.set_content("Hello 4", "text/plain");
  17167. });
  17168. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17169. for (const auto &x : req.headers) {
  17170. auto key = x.first;
  17171. EXPECT_STRNE("evil", key.c_str());
  17172. }
  17173. });
  17174. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17175. auto se = detail::scope_exit([&] {
  17176. svr.stop();
  17177. thread.join();
  17178. ASSERT_FALSE(svr.is_running());
  17179. });
  17180. svr.wait_until_ready();
  17181. {
  17182. Client cli(HOST, PORT);
  17183. cli.Post("/test1", "A=B",
  17184. "application/x-www-form-urlencoded\r\nevil: hello1");
  17185. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17186. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17187. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17188. }
  17189. }
  17190. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17191. auto server_thread = std::thread([] {
  17192. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17193. default_socket_options(srv);
  17194. sockaddr_in addr{};
  17195. addr.sin_family = AF_INET;
  17196. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17197. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17198. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17199. ::listen(srv, 1);
  17200. sockaddr_in cli_addr{};
  17201. socklen_t cli_len = sizeof(cli_addr);
  17202. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17203. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17204. std::string buf_all;
  17205. char buf[2048];
  17206. ssize_t n;
  17207. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17208. buf_all.append(buf, static_cast<size_t>(n));
  17209. size_t pos;
  17210. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17211. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17212. auto e = request_block.find("\r\n");
  17213. if (e != std::string::npos) {
  17214. auto request_line = request_block.substr(0, e);
  17215. std::string msg =
  17216. "CRLF injection detected in request line: '" + request_line + "'";
  17217. EXPECT_FALSE(true) << msg;
  17218. }
  17219. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17220. ::send(cli,
  17221. #ifdef _WIN32
  17222. static_cast<const char *>(resp.c_str()),
  17223. static_cast<int>(resp.size()),
  17224. #else
  17225. resp.c_str(), resp.size(),
  17226. #endif
  17227. 0);
  17228. buf_all.erase(0, pos + 4);
  17229. }
  17230. }
  17231. detail::close_socket(cli);
  17232. detail::close_socket(srv);
  17233. });
  17234. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17235. auto cli = Client("127.0.0.1", PORT + 1);
  17236. auto headers = Headers{
  17237. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17238. {"Connection", "keep-alive"}};
  17239. auto res = cli.Get("/hi", headers);
  17240. EXPECT_FALSE(res);
  17241. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17242. server_thread.join();
  17243. }
  17244. // A request rejected before any byte reaches the socket must fail right away
  17245. // instead of waiting for a response the server will never send.
  17246. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17247. // The kernel completes the TCP handshake from the listen backlog, so the
  17248. // client connects, but nothing ever reads, responds or closes.
  17249. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17250. default_socket_options(srv);
  17251. sockaddr_in addr{};
  17252. addr.sin_family = AF_INET;
  17253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17254. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17255. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17256. ASSERT_EQ(0, ::listen(srv, 8));
  17257. auto cli = Client("127.0.0.1", PORT + 1);
  17258. cli.set_read_timeout(10, 0);
  17259. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17260. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17261. std::chrono::steady_clock::now() - start)
  17262. .count();
  17263. };
  17264. {
  17265. Request req;
  17266. req.method = "GE T";
  17267. req.path = "/";
  17268. auto start = std::chrono::steady_clock::now();
  17269. auto res = cli.send(req);
  17270. EXPECT_FALSE(res);
  17271. EXPECT_EQ(Error::Write, res.error());
  17272. EXPECT_LT(elapsed_ms(start), 1000);
  17273. }
  17274. {
  17275. auto start = std::chrono::steady_clock::now();
  17276. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17277. EXPECT_FALSE(res);
  17278. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17279. EXPECT_LT(elapsed_ms(start), 1000);
  17280. }
  17281. EXPECT_FALSE(cli.is_socket_open());
  17282. detail::close_socket(srv);
  17283. }
  17284. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17285. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17286. default_socket_options(srv);
  17287. sockaddr_in addr{};
  17288. addr.sin_family = AF_INET;
  17289. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17290. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17291. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17292. ASSERT_EQ(0, ::listen(srv, 1));
  17293. std::string received;
  17294. auto server_thread = std::thread([&] {
  17295. auto sock = ::accept(srv, nullptr, nullptr);
  17296. if (sock == INVALID_SOCKET) { return; }
  17297. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17298. char buf[2048];
  17299. ssize_t n;
  17300. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17301. received.append(buf, static_cast<size_t>(n));
  17302. }
  17303. detail::close_socket(sock);
  17304. });
  17305. {
  17306. auto cli = Client("127.0.0.1", PORT + 1);
  17307. // "Z" sorts after the default headers, so writing straight to the socket
  17308. // would have sent the request line and those headers before the rejection.
  17309. auto handle =
  17310. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17311. EXPECT_FALSE(handle.is_valid());
  17312. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17313. }
  17314. server_thread.join();
  17315. detail::close_socket(srv);
  17316. EXPECT_TRUE(received.empty()) << received;
  17317. }
  17318. TEST(PathParamsTest, StaticMatch) {
  17319. const auto pattern = "/users/all";
  17320. detail::PathParamsMatcher matcher(pattern);
  17321. Request request;
  17322. request.path = "/users/all";
  17323. ASSERT_TRUE(matcher.match(request));
  17324. std::unordered_map<std::string, std::string> expected_params = {};
  17325. EXPECT_EQ(request.path_params, expected_params);
  17326. }
  17327. TEST(PathParamsTest, StaticMismatch) {
  17328. const auto pattern = "/users/all";
  17329. detail::PathParamsMatcher matcher(pattern);
  17330. Request request;
  17331. request.path = "/users/1";
  17332. ASSERT_FALSE(matcher.match(request));
  17333. }
  17334. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17335. const auto pattern = "/users/:id/subscriptions";
  17336. detail::PathParamsMatcher matcher(pattern);
  17337. Request request;
  17338. request.path = "/users/42/subscriptions";
  17339. ASSERT_TRUE(matcher.match(request));
  17340. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17341. EXPECT_EQ(request.path_params, expected_params);
  17342. }
  17343. TEST(PathParamsTest, SingleParamInTheEnd) {
  17344. const auto pattern = "/users/:id";
  17345. detail::PathParamsMatcher matcher(pattern);
  17346. Request request;
  17347. request.path = "/users/24";
  17348. ASSERT_TRUE(matcher.match(request));
  17349. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17350. EXPECT_EQ(request.path_params, expected_params);
  17351. }
  17352. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17353. const auto pattern = "/users/:id/";
  17354. detail::PathParamsMatcher matcher(pattern);
  17355. Request request;
  17356. request.path = "/users/42/";
  17357. ASSERT_TRUE(matcher.match(request));
  17358. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17359. EXPECT_EQ(request.path_params, expected_params);
  17360. }
  17361. TEST(PathParamsTest, EmptyParam) {
  17362. const auto pattern = "/users/:id/";
  17363. detail::PathParamsMatcher matcher(pattern);
  17364. Request request;
  17365. request.path = "/users//";
  17366. ASSERT_TRUE(matcher.match(request));
  17367. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17368. EXPECT_EQ(request.path_params, expected_params);
  17369. }
  17370. TEST(PathParamsTest, FragmentMismatch) {
  17371. const auto pattern = "/users/:id/";
  17372. detail::PathParamsMatcher matcher(pattern);
  17373. Request request;
  17374. request.path = "/admins/24/";
  17375. ASSERT_FALSE(matcher.match(request));
  17376. }
  17377. TEST(PathParamsTest, ExtraFragments) {
  17378. const auto pattern = "/users/:id";
  17379. detail::PathParamsMatcher matcher(pattern);
  17380. Request request;
  17381. request.path = "/users/42/subscriptions";
  17382. ASSERT_FALSE(matcher.match(request));
  17383. }
  17384. TEST(PathParamsTest, MissingTrailingParam) {
  17385. const auto pattern = "/users/:id";
  17386. detail::PathParamsMatcher matcher(pattern);
  17387. Request request;
  17388. request.path = "/users";
  17389. ASSERT_FALSE(matcher.match(request));
  17390. }
  17391. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17392. const auto pattern = "/users/:id/subscriptions";
  17393. detail::PathParamsMatcher matcher(pattern);
  17394. Request request;
  17395. request.path = "/users/subscriptions";
  17396. ASSERT_FALSE(matcher.match(request));
  17397. }
  17398. TEST(PathParamsTest, MultipleParams) {
  17399. const auto pattern = "/users/:userid/subscriptions/:subid";
  17400. detail::PathParamsMatcher matcher(pattern);
  17401. Request request;
  17402. request.path = "/users/42/subscriptions/2";
  17403. ASSERT_TRUE(matcher.match(request));
  17404. std::unordered_map<std::string, std::string> expected_params = {
  17405. {"userid", "42"}, {"subid", "2"}};
  17406. EXPECT_EQ(request.path_params, expected_params);
  17407. }
  17408. TEST(PathParamsTest, SequenceOfParams) {
  17409. const auto pattern = "/values/:x/:y/:z";
  17410. detail::PathParamsMatcher matcher(pattern);
  17411. Request request;
  17412. request.path = "/values/1/2/3";
  17413. ASSERT_TRUE(matcher.match(request));
  17414. std::unordered_map<std::string, std::string> expected_params = {
  17415. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17416. EXPECT_EQ(request.path_params, expected_params);
  17417. }
  17418. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17419. const auto pattern = "/prefix:suffix";
  17420. detail::PathParamsMatcher matcher(pattern);
  17421. Request request;
  17422. request.path = "/prefix:suffix";
  17423. ASSERT_TRUE(matcher.match(request));
  17424. const std::unordered_map<std::string, std::string> expected_params = {};
  17425. EXPECT_EQ(request.path_params, expected_params);
  17426. }
  17427. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17428. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17429. // calling thread's stack on a long enough path for a quantified pattern;
  17430. // RegexMatcher must refuse to run regex matching on paths beyond
  17431. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17432. detail::RegexMatcher matcher("/files/(.*)");
  17433. Request within_limit;
  17434. within_limit.path = "/files/" + std::string(10, 'A');
  17435. EXPECT_TRUE(matcher.match(within_limit));
  17436. Request over_limit;
  17437. over_limit.path =
  17438. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17439. EXPECT_FALSE(matcher.match(over_limit));
  17440. }
  17441. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17442. Server svr;
  17443. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17444. res.set_content("ok", "text/plain");
  17445. });
  17446. auto port = svr.bind_to_any_port(HOST);
  17447. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17448. auto se = detail::scope_exit([&] {
  17449. svr.stop();
  17450. thread.join();
  17451. ASSERT_FALSE(svr.is_running());
  17452. });
  17453. svr.wait_until_ready();
  17454. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17455. // request URI limit; this used to be able to crash the process.
  17456. std::string path =
  17457. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17458. std::string req = "GET " + path +
  17459. " HTTP/1.1\r\n"
  17460. "Host: " +
  17461. std::string(HOST) + ":" + std::to_string(port) +
  17462. "\r\n"
  17463. "Connection: close\r\n"
  17464. "\r\n";
  17465. std::string response;
  17466. ASSERT_TRUE(send_request(5, req, &response, port));
  17467. EXPECT_NE(std::string::npos, response.find("404"));
  17468. }
  17469. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17470. Server svr;
  17471. auto handler = [](const Request & /*req*/, Response &res) {
  17472. res.set_content("hit", "text/plain");
  17473. };
  17474. // No regex metacharacter, so this one is compared literally
  17475. svr.Get("/literal/route", handler);
  17476. // '.' is a regex metacharacter, so this one must keep regex semantics
  17477. svr.Get("/a.c", handler);
  17478. auto port = svr.bind_to_any_port(HOST);
  17479. std::thread t([&]() { svr.listen_after_bind(); });
  17480. auto se = detail::scope_exit([&] {
  17481. svr.stop();
  17482. t.join();
  17483. ASSERT_FALSE(svr.is_running());
  17484. });
  17485. svr.wait_until_ready();
  17486. Client cli(HOST, port);
  17487. struct {
  17488. const char *path;
  17489. int status;
  17490. } cases[] = {
  17491. {"/literal/route", StatusCode::OK_200},
  17492. {"/literal/routes", StatusCode::NotFound_404},
  17493. {"/literal/rout", StatusCode::NotFound_404},
  17494. {"/abc", StatusCode::OK_200},
  17495. {"/a.c", StatusCode::OK_200},
  17496. };
  17497. for (const auto &x : cases) {
  17498. auto res = cli.Get(x.path);
  17499. ASSERT_TRUE(res) << x.path;
  17500. EXPECT_EQ(x.status, res->status) << x.path;
  17501. }
  17502. }
  17503. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17504. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17505. // from exhausting the stack, so it must only constrain routes that actually
  17506. // run a regular expression. A literal route is matched by comparison and
  17507. // stays usable at any length.
  17508. Server svr;
  17509. const std::string pattern =
  17510. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17511. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17512. res.set_content("hit", "text/plain");
  17513. });
  17514. auto port = svr.bind_to_any_port(HOST);
  17515. std::thread t([&]() { svr.listen_after_bind(); });
  17516. auto se = detail::scope_exit([&] {
  17517. svr.stop();
  17518. t.join();
  17519. ASSERT_FALSE(svr.is_running());
  17520. });
  17521. svr.wait_until_ready();
  17522. Client cli(HOST, port);
  17523. auto res = cli.Get(pattern);
  17524. ASSERT_TRUE(res);
  17525. EXPECT_EQ(StatusCode::OK_200, res->status);
  17526. }
  17527. TEST(ParseUrlTest, VariousPatterns) {
  17528. {
  17529. detail::UrlComponents uc;
  17530. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17531. EXPECT_EQ("http", uc.scheme);
  17532. EXPECT_EQ("example.com", uc.host);
  17533. EXPECT_EQ("8080", uc.port);
  17534. EXPECT_EQ("/path", uc.path);
  17535. EXPECT_EQ("?q=1", uc.query);
  17536. }
  17537. {
  17538. detail::UrlComponents uc;
  17539. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17540. EXPECT_EQ("https", uc.scheme);
  17541. EXPECT_EQ("example.com", uc.host);
  17542. EXPECT_TRUE(uc.port.empty());
  17543. EXPECT_EQ("/path", uc.path);
  17544. }
  17545. {
  17546. detail::UrlComponents uc;
  17547. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17548. EXPECT_EQ("::1", uc.host);
  17549. EXPECT_EQ("8080", uc.port);
  17550. EXPECT_EQ("/path", uc.path);
  17551. }
  17552. {
  17553. detail::UrlComponents uc;
  17554. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17555. }
  17556. {
  17557. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17558. // the path while the connection still targets the bracketed host.
  17559. detail::UrlComponents uc;
  17560. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17561. }
  17562. {
  17563. detail::UrlComponents uc;
  17564. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17565. }
  17566. {
  17567. detail::UrlComponents uc;
  17568. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17569. EXPECT_EQ("::1", uc.host);
  17570. EXPECT_TRUE(uc.port.empty());
  17571. EXPECT_EQ("/path", uc.path);
  17572. }
  17573. {
  17574. detail::UrlComponents uc;
  17575. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17576. EXPECT_TRUE(uc.scheme.empty());
  17577. EXPECT_EQ("example.com", uc.host);
  17578. EXPECT_EQ("/path", uc.path);
  17579. EXPECT_EQ("?q=1", uc.query);
  17580. }
  17581. {
  17582. detail::UrlComponents uc;
  17583. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17584. EXPECT_TRUE(uc.host.empty());
  17585. EXPECT_EQ("/path", uc.path);
  17586. EXPECT_EQ("?q=1", uc.query);
  17587. }
  17588. {
  17589. detail::UrlComponents uc;
  17590. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17591. EXPECT_EQ("example.com", uc.host);
  17592. EXPECT_EQ("8080", uc.port);
  17593. }
  17594. {
  17595. // Unix socket path — must not be parsed as host
  17596. detail::UrlComponents uc;
  17597. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17598. EXPECT_TRUE(uc.host.empty());
  17599. }
  17600. {
  17601. detail::UrlComponents uc;
  17602. ASSERT_TRUE(detail::parse_url("", uc));
  17603. EXPECT_TRUE(uc.host.empty());
  17604. EXPECT_TRUE(uc.path.empty());
  17605. }
  17606. {
  17607. detail::UrlComponents uc;
  17608. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17609. }
  17610. {
  17611. detail::UrlComponents uc;
  17612. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17613. }
  17614. {
  17615. // Accepted by parse_url; callers restrict to http/https
  17616. detail::UrlComponents uc;
  17617. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17618. EXPECT_EQ("ftp", uc.scheme);
  17619. }
  17620. {
  17621. detail::UrlComponents uc;
  17622. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17623. }
  17624. {
  17625. detail::UrlComponents uc;
  17626. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17627. }
  17628. }
  17629. TEST(ParseUrlTest, FragmentHandling) {
  17630. {
  17631. detail::UrlComponents uc;
  17632. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17633. EXPECT_EQ("/path", uc.path);
  17634. EXPECT_TRUE(uc.query.empty());
  17635. }
  17636. {
  17637. detail::UrlComponents uc;
  17638. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17639. EXPECT_TRUE(uc.path.empty());
  17640. EXPECT_TRUE(uc.query.empty());
  17641. }
  17642. }
  17643. TEST(ParseUrlTest, UserinfoHandling) {
  17644. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17645. // parsers would see evil.com as the host.
  17646. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17647. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17648. for (auto url : urls) {
  17649. detail::UrlComponents uc;
  17650. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17651. }
  17652. }
  17653. TEST(ParseUrlTest, IPv6EdgeCases) {
  17654. {
  17655. detail::UrlComponents uc;
  17656. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17657. EXPECT_TRUE(uc.scheme.empty());
  17658. EXPECT_EQ("::1", uc.host);
  17659. EXPECT_EQ("8080", uc.port);
  17660. }
  17661. {
  17662. // Zone ID '%25' is not in [a-fA-F0-9:]
  17663. detail::UrlComponents uc;
  17664. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17665. }
  17666. }
  17667. TEST(ParseUrlTest, SchemeEdgeCases) {
  17668. {
  17669. detail::UrlComponents uc;
  17670. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17671. }
  17672. {
  17673. detail::UrlComponents uc;
  17674. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17675. }
  17676. {
  17677. detail::UrlComponents uc;
  17678. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17679. }
  17680. }
  17681. TEST(ParseUrlTest, PortEdgeCases) {
  17682. {
  17683. detail::UrlComponents uc;
  17684. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17685. EXPECT_TRUE(uc.port.empty());
  17686. EXPECT_EQ("/path", uc.path);
  17687. }
  17688. {
  17689. // parse_url accepts any port string; validation is done by parse_port
  17690. detail::UrlComponents uc;
  17691. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17692. EXPECT_EQ("abc", uc.port);
  17693. }
  17694. }
  17695. TEST(ParseUrlTest, WebSocketPatterns) {
  17696. {
  17697. detail::UrlComponents uc;
  17698. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17699. EXPECT_EQ("ws", uc.scheme);
  17700. EXPECT_EQ("echo.example.com", uc.host);
  17701. EXPECT_EQ("8080", uc.port);
  17702. EXPECT_EQ("/ws", uc.path);
  17703. }
  17704. {
  17705. detail::UrlComponents uc;
  17706. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17707. EXPECT_EQ("wss", uc.scheme);
  17708. EXPECT_EQ("echo.example.com", uc.host);
  17709. EXPECT_TRUE(uc.port.empty());
  17710. EXPECT_EQ("/ws", uc.path);
  17711. }
  17712. }
  17713. TEST(ParseUrlTest, QueryOnly) {
  17714. detail::UrlComponents uc;
  17715. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17716. EXPECT_TRUE(uc.host.empty());
  17717. EXPECT_TRUE(uc.path.empty());
  17718. EXPECT_EQ("?q=1&r=2", uc.query);
  17719. }
  17720. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17721. detail::UrlComponents uc;
  17722. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17723. EXPECT_TRUE(uc.scheme.empty());
  17724. EXPECT_EQ("example.com", uc.host);
  17725. EXPECT_EQ("443", uc.port);
  17726. EXPECT_EQ("/path", uc.path);
  17727. }
  17728. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17729. // If ipv6 regex working, regex match codepath is taken.
  17730. // else port will default to 80 in Client impl
  17731. int clientImplMagicPort = 80;
  17732. int port = 4321;
  17733. // above ports must be different to avoid false negative
  17734. EXPECT_NE(clientImplMagicPort, port);
  17735. std::string ipV6TestURL = "http://[ff06::c3]";
  17736. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17737. CLIENT_PRIVATE_KEY_FILE);
  17738. EXPECT_EQ(cli.port(), port);
  17739. }
  17740. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17741. auto file_path = "./www/dir/index.html";
  17742. auto dir_path = "./www/dir";
  17743. detail::FileStat stat_file(file_path);
  17744. EXPECT_TRUE(stat_file.is_file());
  17745. EXPECT_FALSE(stat_file.is_dir());
  17746. detail::FileStat stat_dir(dir_path);
  17747. EXPECT_FALSE(stat_dir.is_file());
  17748. EXPECT_TRUE(stat_dir.is_dir());
  17749. }
  17750. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17751. // IPv4 with default HTTP port (80)
  17752. EXPECT_EQ("example.com",
  17753. detail::make_host_and_port_string("example.com", 80, false));
  17754. // IPv4 with default HTTPS port (443)
  17755. EXPECT_EQ("example.com",
  17756. detail::make_host_and_port_string("example.com", 443, true));
  17757. // IPv4 with non-default HTTP port
  17758. EXPECT_EQ("example.com:8080",
  17759. detail::make_host_and_port_string("example.com", 8080, false));
  17760. // IPv4 with non-default HTTPS port
  17761. EXPECT_EQ("example.com:8443",
  17762. detail::make_host_and_port_string("example.com", 8443, true));
  17763. // IPv6 with default HTTP port (80)
  17764. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17765. // IPv6 with default HTTPS port (443)
  17766. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17767. // IPv6 with non-default HTTP port
  17768. EXPECT_EQ("[::1]:8080",
  17769. detail::make_host_and_port_string("::1", 8080, false));
  17770. // IPv6 with non-default HTTPS port
  17771. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17772. // IPv6 full address with default port
  17773. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17774. detail::make_host_and_port_string(
  17775. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17776. // IPv6 full address with non-default port
  17777. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17778. detail::make_host_and_port_string(
  17779. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17780. // IPv6 localhost with non-default port
  17781. EXPECT_EQ("[::1]:3000",
  17782. detail::make_host_and_port_string("::1", 3000, false));
  17783. // IPv6 with zone ID (link-local address) with default port
  17784. EXPECT_EQ("[fe80::1%eth0]",
  17785. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17786. // IPv6 with zone ID (link-local address) with non-default port
  17787. EXPECT_EQ("[fe80::1%eth0]:8080",
  17788. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17789. // Edge case: Port 443 with is_ssl=false (should add port)
  17790. EXPECT_EQ("example.com:443",
  17791. detail::make_host_and_port_string("example.com", 443, false));
  17792. // Edge case: Port 80 with is_ssl=true (should add port)
  17793. EXPECT_EQ("example.com:80",
  17794. detail::make_host_and_port_string("example.com", 80, true));
  17795. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17796. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17797. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17798. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17799. // Security fix: Already bracketed IPv6 should not get double brackets
  17800. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17801. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17802. EXPECT_EQ("[::1]:8080",
  17803. detail::make_host_and_port_string("[::1]", 8080, false));
  17804. EXPECT_EQ("[2001:db8::1]:8080",
  17805. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17806. EXPECT_EQ("[fe80::1%eth0]",
  17807. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17808. EXPECT_EQ("[fe80::1%eth0]:8080",
  17809. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17810. // Edge case: Empty host (should return as-is)
  17811. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17812. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17813. // This is a known limitation but shouldn't crash
  17814. EXPECT_EQ("[host:name]",
  17815. detail::make_host_and_port_string("host:name", 80, false));
  17816. // Port number edge cases (no validation, but should not crash)
  17817. EXPECT_EQ("example.com:0",
  17818. detail::make_host_and_port_string("example.com", 0, false));
  17819. EXPECT_EQ("example.com:-1",
  17820. detail::make_host_and_port_string("example.com", -1, false));
  17821. EXPECT_EQ("example.com:65535",
  17822. detail::make_host_and_port_string("example.com", 65535, false));
  17823. EXPECT_EQ("example.com:65536",
  17824. detail::make_host_and_port_string("example.com", 65536, false));
  17825. }
  17826. #ifdef CPPHTTPLIB_SSL_ENABLED
  17827. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17828. httplib::SSLClient cli("roblox.com", 443);
  17829. cli.set_follow_location(true);
  17830. auto res = cli.Get("/");
  17831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17832. EXPECT_EQ(StatusCode::OK_200, res->status);
  17833. }
  17834. #endif
  17835. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17836. Server svr;
  17837. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17838. EXPECT_EQ(res.status, 400);
  17839. });
  17840. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17841. auto se = detail::scope_exit([&] {
  17842. svr.stop();
  17843. thread.join();
  17844. ASSERT_FALSE(svr.is_running());
  17845. });
  17846. svr.wait_until_ready();
  17847. Client cli(HOST, PORT);
  17848. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17849. }
  17850. TEST(InvalidHeaderCharsTest, is_field_name) {
  17851. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17852. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17853. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17854. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17855. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17856. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17857. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17858. EXPECT_FALSE(detail::fields::is_field_name(""));
  17859. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17860. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17861. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17862. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17863. }
  17864. TEST(InvalidHeaderCharsTest, is_field_value) {
  17865. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17866. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17867. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17868. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17869. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17870. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17871. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17872. EXPECT_TRUE(detail::fields::is_field_value(""));
  17873. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17874. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17875. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17876. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17877. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17878. }
  17879. TEST(InvalidHeaderCharsTest, OnServer) {
  17880. Server svr;
  17881. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17882. std::string header = "Not Set";
  17883. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17884. res.set_header(header, "value");
  17885. res.set_content("Page Content Page Content", "text/plain");
  17886. });
  17887. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17888. std::string header = "Not Set";
  17889. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17890. res.set_header("X-Test", header);
  17891. res.set_content("Page Content Page Content", "text/plain");
  17892. });
  17893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17894. auto se = detail::scope_exit([&] {
  17895. svr.stop();
  17896. thread.join();
  17897. ASSERT_FALSE(svr.is_running());
  17898. });
  17899. svr.wait_until_ready();
  17900. Client cli(HOST, PORT);
  17901. {
  17902. auto res = cli.Get(
  17903. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17905. EXPECT_EQ("Page Content Page Content", res->body);
  17906. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17907. }
  17908. {
  17909. auto res = cli.Get(
  17910. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17912. EXPECT_EQ("Page Content Page Content", res->body);
  17913. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17914. }
  17915. }
  17916. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17917. auto handled = false;
  17918. Server svr;
  17919. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17920. thread t = thread([&] { svr.listen(HOST, PORT); });
  17921. auto se = detail::scope_exit([&] {
  17922. svr.stop();
  17923. t.join();
  17924. ASSERT_FALSE(svr.is_running());
  17925. ASSERT_FALSE(handled);
  17926. });
  17927. svr.wait_until_ready();
  17928. auto req = "POST /test HTTP/1.1\r\n"
  17929. "Content-Length: x\r\n"
  17930. "\r\n";
  17931. std::string response;
  17932. ASSERT_TRUE(send_request(1, req, &response));
  17933. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17934. response.substr(0, response.find("\r\n")));
  17935. }
  17936. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17937. // case-insensitive, and a server that receives a 100-continue expectation in
  17938. // an HTTP/1.0 request MUST ignore it.
  17939. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17940. std::string response;
  17941. ASSERT_TRUE(send_request(1, req, &response, port));
  17942. *got_100 = response.find("100 Continue") != std::string::npos;
  17943. }
  17944. class ExpectTokenTest : public ::testing::Test {
  17945. protected:
  17946. void SetUp() override {
  17947. svr_.Post("/p", [](const Request &, Response &res) {
  17948. res.set_content("ok", "text/plain");
  17949. });
  17950. port_ = svr_.bind_to_any_port(HOST);
  17951. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17952. svr_.wait_until_ready();
  17953. }
  17954. void TearDown() override {
  17955. svr_.stop();
  17956. if (thread_.joinable()) { thread_.join(); }
  17957. }
  17958. std::string request(const char *version, const char *expect_value) const {
  17959. return std::string("POST /p ") + version +
  17960. "\r\n"
  17961. "Host: localhost\r\n"
  17962. "Content-Length: 2\r\n"
  17963. "Connection: close\r\n"
  17964. "Expect: " +
  17965. expect_value +
  17966. "\r\n"
  17967. "\r\n"
  17968. "hi";
  17969. }
  17970. Server svr_;
  17971. int port_ = 0;
  17972. thread thread_;
  17973. };
  17974. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17975. bool got_100 = false;
  17976. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17977. EXPECT_TRUE(got_100);
  17978. }
  17979. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17980. bool got_100 = true;
  17981. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17982. EXPECT_FALSE(got_100);
  17983. }
  17984. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17985. bool got_100 = false;
  17986. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17987. EXPECT_TRUE(got_100);
  17988. }
  17989. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17990. bool got_100 = false;
  17991. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17992. EXPECT_TRUE(got_100);
  17993. }
  17994. // `100 Continue` is sent only when the server starts reading the body, so a
  17995. // request rejected before that never invites the client to send it. The
  17996. // requests below carry the expectation but withhold the body, as a client
  17997. // waiting for `100 Continue` would.
  17998. // A POST that expects `100 Continue` and withholds its two-byte body.
  17999. static std::string expect_headers_only(const std::string &path) {
  18000. return "POST " + path +
  18001. " HTTP/1.1\r\n"
  18002. "Host: localhost\r\n"
  18003. "Content-Length: 2\r\n"
  18004. "Expect: 100-continue\r\n"
  18005. "\r\n";
  18006. }
  18007. class ExpectLazyContinueTest : public ::testing::Test {
  18008. protected:
  18009. void SetUp() override {
  18010. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18011. if (req.path == "/pre-routing") {
  18012. res.status = StatusCode::Unauthorized_401;
  18013. return Server::HandlerResponse::Handled;
  18014. }
  18015. return Server::HandlerResponse::Unhandled;
  18016. });
  18017. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18018. if (req.matched_route == "/pre-request") {
  18019. res.status = StatusCode::Forbidden_403;
  18020. return Server::HandlerResponse::Handled;
  18021. }
  18022. return Server::HandlerResponse::Unhandled;
  18023. });
  18024. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18025. res.set_content("ok", "text/plain");
  18026. });
  18027. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18028. res.set_content("ok", "text/plain");
  18029. });
  18030. svr_.Post("/reader-used", [](const Request &, Response &res,
  18031. const ContentReader &content_reader) {
  18032. std::string body;
  18033. content_reader([&](const char *data, size_t len) {
  18034. body.append(data, len);
  18035. return true;
  18036. });
  18037. res.set_content(body, "text/plain");
  18038. });
  18039. svr_.Post("/reader-unused",
  18040. [](const Request &, Response &res, const ContentReader &) {
  18041. res.set_content("ignored", "text/plain");
  18042. });
  18043. port_ = svr_.bind_to_any_port(HOST);
  18044. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18045. svr_.wait_until_ready();
  18046. }
  18047. void TearDown() override {
  18048. svr_.stop();
  18049. if (thread_.joinable()) { thread_.join(); }
  18050. }
  18051. // Sends `req` and reads until the server closes the connection. Returns
  18052. // false if the read had to wait for the client-side timeout instead.
  18053. bool send_until_closed(const std::string &req, std::string *resp) const {
  18054. auto start = std::chrono::steady_clock::now();
  18055. if (!send_request(3, req, resp, port_)) { return false; }
  18056. auto elapsed = std::chrono::steady_clock::now() - start;
  18057. return elapsed < std::chrono::seconds(2);
  18058. }
  18059. // The final response comes without `100 Continue`, and the server closes
  18060. // the connection since the body may or may not follow.
  18061. void expect_final_without_interim(const std::string &path,
  18062. const char *status_line) const {
  18063. std::string resp;
  18064. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18065. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18066. EXPECT_EQ(0u, resp.find(status_line));
  18067. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18068. }
  18069. Server svr_;
  18070. int port_ = 0;
  18071. thread thread_;
  18072. };
  18073. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18074. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18075. }
  18076. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18077. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18078. }
  18079. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18080. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18081. }
  18082. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18083. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18084. }
  18085. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18086. // The body follows once `100 Continue` has had time to arrive.
  18087. auto req = expect_headers_only("/reader-used");
  18088. req.insert(req.size() - 2, "Connection: close\r\n");
  18089. std::string resp;
  18090. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18091. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18092. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18093. EXPECT_NE(std::string::npos, resp.find("hi"));
  18094. }
  18095. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18096. // Large enough for the client to add `Expect: 100-continue` itself.
  18097. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18098. std::atomic<bool> body_sent{false};
  18099. Client cli(HOST, port_);
  18100. auto res = cli.Post(
  18101. "/pre-request", length,
  18102. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18103. body_sent = true;
  18104. std::string chunk(len, 'x');
  18105. sink.write(chunk.data(), chunk.size());
  18106. return true;
  18107. },
  18108. "application/octet-stream");
  18109. ASSERT_TRUE(res);
  18110. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18111. EXPECT_FALSE(body_sent);
  18112. }
  18113. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18114. Server svr;
  18115. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18116. return StatusCode::ExpectationFailed_417;
  18117. });
  18118. svr.Post("/p", [](const Request &, Response &res) {
  18119. res.set_content("ok", "text/plain");
  18120. });
  18121. auto port = svr.bind_to_any_port(HOST);
  18122. thread t = thread([&] { svr.listen_after_bind(); });
  18123. auto se = detail::scope_exit([&] {
  18124. svr.stop();
  18125. t.join();
  18126. });
  18127. svr.wait_until_ready();
  18128. std::string resp;
  18129. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18130. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18131. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18132. // Exactly one response: the route handler must not run after the 417.
  18133. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18134. }
  18135. #ifndef _WIN32
  18136. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18137. static constexpr char reject[] = "Unauthorized";
  18138. static constexpr char accept[] = "Upload accepted";
  18139. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18140. Server svr;
  18141. svr.set_expect_100_continue_handler(
  18142. [](const Request & /*req*/, Response &res) {
  18143. res.status = StatusCode::Unauthorized_401;
  18144. res.set_content(reject, "text/plain");
  18145. return res.status;
  18146. });
  18147. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18148. res.set_content(accept, "text/plain");
  18149. });
  18150. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18151. auto se = detail::scope_exit([&] {
  18152. svr.stop();
  18153. thread.join();
  18154. ASSERT_FALSE(svr.is_running());
  18155. });
  18156. svr.wait_until_ready();
  18157. {
  18158. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18159. curl_easy_init(), &curl_easy_cleanup};
  18160. ASSERT_NE(curl, nullptr);
  18161. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18162. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18163. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18164. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18165. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18166. &curl_slist_free_all};
  18167. ASSERT_NE(list, nullptr);
  18168. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18169. struct read_data {
  18170. uint64_t read_size;
  18171. uint64_t total_size;
  18172. } data = {0, total_size};
  18173. using read_callback_t =
  18174. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18175. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18176. void *userdata) -> size_t {
  18177. read_data *d = (read_data *)userdata;
  18178. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18179. std::fill_n(ptr, size * nmemb, 'A');
  18180. d->read_size += size * nmemb;
  18181. return size * nmemb;
  18182. };
  18183. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18184. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18185. std::vector<char> buffer;
  18186. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18187. using write_callback_t =
  18188. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18189. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18190. void *userdata) -> size_t {
  18191. std::vector<char> *buf = (std::vector<char> *)userdata;
  18192. buf->reserve(buf->size() + size * nmemb + 1);
  18193. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18194. return size * nmemb;
  18195. };
  18196. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18197. {
  18198. const auto res = curl_easy_perform(curl.get());
  18199. ASSERT_EQ(res, CURLE_OK);
  18200. }
  18201. {
  18202. auto response_code = long{};
  18203. const auto res =
  18204. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18205. ASSERT_EQ(res, CURLE_OK);
  18206. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18207. }
  18208. {
  18209. auto dl = curl_off_t{};
  18210. const auto res =
  18211. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18212. ASSERT_EQ(res, CURLE_OK);
  18213. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18214. }
  18215. {
  18216. buffer.push_back('\0');
  18217. ASSERT_STRCASEEQ(buffer.data(), reject);
  18218. }
  18219. }
  18220. }
  18221. #endif
  18222. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18223. // Regression test for #2458.
  18224. //
  18225. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18226. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18227. // ticket can make the client socket spuriously readable during the
  18228. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18229. // the client withholds the body and then blocks reading a response that never
  18230. // comes, failing with `Failed to read connection`.
  18231. //
  18232. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18233. // within the timeout. This raw OpenSSL server deliberately never sends
  18234. // `100 Continue`; the client must still deliver the body and receive 200.
  18235. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18236. signal(SIGPIPE, SIG_IGN);
  18237. const auto port = PORT + 4;
  18238. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18239. ASSERT_NE(srv, INVALID_SOCKET);
  18240. int opt = 1;
  18241. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18242. sockaddr_in addr{};
  18243. addr.sin_family = AF_INET;
  18244. addr.sin_port = htons(static_cast<uint16_t>(port));
  18245. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18246. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18247. ASSERT_EQ(0, ::listen(srv, 1));
  18248. std::atomic<size_t> server_body_bytes{0};
  18249. auto server_thread = std::thread([&] {
  18250. sockaddr_in cli_addr{};
  18251. socklen_t cli_len = sizeof(cli_addr);
  18252. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18253. if (cli == INVALID_SOCKET) { return; }
  18254. // Bound the lifetime of the server side so a buggy client (which never
  18255. // sends the body) cannot make this thread block forever on join.
  18256. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18257. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18258. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18259. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18260. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18261. SSL *ssl = SSL_new(ctx);
  18262. SSL_set_fd(ssl, static_cast<int>(cli));
  18263. if (SSL_accept(ssl) > 0) {
  18264. // Read the request headers. Reading here also flushes the TLS 1.3
  18265. // session tickets to the client. Deliberately do NOT send
  18266. // `100 Continue`.
  18267. std::string buf;
  18268. char tmp[1024];
  18269. while (buf.find("\r\n\r\n") == std::string::npos) {
  18270. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18271. if (n <= 0) { break; }
  18272. buf.append(tmp, static_cast<size_t>(n));
  18273. }
  18274. // A correct client sends the body now; count what arrives.
  18275. auto pos = buf.find("\r\n\r\n");
  18276. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18277. while (body < 4096) {
  18278. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18279. if (n <= 0) { break; }
  18280. body += static_cast<size_t>(n);
  18281. }
  18282. server_body_bytes = body;
  18283. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18284. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18285. SSL_shutdown(ssl);
  18286. }
  18287. SSL_free(ssl);
  18288. detail::close_socket(cli);
  18289. SSL_CTX_free(ctx);
  18290. });
  18291. auto se = detail::scope_exit([&] {
  18292. server_thread.join();
  18293. detail::close_socket(srv);
  18294. });
  18295. SSLClient cli("127.0.0.1", port);
  18296. cli.enable_server_certificate_verification(false);
  18297. cli.set_connection_timeout(5, 0);
  18298. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18299. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18300. std::string body(4096, 'A');
  18301. auto res = cli.Put("/api/test", body, "application/json");
  18302. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18303. EXPECT_EQ(StatusCode::OK_200, res->status);
  18304. EXPECT_EQ(body.size(), server_body_bytes.load());
  18305. }
  18306. #endif
  18307. template <typename S, typename C>
  18308. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18309. svr.Get("/stream", [&](const Request &, Response &res) {
  18310. auto data = new std::string("01234567890123456789");
  18311. res.set_content_provider(
  18312. data->size(), "text/plain",
  18313. [&, data](size_t offset, size_t length, DataSink &sink) {
  18314. const size_t DATA_CHUNK_SIZE = 4;
  18315. const auto &d = *data;
  18316. std::this_thread::sleep_for(std::chrono::seconds(1));
  18317. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18318. return true;
  18319. },
  18320. [data](bool success) {
  18321. EXPECT_FALSE(success);
  18322. delete data;
  18323. });
  18324. });
  18325. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18326. auto i = new size_t(0);
  18327. res.set_content_provider(
  18328. "text/plain",
  18329. [i](size_t, DataSink &sink) {
  18330. if (*i < 5) {
  18331. std::this_thread::sleep_for(std::chrono::seconds(1));
  18332. sink.write("abcd", 4);
  18333. (*i)++;
  18334. } else {
  18335. sink.done();
  18336. }
  18337. return true;
  18338. },
  18339. [i](bool success) {
  18340. EXPECT_FALSE(success);
  18341. delete i;
  18342. });
  18343. });
  18344. svr.Get("/chunked", [&](const Request &, Response &res) {
  18345. auto i = new size_t(0);
  18346. res.set_chunked_content_provider(
  18347. "text/plain",
  18348. [i](size_t, DataSink &sink) {
  18349. if (*i < 5) {
  18350. std::this_thread::sleep_for(std::chrono::seconds(1));
  18351. sink.os << "abcd";
  18352. (*i)++;
  18353. } else {
  18354. sink.done();
  18355. }
  18356. return true;
  18357. },
  18358. [i](bool success) {
  18359. EXPECT_FALSE(success);
  18360. delete i;
  18361. });
  18362. });
  18363. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18364. auto se = detail::scope_exit([&] {
  18365. svr.stop();
  18366. listen_thread.join();
  18367. ASSERT_FALSE(svr.is_running());
  18368. });
  18369. svr.wait_until_ready();
  18370. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18371. {
  18372. auto start = std::chrono::steady_clock::now();
  18373. auto res = cli.Get("/stream");
  18374. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18375. std::chrono::steady_clock::now() - start)
  18376. .count();
  18377. ASSERT_FALSE(res);
  18378. EXPECT_EQ(Error::Read, res.error());
  18379. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18380. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18381. }
  18382. {
  18383. auto start = std::chrono::steady_clock::now();
  18384. auto res = cli.Get("/stream_without_length");
  18385. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18386. std::chrono::steady_clock::now() - start)
  18387. .count();
  18388. ASSERT_FALSE(res);
  18389. EXPECT_EQ(Error::Read, res.error());
  18390. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18391. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18392. }
  18393. {
  18394. auto start = std::chrono::steady_clock::now();
  18395. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18396. EXPECT_EQ("abcd", string(data, data_length));
  18397. return true;
  18398. });
  18399. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18400. std::chrono::steady_clock::now() - start)
  18401. .count();
  18402. ASSERT_FALSE(res);
  18403. EXPECT_EQ(Error::Read, res.error());
  18404. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18405. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18406. }
  18407. }
  18408. TEST(MaxTimeoutTest, ContentStream) {
  18409. time_t timeout = 2000;
  18410. time_t threshold = 200;
  18411. Server svr;
  18412. Client cli("localhost", PORT);
  18413. max_timeout_test(svr, cli, timeout, threshold);
  18414. }
  18415. #ifdef CPPHTTPLIB_SSL_ENABLED
  18416. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18417. time_t timeout = 2000;
  18418. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18420. SSLClient cli("localhost", PORT);
  18421. cli.enable_server_certificate_verification(false);
  18422. max_timeout_test(svr, cli, timeout, threshold);
  18423. }
  18424. #endif
  18425. class EventDispatcher {
  18426. public:
  18427. EventDispatcher() {}
  18428. bool wait_event(DataSink *sink) {
  18429. unique_lock<mutex> lk(m_);
  18430. int id = id_;
  18431. // Wait with timeout to prevent hanging if client disconnects
  18432. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18433. [&] { return cid_ == id; })) {
  18434. return false; // Timeout occurred
  18435. }
  18436. sink->write(message_.data(), message_.size());
  18437. return true;
  18438. }
  18439. void send_event(const string &message) {
  18440. lock_guard<mutex> lk(m_);
  18441. cid_ = id_++;
  18442. message_ = message;
  18443. cv_.notify_all();
  18444. }
  18445. private:
  18446. mutex m_;
  18447. condition_variable cv_;
  18448. atomic_int id_{0};
  18449. atomic_int cid_{-1};
  18450. string message_;
  18451. };
  18452. TEST(ClientInThreadTest, Issue2068) {
  18453. EventDispatcher ed;
  18454. Server svr;
  18455. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18456. res.set_chunked_content_provider("text/event-stream",
  18457. [&](size_t /*offset*/, DataSink &sink) {
  18458. return ed.wait_event(&sink);
  18459. });
  18460. });
  18461. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18462. svr.wait_until_ready();
  18463. thread event_thread([&] {
  18464. int id = 0;
  18465. while (svr.is_running()) {
  18466. this_thread::sleep_for(chrono::milliseconds(500));
  18467. std::stringstream ss;
  18468. ss << "data: " << id << "\n\n";
  18469. ed.send_event(ss.str());
  18470. id++;
  18471. }
  18472. });
  18473. auto se = detail::scope_exit([&] {
  18474. svr.stop();
  18475. listen_thread.join();
  18476. event_thread.join();
  18477. ASSERT_FALSE(svr.is_running());
  18478. });
  18479. {
  18480. auto client = detail::make_unique<Client>(HOST, PORT);
  18481. client->set_read_timeout(std::chrono::minutes(10));
  18482. std::atomic<bool> stop{false};
  18483. std::thread t([&] {
  18484. client->Get("/event1",
  18485. [&](const char *, size_t) -> bool { return !stop; });
  18486. });
  18487. std::this_thread::sleep_for(std::chrono::seconds(2));
  18488. stop = true;
  18489. client->stop();
  18490. t.join();
  18491. // Reset client after thread has finished
  18492. client.reset();
  18493. }
  18494. }
  18495. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18496. auto handled = false;
  18497. Server svr;
  18498. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18499. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18500. auto se = detail::scope_exit([&] {
  18501. svr.stop();
  18502. t.join();
  18503. ASSERT_FALSE(svr.is_running());
  18504. ASSERT_FALSE(handled);
  18505. });
  18506. svr.wait_until_ready();
  18507. // Two Content-Length headers with different values — must be rejected
  18508. auto req = "POST /test HTTP/1.1\r\n"
  18509. "Content-Length: 5\r\n"
  18510. "Content-Length: 10\r\n"
  18511. "\r\n"
  18512. "hello";
  18513. std::string response;
  18514. ASSERT_TRUE(send_request(1, req, &response));
  18515. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18516. response.substr(0, response.find("\r\n")));
  18517. }
  18518. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18519. auto handled = false;
  18520. Server svr;
  18521. svr.Post("/test", [&](const Request &, Response &res) {
  18522. handled = true;
  18523. res.set_content("ok", "text/plain");
  18524. });
  18525. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18526. auto se = detail::scope_exit([&] {
  18527. svr.stop();
  18528. t.join();
  18529. ASSERT_FALSE(svr.is_running());
  18530. ASSERT_TRUE(handled);
  18531. });
  18532. svr.wait_until_ready();
  18533. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18534. auto req = "POST /test HTTP/1.1\r\n"
  18535. "Host: localhost\r\n"
  18536. "Content-Length: 5\r\n"
  18537. "Content-Length: 5\r\n"
  18538. "\r\n"
  18539. "hello";
  18540. std::string response;
  18541. ASSERT_TRUE(send_request(1, req, &response));
  18542. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18543. }
  18544. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18545. Server svr;
  18546. svr.Get("/test", [](const Request &, Response &res) {
  18547. res.set_content("ok", "text/plain");
  18548. });
  18549. auto port = svr.bind_to_any_port(HOST);
  18550. thread t = thread([&] { svr.listen_after_bind(); });
  18551. auto se = detail::scope_exit([&] {
  18552. svr.stop();
  18553. t.join();
  18554. ASSERT_FALSE(svr.is_running());
  18555. });
  18556. svr.wait_until_ready();
  18557. auto status_line = [&](const std::string &host_lines) {
  18558. std::string res;
  18559. send_request(
  18560. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18561. &res, port);
  18562. return res.substr(0, res.find("\r\n"));
  18563. };
  18564. const char *accepted[] = {
  18565. "Host: localhost\r\n",
  18566. "Host: a.example:8080\r\n",
  18567. "Host: my_service\r\n",
  18568. "Host: [::1]:8080\r\n",
  18569. "Host: [fe80::1%25eth0]\r\n",
  18570. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18571. };
  18572. for (auto host_lines : accepted) {
  18573. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18574. }
  18575. const char *rejected[] = {
  18576. "Host: a.example\r\nHost: b.example\r\n",
  18577. "Host: a.example\r\nHost: a.example\r\n",
  18578. "Host: a@b.example\r\n",
  18579. "Host: a.example/b\r\n",
  18580. "Host: a.example\\b\r\n",
  18581. "Host: a.example?b\r\n",
  18582. "Host: a.example#b\r\n",
  18583. "Host: a.example b.example\r\n",
  18584. };
  18585. for (auto host_lines : rejected) {
  18586. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18587. << host_lines;
  18588. }
  18589. }
  18590. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18591. Server svr;
  18592. svr.Get("/", [](const Request &req, Response &res) {
  18593. EXPECT_EQ(2U, req.trailers.size());
  18594. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18595. // Denied
  18596. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18597. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18598. // Accepted
  18599. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18600. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18601. EXPECT_TRUE(req.has_trailer("X-World"));
  18602. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18603. res.set_content("ok", "text/plain");
  18604. });
  18605. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18606. auto se = detail::scope_exit([&] {
  18607. svr.stop();
  18608. t.join();
  18609. ASSERT_FALSE(svr.is_running());
  18610. });
  18611. svr.wait_until_ready();
  18612. const std::string req = "GET / HTTP/1.1\r\n"
  18613. "Transfer-Encoding: chunked\r\n"
  18614. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18615. "\r\n"
  18616. "0\r\n"
  18617. "Content-Length: 10\r\n"
  18618. "Host: internal.local\r\n"
  18619. "Content-Type: malicious/content\r\n"
  18620. "Cookie: any\r\n"
  18621. "Set-Cookie: any\r\n"
  18622. "X-Forwarded-For: attacker.com\r\n"
  18623. "X-Real-Ip: 1.1.1.1\r\n"
  18624. "X-Hello: hello\r\n"
  18625. "X-World: world\r\n"
  18626. "\r\n";
  18627. std::string res;
  18628. ASSERT_TRUE(send_request(1, req, &res));
  18629. }
  18630. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18631. // several field lines, and the combined value is what has to be parsed. A
  18632. // Trailer field split across lines therefore declares every name it lists;
  18633. // reading only the first line silently drops the trailers the later lines
  18634. // declare. The prohibited-trailer filter still applies to every line.
  18635. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18636. Server svr;
  18637. size_t observed_trailer_count = 0;
  18638. std::string observed_hello;
  18639. std::string observed_world;
  18640. bool observed_content_length = true;
  18641. svr.Get("/", [&](const Request &req, Response &res) {
  18642. observed_trailer_count = req.trailers.size();
  18643. observed_hello = req.get_trailer_value("X-Hello");
  18644. observed_world = req.get_trailer_value("X-World");
  18645. observed_content_length = req.has_trailer("Content-Length");
  18646. res.set_content("ok", "text/plain");
  18647. });
  18648. auto port = svr.bind_to_any_port(HOST);
  18649. thread t = thread([&]() { svr.listen_after_bind(); });
  18650. auto se = detail::scope_exit([&] {
  18651. svr.stop();
  18652. t.join();
  18653. ASSERT_FALSE(svr.is_running());
  18654. });
  18655. svr.wait_until_ready();
  18656. const std::string req = "GET / HTTP/1.1\r\n"
  18657. "Host: localhost\r\n"
  18658. "Transfer-Encoding: chunked\r\n"
  18659. "Trailer: X-Hello\r\n"
  18660. "Trailer: X-World, Content-Length\r\n"
  18661. "\r\n"
  18662. "0\r\n"
  18663. "X-Hello: hello\r\n"
  18664. "X-World: world\r\n"
  18665. "Content-Length: 10\r\n"
  18666. "\r\n";
  18667. std::string res;
  18668. ASSERT_TRUE(send_request(1, req, &res, port));
  18669. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18670. // Accepted: both field lines contribute to the declared set
  18671. EXPECT_EQ(2U, observed_trailer_count);
  18672. EXPECT_EQ(observed_hello, "hello");
  18673. EXPECT_EQ(observed_world, "world");
  18674. // Denied: a prohibited name stays prohibited on a later field line
  18675. EXPECT_FALSE(observed_content_length);
  18676. }
  18677. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18678. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18679. // unbounded run of fields that are never declared, because the counter would
  18680. // only advance for declared fields.
  18681. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18682. Server svr;
  18683. bool handler_called = false;
  18684. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18685. handler_called = true;
  18686. res.set_content("ok", "text/plain");
  18687. });
  18688. auto port = svr.bind_to_any_port(HOST);
  18689. thread t = thread([&]() { svr.listen_after_bind(); });
  18690. auto se = detail::scope_exit([&] {
  18691. svr.stop();
  18692. t.join();
  18693. ASSERT_FALSE(svr.is_running());
  18694. });
  18695. svr.wait_until_ready();
  18696. // Declare nothing, then send far more undeclared trailer fields than the
  18697. // header-count limit. Parsing must stop and reject the request rather than
  18698. // read every line.
  18699. std::string req = "GET / HTTP/1.1\r\n"
  18700. "Transfer-Encoding: chunked\r\n"
  18701. "\r\n"
  18702. "0\r\n";
  18703. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18704. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18705. }
  18706. req += "\r\n";
  18707. std::string res;
  18708. ASSERT_TRUE(send_request(1, req, &res, port));
  18709. // The request is rejected before the handler runs.
  18710. EXPECT_FALSE(handler_called);
  18711. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18712. }
  18713. // The set of declared trailer names is capped so a peer cannot grow it without
  18714. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18715. // declared past the cap is not honored, even if the field is actually sent.
  18716. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18717. Server svr;
  18718. // One name inside the cap and one past it, so the test tracks the cap rather
  18719. // than a fixed count.
  18720. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18721. const std::string within_cap_name = "X-T-0";
  18722. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18723. bool observed_within_cap = false;
  18724. bool observed_past_cap = false;
  18725. svr.Get("/", [&](const Request &req, Response &res) {
  18726. observed_within_cap = req.has_trailer(within_cap_name);
  18727. observed_past_cap = req.has_trailer(past_cap_name);
  18728. res.set_content("ok", "text/plain");
  18729. });
  18730. auto port = svr.bind_to_any_port(HOST);
  18731. thread t = thread([&]() { svr.listen_after_bind(); });
  18732. auto se = detail::scope_exit([&] {
  18733. svr.stop();
  18734. t.join();
  18735. ASSERT_FALSE(svr.is_running());
  18736. });
  18737. svr.wait_until_ready();
  18738. // Declare more trailer names than the cap in a single Trailer field, then
  18739. // actually send the first (within the cap) and the last (past it).
  18740. std::string trailer_decl = "Trailer: ";
  18741. for (int i = 0; i < declared_count; i++) {
  18742. if (i != 0) { trailer_decl += ", "; }
  18743. trailer_decl += "X-T-" + std::to_string(i);
  18744. }
  18745. trailer_decl += "\r\n";
  18746. const std::string req = "GET / HTTP/1.1\r\n"
  18747. "Host: localhost\r\n"
  18748. "Transfer-Encoding: chunked\r\n" +
  18749. trailer_decl +
  18750. "\r\n"
  18751. "0\r\n" +
  18752. within_cap_name + ": a\r\n" + past_cap_name +
  18753. ": b\r\n"
  18754. "\r\n";
  18755. std::string res;
  18756. ASSERT_TRUE(send_request(1, req, &res, port));
  18757. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18758. // A name within the cap is honored; one declared past the cap is dropped.
  18759. EXPECT_TRUE(observed_within_cap);
  18760. EXPECT_FALSE(observed_past_cap);
  18761. }
  18762. // A direct client that is not listed in trusted_proxies must not be able to
  18763. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18764. // the peer address on the actual TCP connection determines whether the
  18765. // header is honored.
  18766. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18767. Server svr;
  18768. // Deliberately does NOT include the loopback address the test client
  18769. // actually connects from, so the direct connection is not a trusted proxy.
  18770. svr.set_trusted_proxies({"203.0.113.66"});
  18771. std::string observed_remote_addr;
  18772. svr.Get("/ip", [&](const Request &req, Response &res) {
  18773. observed_remote_addr = req.remote_addr;
  18774. res.set_content("ok", "text/plain");
  18775. });
  18776. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18777. auto se = detail::scope_exit([&] {
  18778. svr.stop();
  18779. t.join();
  18780. ASSERT_FALSE(svr.is_running());
  18781. });
  18782. svr.wait_until_ready();
  18783. Client cli(HOST, PORT);
  18784. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18786. EXPECT_EQ(StatusCode::OK_200, res->status);
  18787. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18788. // ignored entirely and the real connection-level address retained.
  18789. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18790. observed_remote_addr == "127.0.0.1");
  18791. }
  18792. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18793. Server svr;
  18794. std::string observed_remote_addr;
  18795. std::string observed_xff;
  18796. svr.Get("/ip", [&](const Request &req, Response &res) {
  18797. observed_remote_addr = req.remote_addr;
  18798. observed_xff = req.get_header_value("X-Forwarded-For");
  18799. res.set_content("ok", "text/plain");
  18800. });
  18801. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18802. auto se = detail::scope_exit([&] {
  18803. svr.stop();
  18804. t.join();
  18805. ASSERT_FALSE(svr.is_running());
  18806. });
  18807. svr.wait_until_ready();
  18808. Client cli(HOST, PORT);
  18809. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18811. EXPECT_EQ(StatusCode::OK_200, res->status);
  18812. EXPECT_EQ(observed_xff, "203.0.113.66");
  18813. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18814. observed_remote_addr == "127.0.0.1");
  18815. }
  18816. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18817. Server svr;
  18818. svr.set_trusted_proxies({"203.0.113.66"});
  18819. std::string observed_remote_addr;
  18820. std::string observed_xff;
  18821. svr.Get("/ip", [&](const Request &req, Response &res) {
  18822. observed_remote_addr = req.remote_addr;
  18823. observed_xff = req.get_header_value("X-Forwarded-For");
  18824. res.set_content("ok", "text/plain");
  18825. });
  18826. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18827. auto se = detail::scope_exit([&] {
  18828. svr.stop();
  18829. t.join();
  18830. ASSERT_FALSE(svr.is_running());
  18831. });
  18832. svr.wait_until_ready();
  18833. Client cli(HOST, PORT);
  18834. auto res = cli.Get("/ip");
  18835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18836. EXPECT_EQ(StatusCode::OK_200, res->status);
  18837. EXPECT_EQ(observed_xff, "");
  18838. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18839. observed_remote_addr == "127.0.0.1");
  18840. }
  18841. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18842. Server svr;
  18843. // Include the loopback address the test client actually connects from, so
  18844. // the direct connection itself is recognized as the trusted proxy hop.
  18845. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18846. std::string observed_remote_addr;
  18847. std::string observed_xff;
  18848. svr.Get("/ip", [&](const Request &req, Response &res) {
  18849. observed_remote_addr = req.remote_addr;
  18850. observed_xff = req.get_header_value("X-Forwarded-For");
  18851. res.set_content("ok", "text/plain");
  18852. });
  18853. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18854. auto se = detail::scope_exit([&] {
  18855. svr.stop();
  18856. t.join();
  18857. ASSERT_FALSE(svr.is_running());
  18858. });
  18859. svr.wait_until_ready();
  18860. Client cli(HOST, PORT);
  18861. auto res = cli.Get(
  18862. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18864. EXPECT_EQ(StatusCode::OK_200, res->status);
  18865. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18866. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18867. }
  18868. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18869. Server svr;
  18870. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18871. std::string observed_remote_addr;
  18872. std::string observed_xff;
  18873. svr.Get("/ip", [&](const Request &req, Response &res) {
  18874. observed_remote_addr = req.remote_addr;
  18875. observed_xff = req.get_header_value("X-Forwarded-For");
  18876. res.set_content("ok", "text/plain");
  18877. });
  18878. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18879. auto se = detail::scope_exit([&] {
  18880. svr.stop();
  18881. t.join();
  18882. ASSERT_FALSE(svr.is_running());
  18883. });
  18884. svr.wait_until_ready();
  18885. Client cli(HOST, PORT);
  18886. auto res = cli.Get(
  18887. "/ip",
  18888. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18890. EXPECT_EQ(StatusCode::OK_200, res->status);
  18891. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18892. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18893. }
  18894. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18895. Server svr;
  18896. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18897. std::string observed_remote_addr;
  18898. std::string observed_xff;
  18899. svr.Get("/ip", [&](const Request &req, Response &res) {
  18900. observed_remote_addr = req.remote_addr;
  18901. observed_xff = req.get_header_value("X-Forwarded-For");
  18902. res.set_content("ok", "text/plain");
  18903. });
  18904. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18905. auto se = detail::scope_exit([&] {
  18906. svr.stop();
  18907. t.join();
  18908. ASSERT_FALSE(svr.is_running());
  18909. });
  18910. svr.wait_until_ready();
  18911. Client cli(HOST, PORT);
  18912. auto res = cli.Get(
  18913. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18915. EXPECT_EQ(StatusCode::OK_200, res->status);
  18916. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18917. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18918. // and must not be selected.
  18919. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18920. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18921. }
  18922. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18923. Server svr;
  18924. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18925. std::string observed_remote_addr;
  18926. svr.Get("/ip", [&](const Request &req, Response &res) {
  18927. observed_remote_addr = req.remote_addr;
  18928. res.set_content("ok", "text/plain");
  18929. });
  18930. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18931. auto se = detail::scope_exit([&] {
  18932. svr.stop();
  18933. t.join();
  18934. ASSERT_FALSE(svr.is_running());
  18935. });
  18936. svr.wait_until_ready();
  18937. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18938. // a forged address and the trusted proxy's own address; the forged value must
  18939. // not win over the address the trusted proxy actually recorded.
  18940. Client cli(HOST, PORT);
  18941. auto res = cli.Get(
  18942. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18944. EXPECT_EQ(StatusCode::OK_200, res->status);
  18945. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18946. }
  18947. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18948. Server svr;
  18949. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18950. std::string observed_remote_addr;
  18951. std::string observed_xff;
  18952. svr.Get("/ip", [&](const Request &req, Response &res) {
  18953. observed_remote_addr = req.remote_addr;
  18954. observed_xff = req.get_header_value("X-Forwarded-For");
  18955. res.set_content("ok", "text/plain");
  18956. });
  18957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18958. auto se = detail::scope_exit([&] {
  18959. svr.stop();
  18960. t.join();
  18961. ASSERT_FALSE(svr.is_running());
  18962. });
  18963. svr.wait_until_ready();
  18964. Client cli(HOST, PORT);
  18965. auto res = cli.Get(
  18966. "/ip",
  18967. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18969. EXPECT_EQ(StatusCode::OK_200, res->status);
  18970. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18971. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18972. }
  18973. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18974. Server svr;
  18975. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18976. std::string observed_remote_addr;
  18977. std::string observed_xff;
  18978. svr.Get("/ip", [&](const Request &req, Response &res) {
  18979. observed_remote_addr = req.remote_addr;
  18980. observed_xff = req.get_header_value("X-Forwarded-For");
  18981. res.set_content("ok", "text/plain");
  18982. });
  18983. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18984. auto se = detail::scope_exit([&] {
  18985. svr.stop();
  18986. t.join();
  18987. ASSERT_FALSE(svr.is_running());
  18988. });
  18989. svr.wait_until_ready();
  18990. std::string raw_req =
  18991. "GET /ip HTTP/1.1\r\n"
  18992. "Host: localhost\r\n"
  18993. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18994. "Connection: close\r\n"
  18995. "\r\n";
  18996. std::string out;
  18997. ASSERT_TRUE(send_request(5, raw_req, &out));
  18998. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18999. // Header parser trims surrounding whitespace of the header value
  19000. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19001. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19002. }
  19003. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19004. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19005. // their own X-Forwarded-For as a separate field line rather than extending the
  19006. // one the client sent, so every occurrence has to be taken into account.
  19007. // Reading only the first one hands back the address the client chose.
  19008. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19009. Server svr;
  19010. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19011. std::string observed_remote_addr;
  19012. size_t observed_xff_count = 0;
  19013. svr.Get("/ip", [&](const Request &req, Response &res) {
  19014. observed_remote_addr = req.remote_addr;
  19015. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19016. res.set_content("ok", "text/plain");
  19017. });
  19018. auto port = svr.bind_to_any_port(HOST);
  19019. thread t = thread([&]() { svr.listen_after_bind(); });
  19020. auto se = detail::scope_exit([&] {
  19021. svr.stop();
  19022. t.join();
  19023. ASSERT_FALSE(svr.is_running());
  19024. });
  19025. svr.wait_until_ready();
  19026. // The client supplies the first field line; the trusted proxy appends the
  19027. // address it observed as a second one.
  19028. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19029. "Host: localhost\r\n"
  19030. "X-Forwarded-For: 1.2.3.4\r\n"
  19031. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19032. "Connection: close\r\n"
  19033. "\r\n";
  19034. std::string out;
  19035. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19036. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19037. EXPECT_EQ(observed_xff_count, 2U);
  19038. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19039. // The same chain spread over one field line per hop derives the same client
  19040. // address, i.e. the split and the comma-joined representations agree.
  19041. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19042. "Host: localhost\r\n"
  19043. "X-Forwarded-For: 1.2.3.4\r\n"
  19044. "X-Forwarded-For: 198.51.100.23\r\n"
  19045. "X-Forwarded-For: 192.0.2.45\r\n"
  19046. "Connection: close\r\n"
  19047. "\r\n";
  19048. out.clear();
  19049. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19050. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19051. EXPECT_EQ(observed_xff_count, 3U);
  19052. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19053. }
  19054. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19055. // crash the server (it used to call front() on an empty vector inside
  19056. // get_client_ip). The connection-level remote address must be retained instead.
  19057. static void run_malformed_xff_test(const std::string &xff_value) {
  19058. Server svr;
  19059. svr.set_trusted_proxies({"192.0.2.45"});
  19060. std::string observed_remote_addr;
  19061. svr.Get("/ip", [&](const Request &req, Response &res) {
  19062. observed_remote_addr = req.remote_addr;
  19063. res.set_content("ok", "text/plain");
  19064. });
  19065. int port = 0;
  19066. thread t = thread([&]() {
  19067. port = svr.bind_to_any_port(HOST);
  19068. svr.listen_after_bind();
  19069. });
  19070. auto se = detail::scope_exit([&] {
  19071. svr.stop();
  19072. t.join();
  19073. ASSERT_FALSE(svr.is_running());
  19074. });
  19075. svr.wait_until_ready();
  19076. Client cli(HOST, port);
  19077. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19079. EXPECT_EQ(StatusCode::OK_200, res->status);
  19080. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19081. observed_remote_addr == "127.0.0.1");
  19082. }
  19083. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19084. run_malformed_xff_test("");
  19085. }
  19086. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19087. run_malformed_xff_test(",");
  19088. }
  19089. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19090. run_malformed_xff_test(", , ,");
  19091. }
  19092. // The same rule applies to Accept: a request whose acceptable types are spread
  19093. // over several field lines must be negotiated against all of them.
  19094. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19095. // case-insensitive connection options. Comparing the whole field value against
  19096. // one option misses a client that sends several of them, and misses every
  19097. // casing but the one written in the comparison.
  19098. //
  19099. // Sends req, reads the response, then reuses the same socket for a second
  19100. // request to find out whether the server kept the connection.
  19101. static void probe_connection_reuse(int port, const std::string &req,
  19102. bool *announced_close, bool *reusable) {
  19103. auto error = Error::Success;
  19104. auto sock = detail::create_client_socket(
  19105. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19106. /*connection_timeout_sec=*/5, 0,
  19107. /*read_timeout_sec=*/1, 0,
  19108. /*write_timeout_sec=*/5, 0, std::string(), error);
  19109. ASSERT_NE(sock, INVALID_SOCKET);
  19110. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19111. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19112. "Host: localhost\r\n"
  19113. "Connection: close\r\n"
  19114. "\r\n";
  19115. std::string first_response;
  19116. std::string second_response;
  19117. detail::process_client_socket(
  19118. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19119. [&](Stream &strm) {
  19120. if (strm.write(req.data(), req.size()) !=
  19121. static_cast<ssize_t>(req.size())) {
  19122. return false;
  19123. }
  19124. char buf[512];
  19125. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19126. // Headers plus the two-byte body of the handler below
  19127. while (reader.getline()) {
  19128. first_response += reader.ptr();
  19129. if (first_response.find("ok") != std::string::npos) { break; }
  19130. }
  19131. if (strm.write(second.data(), second.size()) !=
  19132. static_cast<ssize_t>(second.size())) {
  19133. return true;
  19134. }
  19135. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19136. while (reader2.getline()) {
  19137. second_response += reader2.ptr();
  19138. if (second_response.find("ok") != std::string::npos) { break; }
  19139. }
  19140. return true;
  19141. });
  19142. *announced_close =
  19143. first_response.find("Connection: close") != std::string::npos;
  19144. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19145. }
  19146. class ConnectionTokenTest : public ::testing::Test {
  19147. protected:
  19148. void SetUp() override {
  19149. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19150. res.set_content("ok", "text/plain");
  19151. });
  19152. port_ = svr_.bind_to_any_port(HOST);
  19153. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19154. svr_.wait_until_ready();
  19155. }
  19156. void TearDown() override {
  19157. svr_.stop();
  19158. if (thread_.joinable()) { thread_.join(); }
  19159. }
  19160. Server svr_;
  19161. int port_ = 0;
  19162. thread thread_;
  19163. };
  19164. // "close" alongside another option still closes the connection, and the
  19165. // response says so rather than leaving the peer to discover it.
  19166. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19167. bool announced_close = false;
  19168. bool reusable = true;
  19169. probe_connection_reuse(port_,
  19170. "GET /keepalive HTTP/1.1\r\n"
  19171. "Host: localhost\r\n"
  19172. "Connection: keep-alive, close\r\n"
  19173. "\r\n",
  19174. &announced_close, &reusable);
  19175. EXPECT_TRUE(announced_close);
  19176. EXPECT_FALSE(reusable);
  19177. }
  19178. // "close" split over two field lines is the same list, so it is honored too.
  19179. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19180. bool announced_close = false;
  19181. bool reusable = true;
  19182. probe_connection_reuse(port_,
  19183. "GET /keepalive HTTP/1.1\r\n"
  19184. "Host: localhost\r\n"
  19185. "Connection: keep-alive\r\n"
  19186. "Connection: close\r\n"
  19187. "\r\n",
  19188. &announced_close, &reusable);
  19189. EXPECT_TRUE(announced_close);
  19190. EXPECT_FALSE(reusable);
  19191. }
  19192. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19193. // keep-alive in the spelling everyone actually sends keeps its connection.
  19194. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19195. bool announced_close = false;
  19196. bool reusable = false;
  19197. probe_connection_reuse(port_,
  19198. "GET /keepalive HTTP/1.0\r\n"
  19199. "Host: localhost\r\n"
  19200. "Connection: keep-alive\r\n"
  19201. "\r\n",
  19202. &announced_close, &reusable);
  19203. EXPECT_FALSE(announced_close);
  19204. EXPECT_TRUE(reusable);
  19205. }
  19206. // A token the value merely contains is not the token itself.
  19207. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19208. bool announced_close = false;
  19209. bool reusable = false;
  19210. probe_connection_reuse(port_,
  19211. "GET /keepalive HTTP/1.1\r\n"
  19212. "Host: localhost\r\n"
  19213. "Connection: notclose\r\n"
  19214. "\r\n",
  19215. &announced_close, &reusable);
  19216. EXPECT_FALSE(announced_close);
  19217. EXPECT_TRUE(reusable);
  19218. }
  19219. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19220. Server svr;
  19221. std::vector<std::string> observed_types;
  19222. svr.Get("/", [&](const Request &req, Response &res) {
  19223. observed_types = req.accept_content_types;
  19224. res.set_content("ok", "text/plain");
  19225. });
  19226. auto port = svr.bind_to_any_port(HOST);
  19227. thread t = thread([&]() { svr.listen_after_bind(); });
  19228. auto se = detail::scope_exit([&] {
  19229. svr.stop();
  19230. t.join();
  19231. ASSERT_FALSE(svr.is_running());
  19232. });
  19233. svr.wait_until_ready();
  19234. Client cli(HOST, port);
  19235. Headers headers;
  19236. headers.emplace("Accept", "text/plain;q=0.5");
  19237. headers.emplace("Accept", "application/json");
  19238. auto res = cli.Get("/", headers);
  19239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19240. EXPECT_EQ(StatusCode::OK_200, res->status);
  19241. // Sorted by q-value, so the second field line's type comes first
  19242. ASSERT_EQ(2U, observed_types.size());
  19243. EXPECT_EQ("application/json", observed_types[0]);
  19244. EXPECT_EQ("text/plain", observed_types[1]);
  19245. }
  19246. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19247. // empty field line must not contribute a bare comma to the combined value.
  19248. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19249. Server svr;
  19250. std::vector<std::string> observed_types;
  19251. svr.Get("/", [&](const Request &req, Response &res) {
  19252. observed_types = req.accept_content_types;
  19253. res.set_content("ok", "text/plain");
  19254. });
  19255. auto port = svr.bind_to_any_port(HOST);
  19256. thread t = thread([&]() { svr.listen_after_bind(); });
  19257. auto se = detail::scope_exit([&] {
  19258. svr.stop();
  19259. t.join();
  19260. ASSERT_FALSE(svr.is_running());
  19261. });
  19262. svr.wait_until_ready();
  19263. // Empty first field line, then a real one
  19264. std::string raw_req = "GET / HTTP/1.1\r\n"
  19265. "Host: localhost\r\n"
  19266. "Accept:\r\n"
  19267. "Accept: application/json\r\n"
  19268. "Connection: close\r\n"
  19269. "\r\n";
  19270. std::string out;
  19271. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19272. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19273. ASSERT_EQ(1U, observed_types.size());
  19274. EXPECT_EQ("application/json", observed_types[0]);
  19275. }
  19276. // The skip in get_combined_header_value() is what keeps an empty field line
  19277. // from contributing a bare comma. Only a trailing empty field line exercises
  19278. // it: a leading one is already covered by the "combined is still empty" check,
  19279. // and parse_accept_header() now ignores the empty element either way, so the
  19280. // request-level test above can no longer tell the two apart.
  19281. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19282. Headers headers;
  19283. headers.emplace("Accept", "text/html");
  19284. headers.emplace("Accept", "");
  19285. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19286. headers.clear();
  19287. headers.emplace("Accept", "");
  19288. headers.emplace("Accept", "application/json");
  19289. EXPECT_EQ("application/json",
  19290. detail::get_combined_header_value(headers, "Accept"));
  19291. }
  19292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19293. // An encoding offered on a later Accept-Encoding field line is still offered.
  19294. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19295. Server svr;
  19296. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19297. res.set_content(std::string(1024, 'x'), "text/plain");
  19298. });
  19299. auto port = svr.bind_to_any_port(HOST);
  19300. thread t = thread([&]() { svr.listen_after_bind(); });
  19301. auto se = detail::scope_exit([&] {
  19302. svr.stop();
  19303. t.join();
  19304. ASSERT_FALSE(svr.is_running());
  19305. });
  19306. svr.wait_until_ready();
  19307. Client cli(HOST, port);
  19308. cli.set_decompress(false);
  19309. Headers headers;
  19310. headers.emplace("Accept-Encoding", "identity");
  19311. headers.emplace("Accept-Encoding", "gzip");
  19312. auto res = cli.Get("/", headers);
  19313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19314. EXPECT_EQ(StatusCode::OK_200, res->status);
  19315. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19316. }
  19317. #endif
  19318. #ifndef _WIN32
  19319. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19320. Server svr;
  19321. svr.Post("/post", [&](const Request &req, Response &res) {
  19322. res.set_content(req.body, "text/plain");
  19323. });
  19324. svr.Put("/put", [&](const Request &req, Response &res) {
  19325. res.set_content(req.body, "text/plain");
  19326. });
  19327. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19328. res.set_content(req.body, "text/plain");
  19329. });
  19330. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19331. res.set_content(req.body, "text/plain");
  19332. });
  19333. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19334. auto se = detail::scope_exit([&] {
  19335. svr.stop();
  19336. t.join();
  19337. ASSERT_FALSE(svr.is_running());
  19338. });
  19339. svr.wait_until_ready();
  19340. std::string resp;
  19341. // POST without Content-Length
  19342. ASSERT_TRUE(send_request(5,
  19343. "POST /post HTTP/1.1\r\n"
  19344. "Host: localhost\r\n"
  19345. "Connection: close\r\n"
  19346. "\r\n",
  19347. &resp));
  19348. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19349. // PUT without Content-Length
  19350. resp.clear();
  19351. ASSERT_TRUE(send_request(5,
  19352. "PUT /put HTTP/1.1\r\n"
  19353. "Host: localhost\r\n"
  19354. "Connection: close\r\n"
  19355. "\r\n",
  19356. &resp));
  19357. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19358. // PATCH without Content-Length
  19359. resp.clear();
  19360. ASSERT_TRUE(send_request(5,
  19361. "PATCH /patch HTTP/1.1\r\n"
  19362. "Host: localhost\r\n"
  19363. "Connection: close\r\n"
  19364. "\r\n",
  19365. &resp));
  19366. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19367. // DELETE without Content-Length
  19368. resp.clear();
  19369. ASSERT_TRUE(send_request(5,
  19370. "DELETE /delete HTTP/1.1\r\n"
  19371. "Host: localhost\r\n"
  19372. "Connection: close\r\n"
  19373. "\r\n",
  19374. &resp));
  19375. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19376. }
  19377. #endif
  19378. //==============================================================================
  19379. // open_stream() Tests
  19380. //==============================================================================
  19381. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19382. std::string result;
  19383. char buf[8192];
  19384. ssize_t n;
  19385. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19386. result.append(buf, static_cast<size_t>(n));
  19387. }
  19388. return result;
  19389. }
  19390. // Mock stream for unit tests
  19391. class MockStream : public Stream {
  19392. public:
  19393. std::string data;
  19394. size_t pos = 0;
  19395. ssize_t error_after = -1; // -1 = no error
  19396. explicit MockStream(const std::string &d, ssize_t err = -1)
  19397. : data(d), error_after(err) {}
  19398. bool is_readable() const override { return true; }
  19399. bool wait_readable() const override { return true; }
  19400. bool wait_writable() const override { return true; }
  19401. ssize_t read(char *ptr, size_t size) override {
  19402. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19403. if (pos >= data.size()) return 0;
  19404. size_t limit =
  19405. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19406. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19407. std::memcpy(ptr, data.data() + pos, to_read);
  19408. pos += to_read;
  19409. return static_cast<ssize_t>(to_read);
  19410. }
  19411. ssize_t write(const char *, size_t) override { return -1; }
  19412. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19413. ip = "127.0.0.1";
  19414. port = 0;
  19415. }
  19416. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19417. ip = "127.0.0.1";
  19418. port = 0;
  19419. }
  19420. socket_t socket() const override { return INVALID_SOCKET; }
  19421. time_t duration() const override { return 0; }
  19422. };
  19423. TEST(StreamHandleTest, Basic) {
  19424. ClientImpl::StreamHandle handle;
  19425. EXPECT_FALSE(handle.is_valid());
  19426. handle.response = detail::make_unique<Response>();
  19427. handle.error = Error::Connection;
  19428. EXPECT_FALSE(handle.is_valid());
  19429. handle.error = Error::Success;
  19430. EXPECT_TRUE(handle.is_valid());
  19431. }
  19432. TEST(BodyReaderTest, Basic) {
  19433. MockStream stream("Hello, World!");
  19434. detail::BodyReader reader;
  19435. reader.stream = &stream;
  19436. reader.content_length = 13;
  19437. char buf[32];
  19438. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19439. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19440. EXPECT_TRUE(reader.eof);
  19441. }
  19442. TEST(BodyReaderTest, NoStream) {
  19443. detail::BodyReader reader;
  19444. char buf[32];
  19445. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19446. EXPECT_EQ(Error::Connection, reader.last_error);
  19447. }
  19448. TEST(BodyReaderTest, Error) {
  19449. MockStream stream("Hello, World!", 5);
  19450. detail::BodyReader reader;
  19451. reader.stream = &stream;
  19452. reader.content_length = 13;
  19453. char buf[32];
  19454. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19455. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19456. EXPECT_EQ(Error::Read, reader.last_error);
  19457. }
  19458. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19459. // Mock-based StreamHandle tests relying on private internals are removed.
  19460. class OpenStreamTest : public ::testing::Test {
  19461. protected:
  19462. void SetUp() override {
  19463. svr_.Get("/hello", [](const Request &, Response &res) {
  19464. res.set_content("Hello World!", "text/plain");
  19465. });
  19466. svr_.Get("/large", [](const Request &, Response &res) {
  19467. res.set_content(std::string(10000, 'X'), "text/plain");
  19468. });
  19469. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19470. res.set_content("Hello World!", "image/jpeg");
  19471. res.set_header("Content-Encoding", "UTF-8");
  19472. });
  19473. svr_.Get("/chunked", [](const Request &, Response &res) {
  19474. res.set_chunked_content_provider("text/plain",
  19475. [](size_t offset, DataSink &sink) {
  19476. if (offset < 15) {
  19477. sink.write("chunk", 5);
  19478. return true;
  19479. }
  19480. sink.done();
  19481. return true;
  19482. });
  19483. });
  19484. svr_.Get("/compressible", [](const Request &, Response &res) {
  19485. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19486. DataSink &sink) {
  19487. if (offset < 100 * 1024) {
  19488. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19489. sink.write(chunk.data(), chunk.size());
  19490. return true;
  19491. }
  19492. sink.done();
  19493. return true;
  19494. });
  19495. });
  19496. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19497. [](const Request & /*req*/, Response &res) {
  19498. auto i = new int(0);
  19499. res.set_header("Trailer", "Content-Length, X-Allowed");
  19500. res.set_chunked_content_provider(
  19501. "text/plain",
  19502. [i](size_t /*offset*/, DataSink &sink) {
  19503. switch (*i) {
  19504. case 0: sink.os << "123"; break;
  19505. case 1: sink.os << "456"; break;
  19506. case 2: sink.os << "789"; break;
  19507. case 3: {
  19508. sink.done_with_trailer(
  19509. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19510. } break;
  19511. }
  19512. (*i)++;
  19513. return true;
  19514. },
  19515. [i](bool success) {
  19516. EXPECT_TRUE(success);
  19517. delete i;
  19518. });
  19519. });
  19520. // Echo headers endpoint for header-related tests
  19521. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19522. std::string body;
  19523. for (const auto &h : req.headers) {
  19524. body.append(h.first);
  19525. body.push_back(':');
  19526. body.append(h.second);
  19527. body.push_back('\n');
  19528. }
  19529. res.set_content(body, "text/plain");
  19530. });
  19531. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19532. std::string body;
  19533. for (const auto &h : req.headers) {
  19534. body.append(h.first);
  19535. body.push_back(':');
  19536. body.append(h.second);
  19537. body.push_back('\n');
  19538. }
  19539. res.set_content(body, "text/plain");
  19540. });
  19541. port_ = svr_.bind_to_any_port("127.0.0.1");
  19542. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19543. svr_.wait_until_ready();
  19544. }
  19545. void TearDown() override {
  19546. svr_.stop();
  19547. if (thread_.joinable()) thread_.join();
  19548. }
  19549. Server svr_;
  19550. std::thread thread_;
  19551. int port_ = 0;
  19552. };
  19553. TEST_F(OpenStreamTest, Basic) {
  19554. Client cli("127.0.0.1", port_);
  19555. auto handle = cli.open_stream("GET", "/hello");
  19556. EXPECT_TRUE(handle.is_valid());
  19557. EXPECT_EQ("Hello World!", read_all(handle));
  19558. }
  19559. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19560. Client cli("127.0.0.1", port_);
  19561. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19562. ASSERT_TRUE(handle.is_valid());
  19563. EXPECT_EQ("Hello World!", read_all(handle));
  19564. }
  19565. TEST_F(OpenStreamTest, SmallBuffer) {
  19566. Client cli("127.0.0.1", port_);
  19567. auto handle = cli.open_stream("GET", "/hello");
  19568. std::string result;
  19569. char buf[4];
  19570. ssize_t n;
  19571. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19572. result.append(buf, static_cast<size_t>(n));
  19573. EXPECT_EQ("Hello World!", result);
  19574. }
  19575. TEST_F(OpenStreamTest, DefaultHeaders) {
  19576. Client cli("127.0.0.1", port_);
  19577. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19578. {
  19579. auto handle = cli.open_stream("GET", "/echo-headers");
  19580. ASSERT_TRUE(handle.is_valid());
  19581. auto body = read_all(handle);
  19582. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19583. std::string::npos);
  19584. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19585. std::string::npos);
  19586. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19587. }
  19588. // open_stream POST with body and no explicit content_type should NOT add
  19589. // text/plain Content-Type (behavior differs from non-streaming path), but
  19590. // should include Content-Length
  19591. {
  19592. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19593. ASSERT_TRUE(handle.is_valid());
  19594. auto body = read_all(handle);
  19595. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19596. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19597. }
  19598. // open_stream POST with explicit Content-Type should preserve it
  19599. {
  19600. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19601. {{"Content-Type", "application/custom"}},
  19602. "{}", "application/custom");
  19603. ASSERT_TRUE(handle.is_valid());
  19604. auto body = read_all(handle);
  19605. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19606. }
  19607. // User-specified User-Agent must not be overwritten for stream API
  19608. {
  19609. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19610. {{"User-Agent", "MyAgent/1.2"}});
  19611. ASSERT_TRUE(handle.is_valid());
  19612. auto body = read_all(handle);
  19613. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19614. }
  19615. }
  19616. TEST_F(OpenStreamTest, Large) {
  19617. Client cli("127.0.0.1", port_);
  19618. auto handle = cli.open_stream("GET", "/large");
  19619. EXPECT_EQ(10000u, read_all(handle).size());
  19620. }
  19621. TEST_F(OpenStreamTest, ConnectionError) {
  19622. Client cli("127.0.0.1", 9999);
  19623. auto handle = cli.open_stream("GET", "/hello");
  19624. EXPECT_FALSE(handle.is_valid());
  19625. }
  19626. TEST_F(OpenStreamTest, Chunked) {
  19627. Client cli("127.0.0.1", port_);
  19628. auto handle = cli.open_stream("GET", "/chunked");
  19629. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19630. "Transfer-Encoding") == "chunked");
  19631. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19632. }
  19633. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19634. Client cli("127.0.0.1", port_);
  19635. auto handle =
  19636. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19637. ASSERT_TRUE(handle.is_valid());
  19638. // Consume body to allow trailers to be received/parsed
  19639. auto body = read_all(handle);
  19640. // Explicitly parse trailers (ensure trailers are available for assertion)
  19641. handle.parse_trailers_if_needed();
  19642. EXPECT_EQ(std::string("123456789"), body);
  19643. // The response should include a Trailer header declaring both names
  19644. ASSERT_TRUE(handle.response);
  19645. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19646. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19647. handle.response->get_header_value("Trailer"));
  19648. // Prohibited trailer must not be present
  19649. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19650. // Allowed trailer should be present
  19651. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19652. EXPECT_EQ(std::string("yes"),
  19653. handle.response->get_trailer_value("X-Allowed"));
  19654. // Verify trailers are NOT present as regular headers
  19655. EXPECT_EQ(std::string(""),
  19656. handle.response->get_header_value("Content-Length"));
  19657. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19658. }
  19659. // Accepts one connection on an OS-assigned port, which it hands over through
  19660. // port_promise, reads the request head and sends back response. after_send,
  19661. // if given, runs on the connection before it is closed.
  19662. static std::thread
  19663. serve_single_response(std::promise<int> &port_promise,
  19664. const std::string &response,
  19665. std::function<void(socket_t)> after_send = nullptr) {
  19666. return std::thread([&port_promise, response, after_send] {
  19667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19668. default_socket_options(srv);
  19669. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19670. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19671. sockaddr_in addr{};
  19672. addr.sin_family = AF_INET;
  19673. addr.sin_port = htons(0); // Let OS assign a free port
  19674. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19675. int opt = 1;
  19676. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19677. #ifdef _WIN32
  19678. reinterpret_cast<const char *>(&opt),
  19679. #else
  19680. &opt,
  19681. #endif
  19682. sizeof(opt));
  19683. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19684. ::listen(srv, 1) != 0) {
  19685. port_promise.set_value(-1);
  19686. detail::close_socket(srv);
  19687. return;
  19688. }
  19689. socklen_t addr_len = sizeof(addr);
  19690. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19691. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19692. sockaddr_in cli_addr{};
  19693. socklen_t cli_len = sizeof(cli_addr);
  19694. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19695. if (cli != INVALID_SOCKET) {
  19696. // Read the complete HTTP request (until the blank line that terminates
  19697. // headers) before sending the response. If the server closes the socket
  19698. // while the client's request data is still unread in the kernel receive
  19699. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19700. // connection on both sides: it discards the client's receive buffer
  19701. // (which already holds our response) and causes any in-progress write on
  19702. // the client to fail with ECONNRESET. Reading all request data first
  19703. // ensures close() emits a graceful FIN.
  19704. {
  19705. char rbuf[256];
  19706. std::string req;
  19707. while (req.find("\r\n\r\n") == std::string::npos) {
  19708. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19709. if (n <= 0) { break; }
  19710. req.append(rbuf, static_cast<size_t>(n));
  19711. }
  19712. }
  19713. ::send(cli,
  19714. #ifdef _WIN32
  19715. static_cast<const char *>(response.c_str()),
  19716. static_cast<int>(response.size()),
  19717. #else
  19718. response.c_str(), response.size(),
  19719. #endif
  19720. 0);
  19721. if (after_send) { after_send(cli); }
  19722. detail::close_socket(cli);
  19723. }
  19724. detail::close_socket(srv);
  19725. });
  19726. }
  19727. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19728. #ifndef _WIN32
  19729. signal(SIGPIPE, SIG_IGN);
  19730. #endif
  19731. std::promise<int> port_promise;
  19732. auto port_future = port_promise.get_future();
  19733. auto server_thread =
  19734. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19735. "Content-Type: text/plain\r\n"
  19736. "Content-Length: not-a-number\r\n"
  19737. "Connection: close\r\n"
  19738. "\r\n"
  19739. "hello");
  19740. auto port = port_future.get();
  19741. ASSERT_GT(port, 0);
  19742. Client cli("127.0.0.1", port);
  19743. auto handle = cli.open_stream("GET", "/");
  19744. EXPECT_FALSE(handle.is_valid());
  19745. server_thread.join();
  19746. }
  19747. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19748. #ifndef _WIN32
  19749. signal(SIGPIPE, SIG_IGN);
  19750. #endif
  19751. std::promise<int> port_promise;
  19752. auto port_future = port_promise.get_future();
  19753. auto server_thread = serve_single_response(
  19754. port_promise, "HTTP/1.1 200 OK\r\n"
  19755. "Content-Type: text/plain\r\n"
  19756. "Content-Length: 99999999999999999999999999\r\n"
  19757. "Connection: close\r\n"
  19758. "\r\n"
  19759. "hello");
  19760. auto port = port_future.get();
  19761. ASSERT_GT(port, 0);
  19762. // Historically std::stoull would throw std::out_of_range here and crash
  19763. // the process, then parsing silently clamped to a bogus framing length and
  19764. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19765. // so the stream fails to open, matching the not-a-number case above. The
  19766. // process still must NOT terminate.
  19767. Client cli("127.0.0.1", port);
  19768. auto handle = cli.open_stream("GET", "/");
  19769. EXPECT_FALSE(handle.is_valid());
  19770. server_thread.join();
  19771. }
  19772. // Serves `response` to the single request `fn` makes with a fresh client.
  19773. template <typename Fn>
  19774. static void with_single_response(const std::string &response, Fn fn) {
  19775. #ifndef _WIN32
  19776. signal(SIGPIPE, SIG_IGN);
  19777. #endif
  19778. std::promise<int> port_promise;
  19779. auto port_future = port_promise.get_future();
  19780. auto server_thread = serve_single_response(port_promise, response);
  19781. auto se = detail::scope_exit([&] { server_thread.join(); });
  19782. auto port = port_future.get();
  19783. ASSERT_GT(port, 0);
  19784. Client cli("127.0.0.1", port);
  19785. fn(cli);
  19786. }
  19787. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19788. // Neither Content-Length nor chunked: the body ends at the close
  19789. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19790. "Connection: close\r\n"
  19791. "\r\n"
  19792. "hello";
  19793. with_single_response(close_delimited, [](Client &cli) {
  19794. auto handle = cli.open_stream("GET", "/");
  19795. ASSERT_TRUE(handle.is_valid());
  19796. EXPECT_EQ("hello", read_all(handle));
  19797. EXPECT_FALSE(handle.has_read_error());
  19798. });
  19799. // A close before the end of the Content-Length is still an error
  19800. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19801. "Content-Length: 10\r\n"
  19802. "\r\n"
  19803. "hello";
  19804. with_single_response(short_content_length, [](Client &cli) {
  19805. auto handle = cli.open_stream("GET", "/");
  19806. ASSERT_TRUE(handle.is_valid());
  19807. read_all(handle);
  19808. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19809. });
  19810. // So is a close before the last chunk
  19811. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19812. "Transfer-Encoding: chunked\r\n"
  19813. "\r\n"
  19814. "5\r\nhello\r\n";
  19815. with_single_response(short_chunked, [](Client &cli) {
  19816. auto handle = cli.open_stream("GET", "/");
  19817. ASSERT_TRUE(handle.is_valid());
  19818. read_all(handle);
  19819. EXPECT_TRUE(handle.has_read_error());
  19820. });
  19821. }
  19822. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19823. const char *responses[] = {
  19824. "HTTP/1.1 103 Early Hints\r\n"
  19825. "Link: </style.css>; rel=preload\r\n"
  19826. "\r\n"
  19827. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19828. "HTTP/1.1 100 Continue\r\n"
  19829. "X-Note: interim\r\n"
  19830. "\r\n"
  19831. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19832. };
  19833. for (auto response : responses) {
  19834. with_single_response(response, [](Client &cli) {
  19835. auto res = cli.Get("/");
  19836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19837. EXPECT_EQ(StatusCode::OK_200, res->status);
  19838. EXPECT_EQ("ok", res->body);
  19839. });
  19840. }
  19841. }
  19842. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19843. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19844. const std::string final_response =
  19845. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19846. std::string interims;
  19847. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19848. interims += interim;
  19849. }
  19850. with_single_response(interims + final_response, [](Client &cli) {
  19851. auto res = cli.Get("/");
  19852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19853. EXPECT_EQ("ok", res->body);
  19854. });
  19855. with_single_response(interims + interim + final_response, [](Client &cli) {
  19856. auto res = cli.Get("/");
  19857. ASSERT_FALSE(res);
  19858. EXPECT_EQ(Error::Read, res.error());
  19859. });
  19860. }
  19861. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19862. #ifndef _WIN32
  19863. signal(SIGPIPE, SIG_IGN);
  19864. #endif
  19865. // The server answers the head without asking for the body. Bytes it then
  19866. // reads on the connection would be taken for the body the request declared.
  19867. auto closed_by_client = false;
  19868. std::promise<int> port_promise;
  19869. auto server_thread = serve_single_response(
  19870. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19871. [&](socket_t sock) {
  19872. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19873. char buf[256];
  19874. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19875. });
  19876. Client cli("127.0.0.1", port_promise.get_future().get());
  19877. cli.set_keep_alive(true);
  19878. cli.set_read_timeout(1, 0);
  19879. // Long enough for the client to send Expect: 100-continue.
  19880. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19882. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19883. cli.Get("/second");
  19884. server_thread.join();
  19885. EXPECT_TRUE(closed_by_client);
  19886. }
  19887. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19888. // Long enough for the client to send Expect: 100-continue
  19889. with_single_response(
  19890. "HTTP/1.1 103 Early Hints\r\n"
  19891. "Link: </style.css>; rel=preload\r\n"
  19892. "\r\n"
  19893. "HTTP/1.1 401 Unauthorized\r\n"
  19894. "Content-Length: 0\r\n\r\n",
  19895. [](Client &cli) {
  19896. cli.set_read_timeout(2, 0);
  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. });
  19901. }
  19902. #ifdef CPPHTTPLIB_SSL_ENABLED
  19903. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19904. #ifndef _WIN32
  19905. signal(SIGPIPE, SIG_IGN);
  19906. #endif
  19907. auto reused = false;
  19908. std::promise<int> port_promise;
  19909. auto server_thread = serve_single_response(
  19910. port_promise,
  19911. "HTTP/1.1 401 Unauthorized\r\n"
  19912. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19913. "Content-Length: 0\r\n\r\n",
  19914. [&](socket_t sock) {
  19915. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19916. char buf[256];
  19917. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19918. });
  19919. Client cli("127.0.0.1", port_promise.get_future().get());
  19920. cli.set_keep_alive(true);
  19921. cli.set_digest_auth("user", "pass");
  19922. cli.set_read_timeout(1, 0);
  19923. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19924. server_thread.join();
  19925. EXPECT_FALSE(reused);
  19926. }
  19927. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19928. // Any other answer to CONNECT would read as the origin's response.
  19929. struct {
  19930. const char *response;
  19931. bool passed_on;
  19932. } cases[] = {
  19933. {"HTTP/1.1 201 Created\r\n"
  19934. "Set-Cookie: session=from-proxy\r\n"
  19935. "Content-Length: 0\r\n\r\n",
  19936. false},
  19937. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19938. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19939. "Content-Length: 0\r\n\r\n",
  19940. true},
  19941. };
  19942. for (const auto &c : cases) {
  19943. std::promise<int> port_promise;
  19944. auto server_thread = serve_single_response(port_promise, c.response);
  19945. SSLClient cli("example.com", 443);
  19946. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19947. auto res = cli.Get("/");
  19948. server_thread.join();
  19949. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19950. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19951. if (res) {
  19952. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19953. }
  19954. }
  19955. }
  19956. #endif
  19957. // Records the client's error logger calls as "error METHOD path", or
  19958. // "error null" for a call without a request
  19959. static ErrorLogger record_errors(std::vector<std::string> &log) {
  19960. return [&log](const Error &err, const Request *req) {
  19961. log.push_back(to_string(err) + " " +
  19962. (req ? req->method + " " + req->path : "null"));
  19963. };
  19964. }
  19965. // A failed request is reported once, with the request the caller made
  19966. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  19967. Server svr;
  19968. svr.Get("/big", [](const Request &, Response &res) {
  19969. res.set_content(std::string(100000, 'b'), "text/plain");
  19970. });
  19971. auto port = svr.bind_to_any_port(HOST);
  19972. std::thread t([&]() { svr.listen_after_bind(); });
  19973. auto se = detail::scope_exit([&] {
  19974. svr.stop();
  19975. t.join();
  19976. });
  19977. svr.wait_until_ready();
  19978. Client cli(HOST, port);
  19979. std::vector<std::string> log;
  19980. cli.set_error_logger(record_errors(log));
  19981. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  19982. cli.Get("/big", [](const char *, size_t) { return false; });
  19983. EXPECT_EQ(expected, log);
  19984. log.clear();
  19985. cli.Get("/big", [](size_t, size_t) { return false; });
  19986. EXPECT_EQ(expected, log);
  19987. }
  19988. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  19989. // Fails while the body is read
  19990. auto broken = [](const Request &, Response &res) {
  19991. res.set_content_provider(10, "text/plain",
  19992. [](size_t, size_t, DataSink &) { return false; });
  19993. };
  19994. Server other;
  19995. other.Get("/broken", broken);
  19996. auto other_port = other.bind_to_any_port(HOST);
  19997. std::thread other_t([&]() { other.listen_after_bind(); });
  19998. auto other_se = detail::scope_exit([&] {
  19999. other.stop();
  20000. other_t.join();
  20001. });
  20002. other.wait_until_ready();
  20003. Server svr;
  20004. svr.Get("/broken", broken);
  20005. svr.Get("/same-origin",
  20006. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20007. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20008. res.set_redirect("http://" + std::string(HOST) + ":" +
  20009. std::to_string(other_port) + "/broken");
  20010. });
  20011. auto port = svr.bind_to_any_port(HOST);
  20012. std::thread t([&]() { svr.listen_after_bind(); });
  20013. auto se = detail::scope_exit([&] {
  20014. svr.stop();
  20015. t.join();
  20016. });
  20017. svr.wait_until_ready();
  20018. Client cli(HOST, port);
  20019. cli.set_follow_location(true);
  20020. std::vector<std::string> log;
  20021. cli.set_error_logger(record_errors(log));
  20022. for (auto path : {"/same-origin", "/cross-origin"}) {
  20023. log.clear();
  20024. auto res = cli.Get(path);
  20025. ASSERT_FALSE(res);
  20026. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20027. log);
  20028. }
  20029. }
  20030. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20031. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20032. std::vector<std::string> log;
  20033. cli.set_error_logger(record_errors(log));
  20034. auto handle = cli.open_stream("GET", "/x");
  20035. EXPECT_FALSE(handle.is_valid());
  20036. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20037. log);
  20038. });
  20039. }
  20040. #ifdef CPPHTTPLIB_SSL_ENABLED
  20041. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20042. // Not a TLS server, so the handshake fails. It waits for a request line in
  20043. // the handshake bytes, so a short read timeout lets it close quickly.
  20044. Server svr;
  20045. svr.set_read_timeout(0, 100000);
  20046. svr.Get("/x", [](const Request &, Response &res) {
  20047. res.set_content("x", "text/plain");
  20048. });
  20049. auto port = svr.bind_to_any_port(HOST);
  20050. std::thread t([&]() { svr.listen_after_bind(); });
  20051. auto se = detail::scope_exit([&] {
  20052. svr.stop();
  20053. t.join();
  20054. });
  20055. svr.wait_until_ready();
  20056. std::vector<std::string> log;
  20057. SSLClient cli(HOST, port);
  20058. cli.enable_server_certificate_verification(false);
  20059. cli.set_error_logger(record_errors(log));
  20060. auto res = cli.Get("/x");
  20061. ASSERT_FALSE(res);
  20062. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20063. log.clear();
  20064. auto handle = cli.open_stream("GET", "/x");
  20065. EXPECT_FALSE(handle.is_valid());
  20066. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20067. log.clear();
  20068. SSLClient no_ca(HOST, port);
  20069. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20070. no_ca.set_error_logger(record_errors(log));
  20071. res = no_ca.Get("/x");
  20072. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20073. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20074. }
  20075. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20076. #ifndef _WIN32
  20077. signal(SIGPIPE, SIG_IGN);
  20078. #endif
  20079. // Refused, answered with a challenge, or closed without an answer
  20080. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20081. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20082. "Content-Length: 0\r\n\r\n",
  20083. ""}) {
  20084. std::promise<int> port_promise;
  20085. auto server_thread = serve_single_response(port_promise, response);
  20086. SSLClient cli("example.com", 443);
  20087. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20088. std::vector<std::string> log;
  20089. cli.set_error_logger(record_errors(log));
  20090. auto res = cli.Get("/");
  20091. server_thread.join();
  20092. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20093. << response;
  20094. }
  20095. }
  20096. #endif
  20097. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20098. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20099. // the chunked coding and drop Content-Length, so a front-end that trusts
  20100. // Content-Length would disagree about where the body ends (response
  20101. // smuggling). The client must reject such a response.
  20102. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20103. for (const char *te : {"chunked", "gzip, chunked"}) {
  20104. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20105. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20106. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20107. "5\r\nhello\r\n0\r\n\r\n";
  20108. with_single_response(response, [&](Client &cli) {
  20109. auto res = cli.Get("/");
  20110. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20111. EXPECT_EQ(Error::Read, res.error()) << te;
  20112. });
  20113. with_single_response(response, [&](Client &cli) {
  20114. auto handle = cli.open_stream("GET", "/");
  20115. EXPECT_FALSE(handle.is_valid()) << te;
  20116. EXPECT_EQ(Error::Read, handle.error) << te;
  20117. });
  20118. }
  20119. }
  20120. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20121. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20122. // closing the connection (unlike a request, which must be rejected).
  20123. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20124. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20125. "Transfer-Encoding: chunked\r\n"
  20126. "Connection: close\r\n"
  20127. "\r\n"
  20128. "5\r\nhello\r\n0\r\n\r\n",
  20129. "HTTP/1.1 200 OK\r\n"
  20130. "Transfer-Encoding: gzip\r\n"
  20131. "Connection: close\r\n"
  20132. "\r\n"
  20133. "hello"}) {
  20134. with_single_response(response, [&](Client &cli) {
  20135. auto res = cli.Get("/");
  20136. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20137. EXPECT_EQ("hello", res->body);
  20138. });
  20139. with_single_response(response, [&](Client &cli) {
  20140. auto handle = cli.open_stream("GET", "/");
  20141. ASSERT_TRUE(handle.is_valid()) << response;
  20142. EXPECT_EQ("hello", read_all(handle));
  20143. });
  20144. }
  20145. }
  20146. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20147. // framing headers describe nothing to read and must not be rejected.
  20148. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20149. const std::string framing = "Content-Length: 5\r\n"
  20150. "Transfer-Encoding: chunked\r\n"
  20151. "Connection: close\r\n"
  20152. "\r\n";
  20153. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20154. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20155. });
  20156. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20157. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20158. });
  20159. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20160. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20161. with_single_response(response, [&](Client &cli) {
  20162. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20163. });
  20164. with_single_response(response, [&](Client &cli) {
  20165. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20166. });
  20167. }
  20168. }
  20169. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20170. // header section, so a stream opened on one has nothing to read, whatever
  20171. // framing or coding headers it carries.
  20172. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20173. struct Case {
  20174. const char *method;
  20175. const char *status;
  20176. };
  20177. // A reader of the declared body reports an early close when nothing
  20178. // follows, and hands back what does.
  20179. struct Framing {
  20180. const char *headers;
  20181. const char *after;
  20182. };
  20183. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20184. Case{"GET", "304 Not Modified"}}) {
  20185. for (const auto &f :
  20186. {Framing{"Content-Length: 5\r\n", ""},
  20187. Framing{"Content-Length: 5\r\n", "hello"},
  20188. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20189. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20190. // Not decoded, so a build without Brotli opens it too
  20191. Framing{"Content-Encoding: br\r\n", ""}}) {
  20192. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20193. "Connection: close\r\n"
  20194. "\r\n" +
  20195. f.after;
  20196. with_single_response(response, [&](Client &cli) {
  20197. auto handle = cli.open_stream(c.method, "/");
  20198. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20199. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20200. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20201. });
  20202. }
  20203. }
  20204. }
  20205. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20206. // response, is faulty framing, so the connection is not reused after it.
  20207. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20208. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20209. "Content-Length: 0\r\n"
  20210. "Transfer-Encoding: chunked\r\n"
  20211. "\r\n"
  20212. "5\r\nhello\r\n0\r\n\r\n",
  20213. "HTTP/1.0 200 Connection established\r\n"
  20214. "Connection: keep-alive\r\n"
  20215. "Transfer-Encoding: chunked\r\n"
  20216. "\r\n"
  20217. "5\r\nhello\r\n0\r\n\r\n"}) {
  20218. with_single_response(response, [&](Client &cli) {
  20219. cli.set_keep_alive(true);
  20220. auto res = cli.Get("/");
  20221. ASSERT_TRUE(res) << response;
  20222. EXPECT_EQ("hello", res->body);
  20223. EXPECT_FALSE(cli.is_socket_open()) << response;
  20224. });
  20225. }
  20226. }
  20227. // A payload max length of 0 means no limit, however the body is framed.
  20228. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20229. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20230. "Transfer-Encoding: chunked\r\n"
  20231. "\r\n"
  20232. "5\r\nhello\r\n0\r\n\r\n",
  20233. "HTTP/1.1 200 OK\r\n"
  20234. "Connection: close\r\n"
  20235. "\r\n"
  20236. "hello"}) {
  20237. with_single_response(response, [&](Client &cli) {
  20238. cli.set_payload_max_length(0);
  20239. auto res = cli.Get("/");
  20240. ASSERT_TRUE(res) << response;
  20241. EXPECT_EQ("hello", res->body) << response;
  20242. });
  20243. }
  20244. }
  20245. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20246. Server svr;
  20247. svr.set_payload_max_length(0);
  20248. svr.Post("/echo", [](const Request &req, Response &res) {
  20249. res.set_content(req.body, "text/plain");
  20250. });
  20251. auto port = svr.bind_to_any_port(HOST);
  20252. thread t = thread([&] { svr.listen_after_bind(); });
  20253. auto se = detail::scope_exit([&] {
  20254. svr.stop();
  20255. t.join();
  20256. ASSERT_FALSE(svr.is_running());
  20257. });
  20258. svr.wait_until_ready();
  20259. Client cli(HOST, port);
  20260. auto res = cli.Post(
  20261. "/echo",
  20262. [](size_t /*offset*/, DataSink &sink) {
  20263. sink.write("hello", 5);
  20264. sink.done();
  20265. return true;
  20266. },
  20267. "text/plain");
  20268. ASSERT_TRUE(res);
  20269. EXPECT_EQ(StatusCode::OK_200, res->status);
  20270. EXPECT_EQ("hello", res->body);
  20271. }
  20272. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20273. TEST_F(OpenStreamTest, Gzip) {
  20274. Client cli("127.0.0.1", port_);
  20275. auto handle = cli.open_stream("GET", "/compressible", {},
  20276. {{"Accept-Encoding", "gzip"}});
  20277. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20278. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20279. }
  20280. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20281. Client cli("127.0.0.1", port_);
  20282. auto handle =
  20283. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20284. {{"Accept-Encoding", "gzip"}});
  20285. ASSERT_TRUE(handle.is_valid());
  20286. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20287. EXPECT_EQ("123456789", read_all(handle));
  20288. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20289. }
  20290. #endif
  20291. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20292. TEST_F(OpenStreamTest, Brotli) {
  20293. Client cli("127.0.0.1", port_);
  20294. auto handle =
  20295. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20296. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20297. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20298. }
  20299. #endif
  20300. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20301. TEST_F(OpenStreamTest, Zstd) {
  20302. Client cli("127.0.0.1", port_);
  20303. auto handle = cli.open_stream("GET", "/compressible", {},
  20304. {{"Accept-Encoding", "zstd"}});
  20305. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20306. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20307. }
  20308. #endif
  20309. #ifdef CPPHTTPLIB_SSL_ENABLED
  20310. class SSLOpenStreamTest : public ::testing::Test {
  20311. protected:
  20312. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20313. void SetUp() override {
  20314. svr_.Get("/hello", [](const Request &, Response &res) {
  20315. res.set_content("Hello SSL World!", "text/plain");
  20316. });
  20317. svr_.Get("/chunked", [](const Request &, Response &res) {
  20318. res.set_chunked_content_provider("text/plain",
  20319. [](size_t offset, DataSink &sink) {
  20320. if (offset < 15) {
  20321. sink.write("chunk", 5);
  20322. return true;
  20323. }
  20324. sink.done();
  20325. return true;
  20326. });
  20327. });
  20328. svr_.Post("/echo", [](const Request &req, Response &res) {
  20329. res.set_content(req.body, req.get_header_value("Content-Type"));
  20330. });
  20331. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20332. std::string body = req.body;
  20333. res.set_chunked_content_provider(
  20334. "text/plain", [body](size_t offset, DataSink &sink) {
  20335. if (offset < body.size()) {
  20336. sink.write(body.data() + offset, body.size() - offset);
  20337. }
  20338. sink.done();
  20339. return true;
  20340. });
  20341. });
  20342. port_ = svr_.bind_to_any_port("127.0.0.1");
  20343. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20344. svr_.wait_until_ready();
  20345. }
  20346. void TearDown() override {
  20347. svr_.stop();
  20348. if (thread_.joinable()) thread_.join();
  20349. }
  20350. SSLServer svr_;
  20351. std::thread thread_;
  20352. int port_ = 0;
  20353. };
  20354. TEST_F(SSLOpenStreamTest, Basic) {
  20355. SSLClient cli("127.0.0.1", port_);
  20356. cli.enable_server_certificate_verification(false);
  20357. auto handle = cli.open_stream("GET", "/hello");
  20358. ASSERT_TRUE(handle.is_valid());
  20359. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20360. }
  20361. TEST_F(SSLOpenStreamTest, Chunked) {
  20362. SSLClient cli("127.0.0.1", port_);
  20363. cli.enable_server_certificate_verification(false);
  20364. auto handle = cli.open_stream("GET", "/chunked");
  20365. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20366. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20367. "Transfer-Encoding") == "chunked");
  20368. auto body = read_all(handle);
  20369. EXPECT_EQ("chunkchunkchunk", body);
  20370. }
  20371. TEST_F(SSLOpenStreamTest, Post) {
  20372. SSLClient cli("127.0.0.1", port_);
  20373. cli.enable_server_certificate_verification(false);
  20374. auto handle =
  20375. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20376. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20377. EXPECT_EQ(200, handle.response->status);
  20378. auto body = read_all(handle);
  20379. EXPECT_EQ("Hello SSL POST", body);
  20380. }
  20381. TEST_F(SSLOpenStreamTest, PostChunked) {
  20382. SSLClient cli("127.0.0.1", port_);
  20383. cli.enable_server_certificate_verification(false);
  20384. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20385. "Chunked SSL Data", "text/plain");
  20386. ASSERT_TRUE(handle.is_valid());
  20387. EXPECT_EQ(200, handle.response->status);
  20388. auto body = read_all(handle);
  20389. EXPECT_EQ("Chunked SSL Data", body);
  20390. }
  20391. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20392. // Content-Length is terminated by the server closing the connection. When the
  20393. // SSL peer sends a close_notify after the body, the client must treat it as a
  20394. // clean EOF and return a successful response rather than an error.
  20395. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20397. ASSERT_TRUE(svr.is_valid());
  20398. svr.set_keep_alive_max_count(1);
  20399. const std::string expected_body = "Hello from connection-close response!";
  20400. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20401. res.set_content_provider("text/plain",
  20402. [&](size_t offset, DataSink &sink) -> bool {
  20403. if (offset < expected_body.size()) {
  20404. sink.write(expected_body.data() + offset,
  20405. expected_body.size() - offset);
  20406. }
  20407. sink.done();
  20408. return true;
  20409. });
  20410. });
  20411. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20412. auto se = detail::scope_exit([&] {
  20413. svr.stop();
  20414. listen_thread.join();
  20415. ASSERT_FALSE(svr.is_running());
  20416. });
  20417. svr.wait_until_ready();
  20418. SSLClient cli(HOST, PORT);
  20419. cli.enable_server_certificate_verification(false);
  20420. auto res = cli.Get("/no-content-length");
  20421. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20422. EXPECT_EQ(StatusCode::OK_200, res->status);
  20423. EXPECT_EQ(expected_body, res->body);
  20424. }
  20425. #endif // CPPHTTPLIB_SSL_ENABLED
  20426. //==============================================================================
  20427. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20428. // results for various scenarios.
  20429. //==============================================================================
  20430. TEST(ParityTest, GetVsOpenStream) {
  20431. Server svr;
  20432. const std::string path = "/parity";
  20433. const std::string content = "Parity test content: hello world";
  20434. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20435. res.set_content(content, "text/plain");
  20436. });
  20437. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20438. auto se = detail::scope_exit([&] {
  20439. svr.stop();
  20440. t.join();
  20441. ASSERT_FALSE(svr.is_running());
  20442. });
  20443. svr.wait_until_ready();
  20444. Client cli(HOST, PORT);
  20445. // Non-stream path
  20446. auto r1 = cli.Get(path);
  20447. ASSERT_TRUE(r1);
  20448. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20449. // Stream path
  20450. auto h = cli.open_stream("GET", path);
  20451. ASSERT_TRUE(h.is_valid());
  20452. EXPECT_EQ(r1->body, read_all(h));
  20453. }
  20454. // Helper to compress data with provided compressor type T
  20455. template <typename Compressor>
  20456. static std::string compress_payload_for_parity(const std::string &in) {
  20457. std::string out;
  20458. Compressor compressor;
  20459. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20460. [&](const char *data, size_t n) {
  20461. out.append(data, n);
  20462. return true;
  20463. });
  20464. EXPECT_TRUE(ok);
  20465. return out;
  20466. }
  20467. // Helper function for compression parity tests
  20468. template <typename Compressor>
  20469. static void test_compression_parity(const std::string &original,
  20470. const std::string &path,
  20471. const std::string &encoding) {
  20472. const std::string compressed =
  20473. compress_payload_for_parity<Compressor>(original);
  20474. Server svr;
  20475. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20476. res.set_content(compressed, "application/octet-stream");
  20477. res.set_header("Content-Encoding", encoding);
  20478. });
  20479. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20480. auto se = detail::scope_exit([&] {
  20481. svr.stop();
  20482. t.join();
  20483. ASSERT_FALSE(svr.is_running());
  20484. });
  20485. svr.wait_until_ready();
  20486. Client cli(HOST, PORT);
  20487. // Non-streaming
  20488. {
  20489. auto res = cli.Get(path);
  20490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20491. EXPECT_EQ(StatusCode::OK_200, res->status);
  20492. EXPECT_EQ(original, res->body);
  20493. }
  20494. // Streaming
  20495. {
  20496. auto h = cli.open_stream("GET", path);
  20497. ASSERT_TRUE(h.is_valid());
  20498. EXPECT_EQ(original, read_all(h));
  20499. }
  20500. }
  20501. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20502. TEST(ParityTest, Gzip) {
  20503. test_compression_parity<detail::gzip_compressor>(
  20504. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20505. }
  20506. #endif
  20507. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20508. TEST(ParityTest, Brotli) {
  20509. test_compression_parity<detail::brotli_compressor>(
  20510. "Hello, brotli parity test payload", "/parity-br", "br");
  20511. }
  20512. #endif
  20513. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20514. TEST(ParityTest, Zstd) {
  20515. test_compression_parity<detail::zstd_compressor>(
  20516. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20517. }
  20518. #endif
  20519. //==============================================================================
  20520. // New Stream API Tests
  20521. //==============================================================================
  20522. inline std::string read_body(httplib::stream::Result &result) {
  20523. std::string body;
  20524. while (result.next()) {
  20525. body.append(result.data(), result.size());
  20526. }
  20527. return body;
  20528. }
  20529. TEST(ClientConnectionTest, Basic) {
  20530. httplib::ClientConnection conn;
  20531. EXPECT_FALSE(conn.is_open());
  20532. conn.sock = 1;
  20533. EXPECT_TRUE(conn.is_open());
  20534. httplib::ClientConnection conn2(std::move(conn));
  20535. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20536. conn2.sock = INVALID_SOCKET;
  20537. }
  20538. // Unified test server for all stream::* tests
  20539. class StreamApiTest : public ::testing::Test {
  20540. protected:
  20541. void SetUp() override {
  20542. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20543. res.set_content("Hello World!", "text/plain");
  20544. });
  20545. svr_.Get("/echo-params",
  20546. [](const httplib::Request &req, httplib::Response &res) {
  20547. std::string r;
  20548. for (const auto &p : req.params) {
  20549. if (!r.empty()) r += "&";
  20550. r += p.first + "=" + p.second;
  20551. }
  20552. res.set_content(r, "text/plain");
  20553. });
  20554. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20555. res.set_content(req.body, req.get_header_value("Content-Type"));
  20556. });
  20557. svr_.Post("/echo-headers",
  20558. [](const httplib::Request &req, httplib::Response &res) {
  20559. std::string r;
  20560. for (const auto &h : req.headers)
  20561. r += h.first + ": " + h.second + "\n";
  20562. res.set_content(r, "text/plain");
  20563. });
  20564. svr_.Post("/echo-params",
  20565. [](const httplib::Request &req, httplib::Response &res) {
  20566. std::string r = "params:";
  20567. for (const auto &p : req.params)
  20568. r += p.first + "=" + p.second + ";";
  20569. res.set_content(r + " body:" + req.body, "text/plain");
  20570. });
  20571. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20572. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20573. });
  20574. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20575. res.set_content("PUT:" + req.body, "text/plain");
  20576. });
  20577. svr_.Patch("/echo",
  20578. [](const httplib::Request &req, httplib::Response &res) {
  20579. res.set_content("PATCH:" + req.body, "text/plain");
  20580. });
  20581. svr_.Delete(
  20582. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20583. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20584. "text/plain");
  20585. });
  20586. svr_.Get("/head-test",
  20587. [](const httplib::Request &, httplib::Response &res) {
  20588. res.set_content("body for HEAD", "text/plain");
  20589. });
  20590. svr_.Options("/options",
  20591. [](const httplib::Request &, httplib::Response &res) {
  20592. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20593. });
  20594. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20595. svr_.wait_until_ready();
  20596. }
  20597. void TearDown() override {
  20598. svr_.stop();
  20599. if (thread_.joinable()) thread_.join();
  20600. }
  20601. httplib::Server svr_;
  20602. std::thread thread_;
  20603. };
  20604. // stream::Get tests
  20605. TEST_F(StreamApiTest, GetBasic) {
  20606. httplib::Client cli(HOST, PORT);
  20607. auto result = httplib::stream::Get(cli, "/hello");
  20608. ASSERT_TRUE(result.is_valid());
  20609. EXPECT_EQ(200, result.status());
  20610. EXPECT_EQ("Hello World!", read_body(result));
  20611. }
  20612. TEST_F(StreamApiTest, GetWithParams) {
  20613. httplib::Client cli(HOST, PORT);
  20614. httplib::Params params{{"foo", "bar"}};
  20615. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20616. ASSERT_TRUE(result.is_valid());
  20617. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20618. }
  20619. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20620. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20621. httplib::Client cli(HOST, PORT);
  20622. cli.set_payload_max_length(0);
  20623. auto result = httplib::stream::Get(cli, "/hello");
  20624. ASSERT_TRUE(result.is_valid());
  20625. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20626. EXPECT_EQ("Hello World!", read_body(result));
  20627. }
  20628. #endif
  20629. TEST_F(StreamApiTest, GetConnectionError) {
  20630. httplib::Client cli(HOST, 9999);
  20631. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20632. }
  20633. TEST_F(StreamApiTest, Get404) {
  20634. httplib::Client cli(HOST, PORT);
  20635. auto result = httplib::stream::Get(cli, "/nonexistent");
  20636. EXPECT_TRUE(result.is_valid());
  20637. EXPECT_EQ(404, result.status());
  20638. }
  20639. // stream::Post tests
  20640. TEST_F(StreamApiTest, PostBasic) {
  20641. httplib::Client cli(HOST, PORT);
  20642. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20643. "application/json");
  20644. ASSERT_TRUE(result.is_valid());
  20645. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20646. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20647. }
  20648. TEST_F(StreamApiTest, PostWithHeaders) {
  20649. httplib::Client cli(HOST, PORT);
  20650. httplib::Headers headers{{"X-Custom", "value"}};
  20651. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20652. "text/plain");
  20653. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20654. }
  20655. TEST_F(StreamApiTest, PostWithParams) {
  20656. httplib::Client cli(HOST, PORT);
  20657. httplib::Params params{{"k", "v"}};
  20658. auto result =
  20659. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20660. auto body = read_body(result);
  20661. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20662. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20663. }
  20664. TEST_F(StreamApiTest, PostLarge) {
  20665. httplib::Client cli(HOST, PORT);
  20666. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20667. size_t total = 0;
  20668. while (result.next()) {
  20669. total += result.size();
  20670. }
  20671. EXPECT_EQ(100u * 1024u, total);
  20672. }
  20673. // stream::Put/Patch tests
  20674. TEST_F(StreamApiTest, PutAndPatch) {
  20675. httplib::Client cli(HOST, PORT);
  20676. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20677. EXPECT_EQ("PUT:test", read_body(put));
  20678. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20679. EXPECT_EQ("PATCH:test", read_body(patch));
  20680. }
  20681. // stream::Delete tests
  20682. TEST_F(StreamApiTest, Delete) {
  20683. httplib::Client cli(HOST, PORT);
  20684. auto del1 = httplib::stream::Delete(cli, "/resource");
  20685. EXPECT_EQ("Deleted", read_body(del1));
  20686. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20687. EXPECT_EQ("Deleted:data", read_body(del2));
  20688. }
  20689. // stream::Head/Options tests
  20690. TEST_F(StreamApiTest, HeadAndOptions) {
  20691. httplib::Client cli(HOST, PORT);
  20692. auto head = httplib::stream::Head(cli, "/head-test");
  20693. EXPECT_TRUE(head.is_valid());
  20694. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20695. auto opts = httplib::stream::Options(cli, "/options");
  20696. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20697. }
  20698. // SSL stream::* tests
  20699. #ifdef CPPHTTPLIB_SSL_ENABLED
  20700. class SSLStreamApiTest : public ::testing::Test {
  20701. protected:
  20702. void SetUp() override {
  20703. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20704. res.set_content("Hello SSL!", "text/plain");
  20705. });
  20706. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20707. res.set_content(req.body, "text/plain");
  20708. });
  20709. port_ = svr_.bind_to_any_port("127.0.0.1");
  20710. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20711. svr_.wait_until_ready();
  20712. }
  20713. void TearDown() override {
  20714. svr_.stop();
  20715. if (thread_.joinable()) thread_.join();
  20716. }
  20717. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20718. std::thread thread_;
  20719. int port_ = 0;
  20720. };
  20721. TEST_F(SSLStreamApiTest, GetAndPost) {
  20722. httplib::SSLClient cli("127.0.0.1", port_);
  20723. cli.enable_server_certificate_verification(false);
  20724. auto get = httplib::stream::Get(cli, "/hello");
  20725. EXPECT_EQ("Hello SSL!", read_body(get));
  20726. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20727. EXPECT_EQ("test", read_body(post));
  20728. }
  20729. #endif
  20730. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20731. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20732. // BodyReader
  20733. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20734. // Test that read timeout during streaming is detected
  20735. // Use a large content-length response where server delays mid-stream
  20736. Server svr;
  20737. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20738. // Send a large response with delay in the middle
  20739. res.set_content_provider(
  20740. 1000, // content_length
  20741. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20742. if (offset < 100) {
  20743. // Send first 100 bytes immediately
  20744. std::string data(100, 'A');
  20745. sink.write(data.c_str(), data.size());
  20746. return true;
  20747. }
  20748. // Then delay longer than client timeout
  20749. std::this_thread::sleep_for(std::chrono::seconds(3));
  20750. std::string data(900, 'B');
  20751. sink.write(data.c_str(), data.size());
  20752. return true;
  20753. });
  20754. });
  20755. auto port = 8091;
  20756. std::thread t([&]() { svr.listen("localhost", port); });
  20757. svr.wait_until_ready();
  20758. Client cli("localhost", port);
  20759. cli.set_read_timeout(1, 0); // 1 second timeout
  20760. auto handle = cli.open_stream("GET", "/slow-stream");
  20761. ASSERT_TRUE(handle.is_valid());
  20762. char buf[256];
  20763. ssize_t total = 0;
  20764. ssize_t n;
  20765. bool got_error = false;
  20766. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20767. total += n;
  20768. }
  20769. if (n < 0) {
  20770. got_error = true;
  20771. // Should be timeout or read error
  20772. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20773. handle.get_read_error() == Error::Read)
  20774. << "Actual error: " << to_string(handle.get_read_error());
  20775. }
  20776. // Either we got an error, or we got less data than expected
  20777. EXPECT_TRUE(got_error || total < 1000)
  20778. << "Expected timeout but got all " << total << " bytes";
  20779. svr.stop();
  20780. t.join();
  20781. }
  20782. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20783. // Test connection closed detection via BodyReader
  20784. Server svr;
  20785. std::atomic<bool> close_now{false};
  20786. svr.Get("/will-close", [&](const Request &, Response &res) {
  20787. res.set_content_provider(
  20788. 10000, // Large content_length that we won't fully send
  20789. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20790. if (offset < 100) {
  20791. std::string data(100, 'X');
  20792. sink.write(data.c_str(), data.size());
  20793. return true;
  20794. }
  20795. // Wait for signal then abort
  20796. while (!close_now) {
  20797. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20798. }
  20799. return false; // Abort - server will close connection
  20800. });
  20801. });
  20802. auto port = 8092;
  20803. std::thread t([&]() { svr.listen("localhost", port); });
  20804. svr.wait_until_ready();
  20805. Client cli("localhost", port);
  20806. auto handle = cli.open_stream("GET", "/will-close");
  20807. ASSERT_TRUE(handle.is_valid());
  20808. char buf[256];
  20809. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20810. EXPECT_GT(n, 0) << "First read should succeed";
  20811. // Signal server to close
  20812. close_now = true;
  20813. // Keep reading until error or EOF
  20814. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20815. // Keep reading
  20816. }
  20817. // Should get an error since content_length wasn't satisfied
  20818. if (n < 0) {
  20819. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20820. handle.get_read_error() == Error::Read)
  20821. << "Actual error: " << to_string(handle.get_read_error());
  20822. }
  20823. svr.stop();
  20824. t.join();
  20825. }
  20826. #ifdef CPPHTTPLIB_SSL_ENABLED
  20827. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20828. // Test that read timeout during SSL streaming is detected
  20829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20830. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20831. res.set_content_provider(
  20832. 1000, "text/plain",
  20833. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20834. if (offset < 100) {
  20835. std::string data(100, 'A');
  20836. sink.write(data.c_str(), data.size());
  20837. return true;
  20838. }
  20839. std::this_thread::sleep_for(std::chrono::seconds(3));
  20840. std::string data(900, 'B');
  20841. sink.write(data.c_str(), data.size());
  20842. return true;
  20843. });
  20844. });
  20845. auto port = 8093;
  20846. std::thread t([&]() { svr.listen("localhost", port); });
  20847. svr.wait_until_ready();
  20848. SSLClient cli("localhost", port);
  20849. cli.enable_server_certificate_verification(false);
  20850. cli.set_read_timeout(1, 0); // 1 second timeout
  20851. auto handle = cli.open_stream("GET", "/slow-stream");
  20852. ASSERT_TRUE(handle.is_valid());
  20853. char buf[256];
  20854. ssize_t total = 0;
  20855. ssize_t n;
  20856. bool got_error = false;
  20857. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20858. total += n;
  20859. }
  20860. if (n < 0) {
  20861. got_error = true;
  20862. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20863. handle.get_read_error() == Error::Read)
  20864. << "Actual error: " << to_string(handle.get_read_error());
  20865. }
  20866. EXPECT_TRUE(got_error || total < 1000)
  20867. << "Expected timeout but got all " << total << " bytes";
  20868. svr.stop();
  20869. t.join();
  20870. }
  20871. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20872. // Test SSL connection closed detection
  20873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20874. std::atomic<bool> close_now{false};
  20875. svr.Get("/will-close", [&](const Request &, Response &res) {
  20876. res.set_content_provider(
  20877. 10000, "text/plain",
  20878. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20879. if (offset < 100) {
  20880. std::string data(100, 'X');
  20881. sink.write(data.c_str(), data.size());
  20882. return true;
  20883. }
  20884. while (!close_now) {
  20885. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20886. }
  20887. return false;
  20888. });
  20889. });
  20890. auto port = 8094;
  20891. std::thread t([&]() { svr.listen("localhost", port); });
  20892. svr.wait_until_ready();
  20893. SSLClient cli("localhost", port);
  20894. cli.enable_server_certificate_verification(false);
  20895. auto handle = cli.open_stream("GET", "/will-close");
  20896. ASSERT_TRUE(handle.is_valid());
  20897. char buf[256];
  20898. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20899. EXPECT_GT(n, 0);
  20900. // Signal server to close
  20901. close_now = true;
  20902. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20903. // Keep reading
  20904. }
  20905. if (n < 0) {
  20906. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20907. handle.get_read_error() == Error::Read)
  20908. << "Actual error: " << to_string(handle.get_read_error());
  20909. }
  20910. svr.stop();
  20911. t.join();
  20912. }
  20913. #endif
  20914. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20915. using namespace httplib;
  20916. // Create a test file
  20917. const char *fname = "etag_testfile.txt";
  20918. const char *content = "etag-content";
  20919. {
  20920. std::ofstream ofs(fname);
  20921. ofs << content;
  20922. ASSERT_TRUE(ofs.good());
  20923. }
  20924. Server svr;
  20925. svr.set_mount_point("/static", ".");
  20926. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20927. svr.wait_until_ready();
  20928. Client cli(HOST, PORT);
  20929. // First request: should get 200 with ETag header
  20930. auto res1 = cli.Get("/static/etag_testfile.txt");
  20931. ASSERT_TRUE(res1);
  20932. ASSERT_EQ(200, res1->status);
  20933. ASSERT_TRUE(res1->has_header("ETag"));
  20934. std::string etag = res1->get_header_value("ETag");
  20935. EXPECT_FALSE(etag.empty());
  20936. // Verify ETag format: W/"hex-hex"
  20937. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20938. EXPECT_EQ('W', etag[0]);
  20939. EXPECT_EQ('/', etag[1]);
  20940. EXPECT_EQ('"', etag[2]);
  20941. EXPECT_EQ('"', etag.back());
  20942. // Exact match: expect 304 Not Modified
  20943. Headers h2 = {{"If-None-Match", etag}};
  20944. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20945. ASSERT_TRUE(res2);
  20946. EXPECT_EQ(304, res2->status);
  20947. // Wildcard match: expect 304 Not Modified
  20948. Headers h3 = {{"If-None-Match", "*"}};
  20949. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20950. ASSERT_TRUE(res3);
  20951. EXPECT_EQ(304, res3->status);
  20952. // Non-matching ETag: expect 200
  20953. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20954. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20955. ASSERT_TRUE(res4);
  20956. EXPECT_EQ(200, res4->status);
  20957. // Multiple ETags with one matching: expect 304
  20958. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20959. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20960. ASSERT_TRUE(res5);
  20961. EXPECT_EQ(304, res5->status);
  20962. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20963. // that equivalent to the single comma-separated list above, so the match on
  20964. // the second line must still be found.
  20965. Headers h6;
  20966. h6.emplace("If-None-Match", "W/\"other\"");
  20967. h6.emplace("If-None-Match", etag);
  20968. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20969. ASSERT_TRUE(res6);
  20970. EXPECT_EQ(304, res6->status);
  20971. svr.stop();
  20972. t.join();
  20973. std::remove(fname);
  20974. }
  20975. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20976. using namespace httplib;
  20977. Server svr;
  20978. svr.set_mount_point("/static", ".");
  20979. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20980. svr.wait_until_ready();
  20981. Client cli(HOST, PORT);
  20982. // Send If-None-Match: * to a non-existent file
  20983. Headers h = {{"If-None-Match", "*"}};
  20984. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20986. EXPECT_EQ(404, res->status);
  20987. svr.stop();
  20988. t.join();
  20989. }
  20990. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20991. using namespace httplib;
  20992. // Create a test file
  20993. const char *fname = "etag_boundary_testfile.txt";
  20994. const char *content = "boundary-test";
  20995. {
  20996. std::ofstream ofs(fname);
  20997. ofs << content;
  20998. ASSERT_TRUE(ofs.good());
  20999. }
  21000. Server svr;
  21001. svr.set_mount_point("/static", ".");
  21002. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21003. svr.wait_until_ready();
  21004. Client cli(HOST, PORT);
  21005. // Get the actual ETag
  21006. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21007. ASSERT_TRUE(res1);
  21008. ASSERT_EQ(200, res1->status);
  21009. ASSERT_TRUE(res1->has_header("ETag"));
  21010. std::string etag = res1->get_header_value("ETag");
  21011. // Test 1: Very long ETag value (longer than actual ETag)
  21012. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21013. Headers h1 = {{"If-None-Match", "W/"
  21014. "\"very-long-etag-value-that-is-much-longer-"
  21015. "than-the-actual-etag-value\""}};
  21016. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21017. ASSERT_TRUE(res2);
  21018. EXPECT_EQ(200, res2->status); // Should not match
  21019. // Test 2: Long string followed by wildcard
  21020. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21021. // string)
  21022. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21023. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21024. ASSERT_TRUE(res3);
  21025. EXPECT_EQ(304, res3->status); // Should match on "*"
  21026. // Test 3: Wildcard followed by long string
  21027. // Should match on "*" immediately and return 304
  21028. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21029. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21030. ASSERT_TRUE(res4);
  21031. EXPECT_EQ(304, res4->status); // Should match on "*"
  21032. // Test 4: Multiple long non-matching values
  21033. // Should NOT match and return 200 (test that all comparisons are safe)
  21034. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21035. "W/\"second-long-non-matching-value\", "
  21036. "W/\"third-long-non-matching-value\""}};
  21037. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21038. ASSERT_TRUE(res5);
  21039. EXPECT_EQ(200, res5->status); // Should not match
  21040. // Test 5: Single character that is not "*" (edge case)
  21041. Headers h5 = {{"If-None-Match", "X"}};
  21042. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21043. ASSERT_TRUE(res6);
  21044. EXPECT_EQ(200, res6->status); // Should not match
  21045. svr.stop();
  21046. t.join();
  21047. std::remove(fname);
  21048. }
  21049. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21050. using namespace httplib;
  21051. // Create a test file
  21052. const char *fname = "ims_testfile.txt";
  21053. const char *content = "if-modified-since-test";
  21054. {
  21055. std::ofstream ofs(fname);
  21056. ofs << content;
  21057. ASSERT_TRUE(ofs.good());
  21058. }
  21059. Server svr;
  21060. svr.set_mount_point("/static", ".");
  21061. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21062. svr.wait_until_ready();
  21063. Client cli(HOST, PORT);
  21064. // First request: should get 200 with Last-Modified header
  21065. auto res1 = cli.Get("/static/ims_testfile.txt");
  21066. ASSERT_TRUE(res1);
  21067. ASSERT_EQ(200, res1->status);
  21068. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21069. std::string last_modified = res1->get_header_value("Last-Modified");
  21070. EXPECT_FALSE(last_modified.empty());
  21071. // If-Modified-Since with same time: expect 304
  21072. Headers h2 = {{"If-Modified-Since", last_modified}};
  21073. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21074. ASSERT_TRUE(res2);
  21075. EXPECT_EQ(304, res2->status);
  21076. // If-Modified-Since with future time: expect 304
  21077. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21078. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21079. ASSERT_TRUE(res3);
  21080. EXPECT_EQ(304, res3->status);
  21081. // If-Modified-Since with past time: expect 200
  21082. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21083. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21084. ASSERT_TRUE(res4);
  21085. EXPECT_EQ(200, res4->status);
  21086. // If-None-Match takes precedence over If-Modified-Since
  21087. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21088. ASSERT_TRUE(res1->has_header("ETag"));
  21089. std::string etag = res1->get_header_value("ETag");
  21090. Headers h5 = {{"If-None-Match", etag},
  21091. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21092. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21093. ASSERT_TRUE(res5);
  21094. EXPECT_EQ(304, res5->status);
  21095. svr.stop();
  21096. t.join();
  21097. std::remove(fname);
  21098. }
  21099. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21100. using namespace httplib;
  21101. Server svr;
  21102. // Endpoint that returns compressible content
  21103. svr.Get("/compressible", [](const Request &, Response &res) {
  21104. // Return a large enough body to trigger compression
  21105. std::string body(1000, 'a');
  21106. res.set_content(body, "text/plain");
  21107. });
  21108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21109. svr.wait_until_ready();
  21110. Client cli(HOST, PORT);
  21111. // Request with gzip support: should get Vary header when compressed
  21112. cli.set_compress(true);
  21113. auto res1 = cli.Get("/compressible");
  21114. ASSERT_TRUE(res1);
  21115. EXPECT_EQ(200, res1->status);
  21116. // If Content-Encoding is set, Vary should also be set
  21117. if (res1->has_header("Content-Encoding")) {
  21118. EXPECT_TRUE(res1->has_header("Vary"));
  21119. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21120. }
  21121. // Request without Accept-Encoding header: should not have compression
  21122. Headers h_no_compress;
  21123. auto res2 = cli.Get("/compressible", h_no_compress);
  21124. ASSERT_TRUE(res2);
  21125. EXPECT_EQ(200, res2->status);
  21126. // Verify Vary header is present when compression is applied
  21127. // (the exact behavior depends on server configuration)
  21128. svr.stop();
  21129. t.join();
  21130. }
  21131. TEST(ETagTest, IfRangeWithETag) {
  21132. using namespace httplib;
  21133. // Create a test file with known content
  21134. const char *fname = "if_range_testfile.txt";
  21135. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21136. {
  21137. std::ofstream ofs(fname);
  21138. ofs << content;
  21139. ASSERT_TRUE(ofs.good());
  21140. }
  21141. Server svr;
  21142. svr.set_mount_point("/static", ".");
  21143. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21144. svr.wait_until_ready();
  21145. Client cli(HOST, PORT);
  21146. // First request: get ETag
  21147. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21148. ASSERT_TRUE(res1);
  21149. ASSERT_EQ(200, res1->status);
  21150. ASSERT_TRUE(res1->has_header("ETag"));
  21151. std::string etag = res1->get_header_value("ETag");
  21152. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21153. // Since our server generates weak ETags (W/"..."), If-Range with our
  21154. // ETag should NOT result in partial content - it should return full content.
  21155. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21156. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21157. ASSERT_TRUE(res2);
  21158. // Weak ETag in If-Range -> full content (200), not partial (206)
  21159. EXPECT_EQ(200, res2->status);
  21160. EXPECT_EQ(content, res2->body);
  21161. EXPECT_FALSE(res2->has_header("Content-Range"));
  21162. // Range request with non-matching If-Range (ETag): should get 200 (full
  21163. // content)
  21164. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21165. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21166. ASSERT_TRUE(res3);
  21167. EXPECT_EQ(200, res3->status);
  21168. EXPECT_EQ(content, res3->body);
  21169. EXPECT_FALSE(res3->has_header("Content-Range"));
  21170. // Range request with strong ETag (hypothetical - our server doesn't generate
  21171. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21172. // should return full content)
  21173. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21174. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21175. ASSERT_TRUE(res4);
  21176. EXPECT_EQ(200, res4->status);
  21177. EXPECT_EQ(content, res4->body);
  21178. EXPECT_FALSE(res4->has_header("Content-Range"));
  21179. svr.stop();
  21180. t.join();
  21181. std::remove(fname);
  21182. }
  21183. TEST(ETagTest, IfRangeWithDate) {
  21184. using namespace httplib;
  21185. // Create a test file
  21186. const char *fname = "if_range_date_testfile.txt";
  21187. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21188. {
  21189. std::ofstream ofs(fname);
  21190. ofs << content;
  21191. ASSERT_TRUE(ofs.good());
  21192. }
  21193. Server svr;
  21194. svr.set_mount_point("/static", ".");
  21195. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21196. svr.wait_until_ready();
  21197. Client cli(HOST, PORT);
  21198. // First request: get Last-Modified
  21199. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21200. ASSERT_TRUE(res1);
  21201. ASSERT_EQ(200, res1->status);
  21202. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21203. std::string last_modified = res1->get_header_value("Last-Modified");
  21204. // Range request with matching If-Range (date): should get 206
  21205. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21206. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21207. ASSERT_TRUE(res2);
  21208. EXPECT_EQ(206, res2->status);
  21209. EXPECT_EQ("FGHIJ", res2->body);
  21210. // Range request with old If-Range date: should get 200 (full content)
  21211. Headers h3 = {{"Range", "bytes=5-9"},
  21212. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21213. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21214. ASSERT_TRUE(res3);
  21215. EXPECT_EQ(200, res3->status);
  21216. EXPECT_EQ(content, res3->body);
  21217. // Range request with future If-Range date: should get 206
  21218. Headers h4 = {{"Range", "bytes=0-4"},
  21219. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21220. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21221. ASSERT_TRUE(res4);
  21222. EXPECT_EQ(206, res4->status);
  21223. EXPECT_EQ("ABCDE", res4->body);
  21224. svr.stop();
  21225. t.join();
  21226. std::remove(fname);
  21227. }
  21228. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21229. using namespace httplib;
  21230. const char *fname = "etag_malformed.txt";
  21231. const char *content = "malformed-etag";
  21232. {
  21233. std::ofstream ofs(fname);
  21234. ofs << content;
  21235. ASSERT_TRUE(ofs.good());
  21236. }
  21237. Server svr;
  21238. svr.set_mount_point("/static", ".");
  21239. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21240. svr.wait_until_ready();
  21241. Client cli(HOST, PORT);
  21242. // baseline: should get 200 and an ETag
  21243. auto res1 = cli.Get("/static/etag_malformed.txt");
  21244. ASSERT_TRUE(res1);
  21245. ASSERT_EQ(200, res1->status);
  21246. ASSERT_TRUE(res1->has_header("ETag"));
  21247. // Malformed ETag value (missing quotes) should be treated as non-matching
  21248. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21249. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21250. ASSERT_TRUE(res_bad);
  21251. EXPECT_EQ(200, res_bad->status);
  21252. // Whitespace-only header value should be considered invalid / non-matching
  21253. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21254. "Host: localhost\r\n"
  21255. "If-None-Match: \r\n"
  21256. "Connection: close\r\n"
  21257. "\r\n";
  21258. std::string out;
  21259. ASSERT_TRUE(send_request(5, raw_req, &out));
  21260. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21261. svr.stop();
  21262. t.join();
  21263. std::remove(fname);
  21264. }
  21265. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21266. using namespace httplib;
  21267. const char *fname = "ims_invalid_format.txt";
  21268. const char *content = "ims-bad-format";
  21269. {
  21270. std::ofstream ofs(fname);
  21271. ofs << content;
  21272. ASSERT_TRUE(ofs.good());
  21273. }
  21274. Server svr;
  21275. svr.set_mount_point("/static", ".");
  21276. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21277. svr.wait_until_ready();
  21278. Client cli(HOST, PORT);
  21279. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21280. ASSERT_TRUE(res1);
  21281. ASSERT_EQ(200, res1->status);
  21282. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21283. // If-Modified-Since with invalid format should not result in 304
  21284. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21285. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21286. ASSERT_TRUE(res_bad);
  21287. EXPECT_EQ(200, res_bad->status);
  21288. // If-Range with invalid date format should be treated as mismatch -> full
  21289. // content (200)
  21290. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21291. {"If-Range", "invalid-date"}};
  21292. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21293. ASSERT_TRUE(res_ifrange);
  21294. EXPECT_EQ(200, res_ifrange->status);
  21295. svr.stop();
  21296. t.join();
  21297. std::remove(fname);
  21298. }
  21299. TEST(ETagTest, IfRangeWithMalformedETag) {
  21300. using namespace httplib;
  21301. const char *fname = "ifrange_malformed.txt";
  21302. const std::string content = "0123456789";
  21303. {
  21304. std::ofstream ofs(fname);
  21305. ofs << content;
  21306. ASSERT_TRUE(ofs.good());
  21307. }
  21308. Server svr;
  21309. svr.set_mount_point("/static", ".");
  21310. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21311. svr.wait_until_ready();
  21312. Client cli(HOST, PORT);
  21313. // First request: get ETag
  21314. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21315. ASSERT_TRUE(res1);
  21316. ASSERT_EQ(200, res1->status);
  21317. ASSERT_TRUE(res1->has_header("ETag"));
  21318. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21319. // full content (200)
  21320. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21321. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21322. ASSERT_TRUE(res2);
  21323. EXPECT_EQ(200, res2->status);
  21324. EXPECT_EQ(content, res2->body);
  21325. svr.stop();
  21326. t.join();
  21327. std::remove(fname);
  21328. }
  21329. TEST(ETagTest, ExtremeLargeDateValues) {
  21330. using namespace httplib;
  21331. const char *fname = "ims_extreme_date.txt";
  21332. const char *content = "ims-extreme-date";
  21333. {
  21334. std::ofstream ofs(fname);
  21335. ofs << content;
  21336. ASSERT_TRUE(ofs.good());
  21337. }
  21338. Server svr;
  21339. svr.set_mount_point("/static", ".");
  21340. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21341. svr.wait_until_ready();
  21342. Client cli(HOST, PORT);
  21343. auto res1 = cli.Get(std::string("/static/") + fname);
  21344. ASSERT_TRUE(res1);
  21345. ASSERT_EQ(200, res1->status);
  21346. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21347. // Extremely large year that may overflow date parsing routines.
  21348. Headers h_large_date = {
  21349. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21350. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21351. ASSERT_TRUE(res_bad);
  21352. // Expect server to treat this as invalid/mismatch and return full content
  21353. EXPECT_EQ(200, res_bad->status);
  21354. // If-Range with extremely large date should be treated as mismatch -> full
  21355. // content (200)
  21356. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21357. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21358. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21359. ASSERT_TRUE(res_ifrange);
  21360. EXPECT_EQ(200, res_ifrange->status);
  21361. svr.stop();
  21362. t.join();
  21363. std::remove(fname);
  21364. }
  21365. TEST(ETagTest, NegativeFileModificationTime) {
  21366. using namespace httplib;
  21367. const char *fname = "ims_negative_mtime.txt";
  21368. const std::string content = "negative-mtime";
  21369. {
  21370. std::ofstream ofs(fname);
  21371. ofs << content;
  21372. ASSERT_TRUE(ofs.good());
  21373. }
  21374. // Try to set file mtime to a negative value. This may fail on some
  21375. // platforms/filesystems; if it fails, the test will still verify server
  21376. // behaves safely by performing a regular conditional request.
  21377. #if defined(__APPLE__) || defined(__linux__)
  21378. bool set_negative = false;
  21379. do {
  21380. struct timeval times[2];
  21381. // access time: now
  21382. times[0].tv_sec = time(nullptr);
  21383. times[0].tv_usec = 0;
  21384. // modification time: negative (e.g., -1)
  21385. times[1].tv_sec = -1;
  21386. times[1].tv_usec = 0;
  21387. if (utimes(fname, times) == 0) { set_negative = true; }
  21388. } while (0);
  21389. #else
  21390. bool set_negative = false;
  21391. #endif
  21392. Server svr;
  21393. svr.set_mount_point("/static", ".");
  21394. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21395. svr.wait_until_ready();
  21396. Client cli(HOST, PORT);
  21397. auto res1 = cli.Get(std::string("/static/") + fname);
  21398. ASSERT_TRUE(res1);
  21399. ASSERT_EQ(200, res1->status);
  21400. bool has_last_modified = res1->has_header("Last-Modified");
  21401. std::string last_modified;
  21402. if (has_last_modified) {
  21403. last_modified = res1->get_header_value("Last-Modified");
  21404. }
  21405. if (set_negative) {
  21406. // If we successfully set a negative mtime, ensure server returns a
  21407. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21408. // with an old date and ensure server handles it without crash.
  21409. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21410. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21411. ASSERT_TRUE(res2);
  21412. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21413. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21414. } else {
  21415. // Could not set negative mtime on this platform; fall back to verifying
  21416. // that normal invalid/malformed dates are treated safely (non-304).
  21417. Headers h_bad_date = {
  21418. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21419. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21420. ASSERT_TRUE(res_bad);
  21421. EXPECT_EQ(200, res_bad->status);
  21422. }
  21423. svr.stop();
  21424. t.join();
  21425. std::remove(fname);
  21426. }
  21427. //==============================================================================
  21428. // Integration Tests with Server
  21429. //==============================================================================
  21430. class SSEIntegrationTest : public ::testing::Test {
  21431. protected:
  21432. void SetUp() override {
  21433. stop_server_.store(false);
  21434. events_.clear();
  21435. server_ = httplib::detail::make_unique<Server>();
  21436. setup_server();
  21437. start_server();
  21438. }
  21439. void TearDown() override {
  21440. stop_server_.store(true);
  21441. event_cv_.notify_all();
  21442. server_->stop();
  21443. if (server_thread_.joinable()) { server_thread_.join(); }
  21444. }
  21445. void setup_server() {
  21446. // Simple SSE endpoint
  21447. server_->Get("/events", [this](const Request &req, Response &res) {
  21448. auto last_id = req.get_header_value("Last-Event-ID");
  21449. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21450. res.set_chunked_content_provider(
  21451. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21452. std::unique_lock<std::mutex> lock(event_mutex_);
  21453. if (event_cv_.wait_for(
  21454. lock, std::chrono::milliseconds(200), [this] {
  21455. return !events_.empty() || stop_server_.load();
  21456. })) {
  21457. if (stop_server_.load()) { return false; }
  21458. if (!events_.empty()) {
  21459. std::string event = events_.front();
  21460. events_.erase(events_.begin());
  21461. sink.write(event.data(), event.size());
  21462. return true;
  21463. }
  21464. }
  21465. return !stop_server_.load();
  21466. });
  21467. });
  21468. // Endpoint that returns error
  21469. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21470. res.status = 500;
  21471. res.set_content("Internal Server Error", "text/plain");
  21472. });
  21473. // Endpoint for custom event types
  21474. server_->Get("/custom-events", [](const Request &, Response &res) {
  21475. res.set_chunked_content_provider(
  21476. "text/event-stream", [](size_t offset, DataSink &sink) {
  21477. if (offset == 0) {
  21478. std::string event = "event: update\ndata: updated\n\n"
  21479. "event: delete\ndata: deleted\n\n";
  21480. sink.write(event.data(), event.size());
  21481. }
  21482. return false; // End stream after sending
  21483. });
  21484. });
  21485. }
  21486. void start_server() {
  21487. port_ = server_->bind_to_any_port(HOST);
  21488. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21489. // Wait for server to start
  21490. while (!server_->is_running()) {
  21491. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21492. }
  21493. }
  21494. int get_port() const { return port_; }
  21495. void send_event(const std::string &event) {
  21496. std::lock_guard<std::mutex> lock(event_mutex_);
  21497. events_.push_back(event);
  21498. event_cv_.notify_all();
  21499. }
  21500. std::unique_ptr<Server> server_;
  21501. std::thread server_thread_;
  21502. std::mutex event_mutex_;
  21503. std::condition_variable event_cv_;
  21504. std::vector<std::string> events_;
  21505. std::atomic<bool> stop_server_{false};
  21506. std::string last_received_event_id_;
  21507. int port_ = 0;
  21508. };
  21509. //==============================================================================
  21510. // SSE Parsing Tests
  21511. //==============================================================================
  21512. class SSEParsingTest : public SSEIntegrationTest {
  21513. protected:
  21514. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21515. // A trailing sentinel event tells when the whole stream has been parsed.
  21516. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21517. auto body = stream + "event: end\ndata: end\n\n";
  21518. server_->Get("/parse", [body](const Request &, Response &res) {
  21519. res.set_content(body, "text/event-stream");
  21520. });
  21521. return collect("/parse");
  21522. }
  21523. // Runs SSEClient against path until an "end" event arrives and returns the
  21524. // messages dispatched before it
  21525. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21526. Client client(HOST, get_port());
  21527. sse::SSEClient sse(client, path);
  21528. std::mutex mutex;
  21529. std::condition_variable cv;
  21530. std::vector<sse::SSEMessage> messages;
  21531. auto done = false;
  21532. sse.on_message([&](const sse::SSEMessage &msg) {
  21533. std::lock_guard<std::mutex> lock(mutex);
  21534. // Ignore a replay from a reconnect that races with stop()
  21535. if (!done) { messages.push_back(msg); }
  21536. });
  21537. sse.on_event("end", [&](const sse::SSEMessage &) {
  21538. std::lock_guard<std::mutex> lock(mutex);
  21539. done = true;
  21540. cv.notify_all();
  21541. });
  21542. sse.set_reconnect_interval(100);
  21543. sse.start_async();
  21544. {
  21545. std::unique_lock<std::mutex> lock(mutex);
  21546. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21547. }
  21548. sse.stop();
  21549. EXPECT_TRUE(done);
  21550. return messages;
  21551. }
  21552. };
  21553. TEST_F(SSEParsingTest, SingleLineData) {
  21554. auto msgs = parse("data: hello\n\n");
  21555. ASSERT_EQ(msgs.size(), 1u);
  21556. EXPECT_EQ(msgs[0].data, "hello");
  21557. EXPECT_EQ(msgs[0].event, "message");
  21558. }
  21559. TEST_F(SSEParsingTest, MultiLineData) {
  21560. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21561. ASSERT_EQ(msgs.size(), 1u);
  21562. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21563. }
  21564. TEST_F(SSEParsingTest, CustomEventType) {
  21565. auto msgs = parse("event: update\ndata: payload\n\n");
  21566. ASSERT_EQ(msgs.size(), 1u);
  21567. EXPECT_EQ(msgs[0].event, "update");
  21568. EXPECT_EQ(msgs[0].data, "payload");
  21569. }
  21570. TEST_F(SSEParsingTest, EventIdHandling) {
  21571. auto msgs = parse("id: 12345\ndata: test\n\n");
  21572. ASSERT_EQ(msgs.size(), 1u);
  21573. EXPECT_EQ(msgs[0].id, "12345");
  21574. }
  21575. TEST_F(SSEParsingTest, EmptyEventId) {
  21576. auto msgs = parse("id:\ndata: test\n\n");
  21577. ASSERT_EQ(msgs.size(), 1u);
  21578. EXPECT_EQ(msgs[0].id, "");
  21579. }
  21580. TEST_F(SSEParsingTest, CommentsIgnored) {
  21581. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21582. ASSERT_EQ(msgs.size(), 1u);
  21583. EXPECT_EQ(msgs[0].data, "hello");
  21584. EXPECT_EQ(msgs[0].event, "message");
  21585. }
  21586. TEST_F(SSEParsingTest, ColonInValue) {
  21587. auto msgs = parse("data: hello:world:test\n\n");
  21588. ASSERT_EQ(msgs.size(), 1u);
  21589. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21590. }
  21591. TEST_F(SSEParsingTest, FieldNameOnly) {
  21592. // A line without a colon is a field name with an empty value
  21593. auto msgs = parse("data\n\n");
  21594. ASSERT_EQ(msgs.size(), 1u);
  21595. EXPECT_EQ(msgs[0].data, "");
  21596. }
  21597. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21598. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21599. ASSERT_EQ(msgs.size(), 1u);
  21600. EXPECT_EQ(msgs[0].event, "update");
  21601. EXPECT_EQ(msgs[0].data, "hello");
  21602. }
  21603. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21604. auto msgs = parse("data\r\n\r\n");
  21605. ASSERT_EQ(msgs.size(), 1u);
  21606. EXPECT_EQ(msgs[0].data, "");
  21607. }
  21608. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21609. auto msgs = parse("event: update\rdata: hello\r\r");
  21610. ASSERT_EQ(msgs.size(), 1u);
  21611. EXPECT_EQ(msgs[0].event, "update");
  21612. EXPECT_EQ(msgs[0].data, "hello");
  21613. }
  21614. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21615. // Chunk boundaries fall inside every \r\n and right before the first one
  21616. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21617. "\n\r", "\nevent: end\ndata: end\n\n"};
  21618. server_->Get("/split", [chunks](const Request &, Response &res) {
  21619. auto i = std::make_shared<size_t>(0);
  21620. res.set_chunked_content_provider(
  21621. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21622. if (*i == chunks.size()) {
  21623. sink.done();
  21624. } else {
  21625. sink.write(chunks[*i].data(), chunks[*i].size());
  21626. (*i)++;
  21627. }
  21628. return true;
  21629. });
  21630. });
  21631. auto msgs = collect("/split");
  21632. ASSERT_EQ(msgs.size(), 1u);
  21633. EXPECT_EQ(msgs[0].event, "update");
  21634. EXPECT_EQ(msgs[0].data, "hello");
  21635. }
  21636. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21637. // Only a BOM at the start of the stream is ignored
  21638. auto msgs = parse("\xEF\xBB\xBF"
  21639. "data: first\n\n"
  21640. "\xEF\xBB\xBF"
  21641. "data: second\n\n");
  21642. ASSERT_EQ(msgs.size(), 1u);
  21643. EXPECT_EQ(msgs[0].data, "first");
  21644. }
  21645. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21646. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21647. ASSERT_EQ(msgs.size(), 1u);
  21648. EXPECT_EQ(msgs[0].data, "hello");
  21649. EXPECT_EQ(msgs[0].event, "message");
  21650. }
  21651. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21652. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21653. ASSERT_EQ(msgs.size(), 2u);
  21654. EXPECT_EQ(msgs[0].data, "hello");
  21655. EXPECT_EQ(msgs[1].data, "hello");
  21656. }
  21657. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21658. // An event without data is not dispatched, and its type must not leak
  21659. // into the next event
  21660. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21661. ASSERT_EQ(msgs.size(), 1u);
  21662. EXPECT_EQ(msgs[0].event, "message");
  21663. EXPECT_EQ(msgs[0].data, "hello");
  21664. }
  21665. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21666. // Also when the empty field replaces an earlier type
  21667. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21668. ASSERT_EQ(msgs.size(), 2u);
  21669. EXPECT_EQ(msgs[0].event, "message");
  21670. EXPECT_EQ(msgs[1].event, "message");
  21671. }
  21672. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21673. // The first connection sends only an id; the second echoes back the
  21674. // Last-Event-ID it was reconnected with
  21675. std::atomic<int> connection_count{0};
  21676. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21677. if (connection_count++ == 0) {
  21678. res.set_content("id: 42\n\n", "text/event-stream");
  21679. } else {
  21680. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21681. "\n\nevent: end\ndata: end\n\n",
  21682. "text/event-stream");
  21683. }
  21684. });
  21685. auto msgs = collect("/id-only");
  21686. ASSERT_EQ(msgs.size(), 1u);
  21687. EXPECT_EQ(msgs[0].data, "42");
  21688. }
  21689. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21690. // The first connection sets an id and then clears it with an empty one; the
  21691. // second reports whether it was reconnected with a Last-Event-ID
  21692. std::atomic<int> connection_count{0};
  21693. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21694. if (connection_count++ == 0) {
  21695. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21696. "text/event-stream");
  21697. } else {
  21698. res.set_content(
  21699. std::string("data: ") +
  21700. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21701. "\n\nevent: end\ndata: end\n\n",
  21702. "text/event-stream");
  21703. }
  21704. });
  21705. auto msgs = collect("/id-clear");
  21706. ASSERT_EQ(msgs.size(), 3u);
  21707. EXPECT_EQ(msgs[0].id, "1");
  21708. EXPECT_EQ(msgs[1].id, "");
  21709. EXPECT_EQ(msgs[2].data, "not sent");
  21710. }
  21711. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21712. // The first connection sets an id and then sends ids that cannot be carried
  21713. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21714. // with
  21715. std::atomic<int> connection_count{0};
  21716. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21717. if (connection_count++ == 0) {
  21718. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21719. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21720. "text/event-stream");
  21721. } else {
  21722. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21723. "\n\nevent: end\ndata: end\n\n",
  21724. "text/event-stream");
  21725. }
  21726. });
  21727. auto msgs = collect("/id-unsendable");
  21728. ASSERT_EQ(msgs.size(), 1u);
  21729. EXPECT_EQ(msgs[0].data, "42");
  21730. }
  21731. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21732. auto msgs = parse("event: notification\nid: evt-42\n"
  21733. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21734. ASSERT_EQ(msgs.size(), 1u);
  21735. EXPECT_EQ(msgs[0].event, "notification");
  21736. EXPECT_EQ(msgs[0].id, "evt-42");
  21737. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21738. }
  21739. TEST(SSEMessageTest, Clear) {
  21740. sse::SSEMessage msg;
  21741. msg.event = "custom";
  21742. msg.data = "some data";
  21743. msg.id = "123";
  21744. msg.clear();
  21745. EXPECT_EQ(msg.event, "message");
  21746. EXPECT_EQ(msg.data, "");
  21747. EXPECT_EQ(msg.id, "");
  21748. }
  21749. //==============================================================================
  21750. // SSE Integration Tests
  21751. //==============================================================================
  21752. // Test: Successful connection and on_open callback
  21753. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21754. // Add a simple endpoint that sends one event and closes
  21755. server_->Get("/simple-event", [](const Request &, Response &res) {
  21756. res.set_chunked_content_provider(
  21757. "text/event-stream", [](size_t offset, DataSink &sink) {
  21758. if (offset == 0) {
  21759. std::string event = "data: hello\n\n";
  21760. sink.write(event.data(), event.size());
  21761. }
  21762. return false; // Close stream after sending
  21763. });
  21764. });
  21765. Client client("localhost", get_port());
  21766. sse::SSEClient sse(client, "/simple-event");
  21767. std::atomic<bool> open_called{false};
  21768. std::atomic<bool> message_received{false};
  21769. sse.on_open([&open_called]() { open_called.store(true); });
  21770. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21771. if (msg.data == "hello") { message_received.store(true); }
  21772. });
  21773. sse.set_reconnect_interval(100);
  21774. sse.set_max_reconnect_attempts(1);
  21775. // Start async
  21776. sse.start_async();
  21777. // Wait for message to be processed
  21778. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21779. sse.stop();
  21780. EXPECT_TRUE(open_called.load());
  21781. EXPECT_TRUE(message_received.load());
  21782. }
  21783. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21784. // A data line that never ends.
  21785. server_->Get("/endless-line", [](const Request &, Response &res) {
  21786. res.set_chunked_content_provider(
  21787. "text/event-stream", [](size_t offset, DataSink &sink) {
  21788. if (offset == 0) { sink.write("data: ", 6); }
  21789. std::string chunk(64 * 1024, 'A');
  21790. return sink.write(chunk.data(), chunk.size());
  21791. });
  21792. });
  21793. Client client("localhost", get_port());
  21794. sse::SSEClient sse(client, "/endless-line");
  21795. std::atomic<bool> too_long{false};
  21796. sse.on_error([&](Error err) {
  21797. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21798. });
  21799. sse.set_max_reconnect_attempts(1);
  21800. sse.start_async();
  21801. for (int i = 0; i < 500 && !too_long; i++) {
  21802. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21803. }
  21804. sse.stop();
  21805. EXPECT_TRUE(too_long);
  21806. }
  21807. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21808. // Far more in all than the client's payload limit below.
  21809. server_->Get("/many-events", [](const Request &, Response &res) {
  21810. res.set_chunked_content_provider(
  21811. "text/event-stream", [](size_t offset, DataSink &sink) {
  21812. if (offset == 0) {
  21813. std::string events;
  21814. for (int i = 0; i < 1000; i++) {
  21815. events += "data: message\n\n";
  21816. }
  21817. sink.write(events.data(), events.size());
  21818. }
  21819. return false;
  21820. });
  21821. });
  21822. Client client("localhost", get_port());
  21823. client.set_payload_max_length(1024);
  21824. sse::SSEClient sse(client, "/many-events");
  21825. std::atomic<int> messages{0};
  21826. std::atomic<bool> too_large{false};
  21827. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21828. sse.on_error([&](Error err) {
  21829. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21830. });
  21831. sse.set_max_reconnect_attempts(1);
  21832. sse.start_async();
  21833. for (int i = 0; i < 500 && messages < 1000; i++) {
  21834. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21835. }
  21836. sse.stop();
  21837. EXPECT_GE(messages.load(), 1000);
  21838. EXPECT_FALSE(too_large);
  21839. }
  21840. // Test: on_message callback
  21841. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21842. // Endpoint that sends multiple events then closes
  21843. server_->Get("/multi-event", [](const Request &, Response &res) {
  21844. res.set_chunked_content_provider(
  21845. "text/event-stream", [](size_t offset, DataSink &sink) {
  21846. if (offset == 0) {
  21847. std::string events = "data: message1\n\ndata: message2\n\n";
  21848. sink.write(events.data(), events.size());
  21849. }
  21850. return false;
  21851. });
  21852. });
  21853. Client client("localhost", get_port());
  21854. sse::SSEClient sse(client, "/multi-event");
  21855. std::vector<std::string> received_messages;
  21856. std::mutex messages_mutex;
  21857. sse.on_message([&](const sse::SSEMessage &msg) {
  21858. std::lock_guard<std::mutex> lock(messages_mutex);
  21859. received_messages.push_back(msg.data);
  21860. });
  21861. sse.set_reconnect_interval(100);
  21862. sse.set_max_reconnect_attempts(1);
  21863. sse.start_async();
  21864. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21865. sse.stop();
  21866. std::lock_guard<std::mutex> lock(messages_mutex);
  21867. EXPECT_GE(received_messages.size(), 2u);
  21868. if (received_messages.size() >= 2) {
  21869. EXPECT_EQ(received_messages[0], "message1");
  21870. EXPECT_EQ(received_messages[1], "message2");
  21871. }
  21872. }
  21873. // Test: on_event for specific types
  21874. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21875. Client client("localhost", get_port());
  21876. sse::SSEClient sse(client, "/custom-events");
  21877. std::atomic<bool> update_received{false};
  21878. std::atomic<bool> delete_received{false};
  21879. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21880. if (msg.data == "updated") { update_received.store(true); }
  21881. });
  21882. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21883. if (msg.data == "deleted") { delete_received.store(true); }
  21884. });
  21885. sse.set_max_reconnect_attempts(1);
  21886. sse.start_async();
  21887. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21888. sse.stop();
  21889. EXPECT_TRUE(update_received.load());
  21890. EXPECT_TRUE(delete_received.load());
  21891. }
  21892. // Test: on_error callback on connection failure
  21893. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21894. // Connect to a non-existent port
  21895. Client client("localhost", 59999);
  21896. sse::SSEClient sse(client, "/events");
  21897. std::atomic<bool> error_called{false};
  21898. Error received_error = Error::Success;
  21899. sse.on_error([&](Error err) {
  21900. error_called.store(true);
  21901. received_error = err;
  21902. });
  21903. sse.set_reconnect_interval(50);
  21904. sse.set_max_reconnect_attempts(1);
  21905. sse.start_async();
  21906. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21907. sse.stop();
  21908. EXPECT_TRUE(error_called.load());
  21909. EXPECT_NE(received_error, Error::Success);
  21910. }
  21911. // Test: Last-Event-ID header sent on reconnect
  21912. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21913. // Endpoint that sends event with ID
  21914. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21915. res.set_chunked_content_provider(
  21916. "text/event-stream", [](size_t offset, DataSink &sink) {
  21917. if (offset == 0) {
  21918. std::string event = "id: evt-123\ndata: test\n\n";
  21919. sink.write(event.data(), event.size());
  21920. }
  21921. return false;
  21922. });
  21923. });
  21924. Client client("localhost", get_port());
  21925. sse::SSEClient sse(client, "/event-with-id");
  21926. std::atomic<bool> id_received{false};
  21927. sse.on_message([&](const sse::SSEMessage &msg) {
  21928. if (!msg.id.empty()) { id_received.store(true); }
  21929. });
  21930. sse.set_reconnect_interval(100);
  21931. sse.set_max_reconnect_attempts(1);
  21932. sse.start_async();
  21933. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21934. sse.stop();
  21935. EXPECT_TRUE(id_received.load());
  21936. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21937. }
  21938. // Test: Manual stop
  21939. TEST_F(SSEIntegrationTest, ManualStop) {
  21940. // Endpoint that sends one event and stays open briefly. The server outlives
  21941. // this test body, so the provider uses the fixture's flag, not a local.
  21942. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21943. res.set_chunked_content_provider(
  21944. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21945. if (offset == 0) {
  21946. std::string event = "data: connected\n\n";
  21947. sink.write(event.data(), event.size());
  21948. }
  21949. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21950. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21951. }
  21952. return false;
  21953. });
  21954. });
  21955. Client client("localhost", get_port());
  21956. sse::SSEClient sse(client, "/stay-open");
  21957. std::atomic<bool> connected{false};
  21958. sse.on_open([&connected]() { connected.store(true); });
  21959. sse.set_reconnect_interval(100);
  21960. sse.set_max_reconnect_attempts(1);
  21961. sse.start_async();
  21962. // Wait for connection to establish
  21963. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21964. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21965. }
  21966. EXPECT_TRUE(connected.load());
  21967. EXPECT_TRUE(sse.is_connected());
  21968. // Signal handler to stop
  21969. stop_server_.store(true);
  21970. // Stop SSE client
  21971. sse.stop();
  21972. EXPECT_FALSE(sse.is_connected());
  21973. }
  21974. // Sends one event, then nothing until stop is set
  21975. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21976. return [&stop](const Request &, Response &res) {
  21977. res.set_chunked_content_provider(
  21978. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21979. if (offset == 0) {
  21980. std::string event = "data: hello\n\n";
  21981. sink.write(event.data(), event.size());
  21982. }
  21983. while (!stop.load()) {
  21984. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21985. }
  21986. return false;
  21987. });
  21988. };
  21989. }
  21990. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  21991. static void check_stop_interrupts_blocked_read(Client &client) {
  21992. client.set_read_timeout(30, 0);
  21993. for (auto by_destructor : {false, true}) {
  21994. std::atomic<bool> received{false};
  21995. std::chrono::steady_clock::time_point start;
  21996. {
  21997. sse::SSEClient sse(client, "/idle-stream");
  21998. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  21999. sse.start_async();
  22000. for (int i = 0; i < 500 && !received.load(); ++i) {
  22001. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22002. }
  22003. ASSERT_TRUE(received.load());
  22004. // Let the client block in the next read
  22005. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22006. start = std::chrono::steady_clock::now();
  22007. if (!by_destructor) { sse.stop(); }
  22008. }
  22009. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22010. std::chrono::seconds(2));
  22011. }
  22012. }
  22013. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22014. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22015. Client client("localhost", get_port());
  22016. check_stop_interrupts_blocked_read(client);
  22017. }
  22018. #ifdef CPPHTTPLIB_SSL_ENABLED
  22019. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22021. std::atomic<bool> done{false};
  22022. svr.Get("/idle-stream", idle_event_stream(done));
  22023. auto port = svr.bind_to_any_port(HOST);
  22024. std::thread t([&] { svr.listen_after_bind(); });
  22025. auto se = detail::scope_exit([&] {
  22026. done.store(true);
  22027. svr.stop();
  22028. t.join();
  22029. });
  22030. svr.wait_until_ready();
  22031. Client client("https://localhost:" + std::to_string(port));
  22032. client.enable_server_certificate_verification(false);
  22033. check_stop_interrupts_blocked_read(client);
  22034. }
  22035. #endif
  22036. // Test: SSEClient with custom headers
  22037. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22038. // Setup a server endpoint that checks for custom header
  22039. std::atomic<bool> header_received{false};
  22040. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22041. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22042. header_received.store(true);
  22043. }
  22044. res.set_chunked_content_provider("text/event-stream",
  22045. [](size_t, DataSink &) { return false; });
  22046. });
  22047. Client client("localhost", get_port());
  22048. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22049. sse::SSEClient sse(client, "/header-check", headers);
  22050. sse.set_max_reconnect_attempts(1);
  22051. sse.start_async();
  22052. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22053. sse.stop();
  22054. EXPECT_TRUE(header_received.load());
  22055. }
  22056. // Test: Reconnect interval configuration
  22057. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22058. Client client("localhost", get_port());
  22059. sse::SSEClient sse(client, "/events");
  22060. auto &result = sse.set_reconnect_interval(500);
  22061. // Builder pattern should return reference to self
  22062. EXPECT_EQ(&result, &sse);
  22063. }
  22064. // Test: Max reconnect attempts
  22065. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22066. // Connect to non-existent port to force reconnects
  22067. Client client("localhost", 59998);
  22068. sse::SSEClient sse(client, "/events");
  22069. std::atomic<int> error_count{0};
  22070. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22071. sse.set_reconnect_interval(50);
  22072. sse.set_max_reconnect_attempts(2);
  22073. auto start = std::chrono::steady_clock::now();
  22074. sse.start(); // Blocking call
  22075. auto end = std::chrono::steady_clock::now();
  22076. // Should have stopped after 2 failed attempts
  22077. EXPECT_GE(error_count.load(), 2);
  22078. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22079. auto duration =
  22080. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22081. #ifdef _WIN32
  22082. // Windows is much slower for socket connection failures
  22083. EXPECT_LT(duration.count(), 7000);
  22084. #else
  22085. EXPECT_LT(duration.count(), 1000);
  22086. #endif
  22087. }
  22088. // Test: Multi-line data in integration
  22089. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22090. // Endpoint with multi-line data
  22091. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22092. res.set_chunked_content_provider(
  22093. "text/event-stream", [](size_t offset, DataSink &sink) {
  22094. if (offset == 0) {
  22095. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22096. sink.write(event.data(), event.size());
  22097. }
  22098. return false;
  22099. });
  22100. });
  22101. Client client("localhost", get_port());
  22102. sse::SSEClient sse(client, "/multiline-data");
  22103. std::string received_data;
  22104. std::mutex data_mutex;
  22105. sse.on_message([&](const sse::SSEMessage &msg) {
  22106. std::lock_guard<std::mutex> lock(data_mutex);
  22107. received_data = msg.data;
  22108. });
  22109. sse.set_reconnect_interval(100);
  22110. sse.set_max_reconnect_attempts(1);
  22111. sse.start_async();
  22112. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22113. sse.stop();
  22114. std::lock_guard<std::mutex> lock(data_mutex);
  22115. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22116. }
  22117. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22118. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22119. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22120. DataSink &sink) {
  22121. if (offset == 0) {
  22122. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22123. sink.write(events.data(), events.size());
  22124. }
  22125. return false;
  22126. });
  22127. });
  22128. Client client("localhost", get_port());
  22129. sse::SSEClient sse(client, "/empty-data-lines");
  22130. std::mutex mutex;
  22131. std::condition_variable cv;
  22132. std::vector<std::string> received;
  22133. sse.on_message([&](const sse::SSEMessage &msg) {
  22134. std::lock_guard<std::mutex> lock(mutex);
  22135. received.push_back(msg.data);
  22136. cv.notify_all();
  22137. });
  22138. sse.set_max_reconnect_attempts(1);
  22139. sse.start_async();
  22140. {
  22141. std::unique_lock<std::mutex> lock(mutex);
  22142. cv.wait_for(lock, std::chrono::seconds(2),
  22143. [&] { return received.size() >= 3; });
  22144. }
  22145. sse.stop();
  22146. ASSERT_GE(received.size(), 3u);
  22147. EXPECT_EQ(received[0], "");
  22148. EXPECT_EQ(received[1], "\nhello");
  22149. EXPECT_EQ(received[2], "");
  22150. }
  22151. // Test: Auto-reconnect after server disconnection
  22152. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22153. std::atomic<int> connection_count{0};
  22154. std::atomic<int> message_count{0};
  22155. // Endpoint that sends one event and closes, forcing reconnect
  22156. server_->Get("/reconnect-test",
  22157. [&connection_count](const Request &, Response &res) {
  22158. connection_count.fetch_add(1);
  22159. res.set_chunked_content_provider(
  22160. "text/event-stream", [](size_t offset, DataSink &sink) {
  22161. if (offset == 0) {
  22162. std::string event = "data: hello\n\n";
  22163. sink.write(event.data(), event.size());
  22164. }
  22165. return false; // Close connection after sending
  22166. });
  22167. });
  22168. Client client("localhost", get_port());
  22169. sse::SSEClient sse(client, "/reconnect-test");
  22170. sse.on_message([&message_count](const sse::SSEMessage &) {
  22171. message_count.fetch_add(1);
  22172. });
  22173. sse.set_reconnect_interval(100);
  22174. sse.set_max_reconnect_attempts(3);
  22175. sse.start_async();
  22176. // Wait long enough for multiple reconnects
  22177. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22178. sse.stop();
  22179. // Should have connected multiple times (initial + reconnects)
  22180. EXPECT_GE(connection_count.load(), 2);
  22181. // Should have received messages from multiple connections
  22182. EXPECT_GE(message_count.load(), 2);
  22183. }
  22184. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22185. std::atomic<int> connection_count{0};
  22186. // Neither Content-Length nor chunked: the close ends the stream
  22187. server_->Get("/close-delimited",
  22188. [&connection_count](const Request &, Response &res) {
  22189. connection_count.fetch_add(1);
  22190. res.set_content_provider(
  22191. "text/event-stream", [](size_t offset, DataSink &sink) {
  22192. if (offset == 0) {
  22193. std::string event = "data: hello\n\n";
  22194. sink.write(event.data(), event.size());
  22195. } else {
  22196. sink.done();
  22197. }
  22198. return true;
  22199. });
  22200. });
  22201. Client client("localhost", get_port());
  22202. sse::SSEClient sse(client, "/close-delimited");
  22203. std::atomic<int> error_count{0};
  22204. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22205. sse.set_reconnect_interval(100);
  22206. sse.start_async();
  22207. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22208. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22209. }
  22210. sse.stop();
  22211. // Reconnects as after any end of the stream, but reports no error
  22212. EXPECT_GE(connection_count.load(), 2);
  22213. EXPECT_EQ(0, error_count.load());
  22214. }
  22215. // Test: A retry field that is not all ASCII digits is ignored
  22216. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22217. std::atomic<int> connection_count{0};
  22218. server_->Get("/bad-retry",
  22219. [&connection_count](const Request &, Response &res) {
  22220. connection_count.fetch_add(1);
  22221. res.set_chunked_content_provider(
  22222. "text/event-stream", [](size_t offset, DataSink &sink) {
  22223. if (offset == 0) {
  22224. std::string event = "retry: -1\ndata: hello\n\n";
  22225. sink.write(event.data(), event.size());
  22226. }
  22227. return false;
  22228. });
  22229. });
  22230. Client client("localhost", get_port());
  22231. sse::SSEClient sse(client, "/bad-retry");
  22232. sse.set_reconnect_interval(10000);
  22233. sse.start_async();
  22234. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22235. sse.stop();
  22236. EXPECT_EQ(connection_count.load(), 1);
  22237. }
  22238. // Test: A retry field of all ASCII digits sets the reconnection time
  22239. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22240. std::mutex mutex;
  22241. std::condition_variable cv;
  22242. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22243. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22244. {
  22245. std::lock_guard<std::mutex> lock(mutex);
  22246. connected_at.push_back(std::chrono::steady_clock::now());
  22247. cv.notify_all();
  22248. }
  22249. res.set_chunked_content_provider(
  22250. "text/event-stream", [](size_t offset, DataSink &sink) {
  22251. if (offset == 0) {
  22252. std::string event = "retry: 0\ndata: hello\n\n";
  22253. sink.write(event.data(), event.size());
  22254. }
  22255. return false;
  22256. });
  22257. });
  22258. Client client("localhost", get_port());
  22259. sse::SSEClient sse(client, "/zero-retry");
  22260. sse.set_reconnect_interval(10000);
  22261. sse.start_async();
  22262. {
  22263. std::unique_lock<std::mutex> lock(mutex);
  22264. cv.wait_for(lock, std::chrono::seconds(5),
  22265. [&] { return connected_at.size() >= 2; });
  22266. }
  22267. sse.stop();
  22268. // The server-supplied interval is applied, but never below 100ms, so
  22269. // "retry: 0" does not cause a busy reconnect loop
  22270. std::lock_guard<std::mutex> lock(mutex);
  22271. ASSERT_GE(connected_at.size(), 2u);
  22272. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22273. connected_at[1] - connected_at[0])
  22274. .count();
  22275. EXPECT_GE(interval_ms, 100);
  22276. }
  22277. // Test: Last-Event-ID sent on reconnect
  22278. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22279. std::atomic<int> connection_count{0};
  22280. std::vector<std::string> received_last_event_ids;
  22281. std::mutex id_mutex;
  22282. // Endpoint that checks Last-Event-ID header and sends event with ID
  22283. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22284. int conn = connection_count.fetch_add(1);
  22285. // Capture the Last-Event-ID header from each connection
  22286. {
  22287. std::lock_guard<std::mutex> lock(id_mutex);
  22288. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22289. }
  22290. res.set_chunked_content_provider(
  22291. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22292. if (offset == 0) {
  22293. std::string event =
  22294. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22295. sink.write(event.data(), event.size());
  22296. }
  22297. return false;
  22298. });
  22299. });
  22300. Client client("localhost", get_port());
  22301. sse::SSEClient sse(client, "/reconnect-with-id");
  22302. sse.set_reconnect_interval(100);
  22303. sse.set_max_reconnect_attempts(3);
  22304. sse.start_async();
  22305. // Wait for at least 2 connections
  22306. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22307. sse.stop();
  22308. // Verify behavior
  22309. std::lock_guard<std::mutex> lock(id_mutex);
  22310. EXPECT_GE(received_last_event_ids.size(), 2u);
  22311. // First connection should have no Last-Event-ID
  22312. if (!received_last_event_ids.empty()) {
  22313. EXPECT_EQ(received_last_event_ids[0], "");
  22314. }
  22315. // Second connection should have Last-Event-ID from first connection
  22316. if (received_last_event_ids.size() >= 2) {
  22317. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22318. }
  22319. }
  22320. // Test: set_headers updates headers used on reconnect
  22321. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22322. std::vector<std::string> received_tokens;
  22323. std::mutex token_mutex;
  22324. // Endpoint that captures Authorization header
  22325. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22326. {
  22327. std::lock_guard<std::mutex> lock(token_mutex);
  22328. received_tokens.push_back(req.get_header_value("Authorization"));
  22329. }
  22330. res.set_chunked_content_provider(
  22331. "text/event-stream", [](size_t offset, DataSink &sink) {
  22332. if (offset == 0) {
  22333. std::string event = "data: hello\n\n";
  22334. sink.write(event.data(), event.size());
  22335. }
  22336. return false; // Close connection to trigger reconnect
  22337. });
  22338. });
  22339. Client client("localhost", get_port());
  22340. Headers headers = {{"Authorization", "Bearer old-token"}};
  22341. sse::SSEClient sse(client, "/auth-check", headers);
  22342. // Update headers on each successful connection
  22343. sse.on_open(
  22344. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22345. sse.set_reconnect_interval(100);
  22346. sse.set_max_reconnect_attempts(3);
  22347. sse.start_async();
  22348. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22349. sse.stop();
  22350. std::lock_guard<std::mutex> lock(token_mutex);
  22351. ASSERT_GE(received_tokens.size(), 2u);
  22352. // First connection uses original header
  22353. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22354. // Second connection uses updated header from set_headers
  22355. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22356. }
  22357. // Test: 401 allows reconnection (so on_error can refresh headers)
  22358. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22359. std::atomic<int> connection_count{0};
  22360. // Endpoint: returns 401 on first attempt, 200 on second
  22361. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22362. int conn = connection_count.fetch_add(1);
  22363. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22364. res.status = StatusCode::Unauthorized_401;
  22365. res.set_content("Unauthorized", "text/plain");
  22366. return;
  22367. }
  22368. res.set_chunked_content_provider(
  22369. "text/event-stream", [](size_t offset, DataSink &sink) {
  22370. if (offset == 0) {
  22371. std::string event = "data: authenticated\n\n";
  22372. sink.write(event.data(), event.size());
  22373. }
  22374. return false;
  22375. });
  22376. });
  22377. Client client("localhost", get_port());
  22378. Headers headers = {{"Authorization", "Bearer expired"}};
  22379. sse::SSEClient sse(client, "/auth-retry", headers);
  22380. std::atomic<bool> message_received{false};
  22381. // Refresh token on error
  22382. sse.on_error(
  22383. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22384. sse.on_message([&](const sse::SSEMessage &msg) {
  22385. if (msg.data == "authenticated") { message_received.store(true); }
  22386. });
  22387. sse.set_reconnect_interval(100);
  22388. sse.set_max_reconnect_attempts(3);
  22389. sse.start_async();
  22390. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22391. sse.stop();
  22392. // Should have reconnected after 401 and succeeded with new token
  22393. EXPECT_GE(connection_count.load(), 2);
  22394. EXPECT_TRUE(message_received.load());
  22395. }
  22396. TEST(Issue2318Test, EmptyHostString) {
  22397. {
  22398. httplib::Client cli_empty("", PORT);
  22399. auto res = cli_empty.Get("/");
  22400. ASSERT_FALSE(res);
  22401. EXPECT_EQ(httplib::Error::Connection, res.error());
  22402. }
  22403. {
  22404. httplib::Client cli(" ", PORT);
  22405. auto res = cli.Get("/");
  22406. ASSERT_FALSE(res);
  22407. EXPECT_EQ(httplib::Error::Connection, res.error());
  22408. }
  22409. }
  22410. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22411. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22412. Server svr;
  22413. // Set a small payload limit (1KB)
  22414. svr.set_payload_max_length(1024);
  22415. svr.Post("/test", [&](const Request &req, Response &res) {
  22416. res.set_content("Body size: " + std::to_string(req.body.size()),
  22417. "text/plain");
  22418. });
  22419. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22420. auto se = detail::scope_exit([&] {
  22421. svr.stop();
  22422. listen_thread.join();
  22423. });
  22424. svr.wait_until_ready();
  22425. // Create data that compresses well but exceeds limit when decompressed
  22426. // 8KB of repeated null bytes compresses to a very small size
  22427. std::string original_data(8 * 1024, '\0');
  22428. // Compress the data using gzip
  22429. std::string compressed_data;
  22430. detail::gzip_compressor compressor;
  22431. compressor.compress(original_data.data(), original_data.size(), true,
  22432. [&](const char *data, size_t size) {
  22433. compressed_data.append(data, size);
  22434. return true;
  22435. });
  22436. // Verify compression worked (compressed should be much smaller)
  22437. ASSERT_LT(compressed_data.size(), original_data.size());
  22438. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22439. // Send compressed data with Content-Encoding: gzip
  22440. Client cli(HOST, PORT);
  22441. Headers headers = {{"Content-Encoding", "gzip"}};
  22442. auto res =
  22443. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22444. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22446. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22447. }
  22448. #endif
  22449. // ============================================================================
  22450. // OpenSSL-Specific Tests
  22451. // ============================================================================
  22452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22453. X509 *readCertificate(const std::string &strFileName) {
  22454. std::ifstream inStream(strFileName);
  22455. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22456. std::istreambuf_iterator<char>());
  22457. if (strCertPEM.empty()) return (nullptr);
  22458. BIO *pbCert = BIO_new(BIO_s_mem());
  22459. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22460. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22461. BIO_free(pbCert);
  22462. return (pCert);
  22463. }
  22464. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22465. std::ifstream inStream(strFileName);
  22466. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22467. std::istreambuf_iterator<char>());
  22468. if (strPrivateKeyPEM.empty()) return (nullptr);
  22469. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22470. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22471. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22472. BIO_free(pbPrivKey);
  22473. return (pPrivateKey);
  22474. }
  22475. TEST(BindServerTest, UpdateCerts) {
  22476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22477. int port = svr.bind_to_any_port("0.0.0.0");
  22478. ASSERT_TRUE(svr.is_valid());
  22479. ASSERT_TRUE(port > 0);
  22480. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22481. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22482. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22483. ASSERT_TRUE(cert != nullptr);
  22484. ASSERT_TRUE(ca_cert != nullptr);
  22485. ASSERT_TRUE(key != nullptr);
  22486. X509_STORE *cert_store = X509_STORE_new();
  22487. X509_STORE_add_cert(cert_store, ca_cert);
  22488. // svr.update_certs(cert, key, cert_store); // deprecated
  22489. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22490. CLIENT_CA_CERT_FILE);
  22491. ASSERT_TRUE(svr.is_valid());
  22492. svr.stop();
  22493. X509_STORE_free(cert_store);
  22494. X509_free(cert);
  22495. X509_free(ca_cert);
  22496. EVP_PKEY_free(key);
  22497. }
  22498. // Test that update_certs() updates client CA list correctly
  22499. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22500. // Start with file-based constructor
  22501. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22502. ASSERT_TRUE(svr.is_valid());
  22503. // Initially no client CA list should be set
  22504. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22505. ASSERT_TRUE(ssl_ctx != nullptr);
  22506. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22507. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22508. // Now update with client CA (PEM string)
  22509. std::string cert_pem, key_pem, ca_pem;
  22510. read_file(SERVER_CERT_FILE, cert_pem);
  22511. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22512. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22513. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22514. ASSERT_TRUE(svr.is_valid());
  22515. // Now client CA list should be set
  22516. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22517. ASSERT_TRUE(ca_list_after != nullptr);
  22518. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22519. }
  22520. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22521. // Test that the file-path SSLServer constructor properly sets the client CA
  22522. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22524. ASSERT_TRUE(svr.is_valid());
  22525. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22526. ASSERT_TRUE(ssl_ctx != nullptr);
  22527. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22528. ASSERT_TRUE(ca_list != nullptr);
  22529. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22530. }
  22531. #endif
  22532. // ============================================================================
  22533. // MbedTLS-Specific Tests
  22534. // ============================================================================
  22535. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22536. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22537. using namespace httplib::tls;
  22538. // Track if callback was invoked
  22539. bool callback_invoked = false;
  22540. // The callback receives void* ctx which is actually MbedTlsContext*
  22541. // We can access the mbedtls_ssl_config via the context
  22542. auto setup_callback = [&callback_invoked](void *ctx) {
  22543. callback_invoked = true;
  22544. // Cast to MbedTlsContext* to access the ssl config
  22545. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22546. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22547. // Use static variables to hold certificate data (simplified for test)
  22548. static mbedtls_x509_crt own_cert;
  22549. static mbedtls_pk_context own_key;
  22550. static mbedtls_x509_crt ca_chain;
  22551. static bool initialized = false;
  22552. if (!initialized) {
  22553. mbedtls_x509_crt_init(&own_cert);
  22554. mbedtls_pk_init(&own_key);
  22555. mbedtls_x509_crt_init(&ca_chain);
  22556. // Load server certificate
  22557. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22558. return false;
  22559. }
  22560. // Load server private key.
  22561. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22562. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22563. #if MBEDTLS_VERSION_MAJOR == 3
  22564. ,
  22565. mbedtls_ctr_drbg_random, nullptr
  22566. #endif
  22567. ) != 0) {
  22568. return false;
  22569. }
  22570. // Load CA chain for client verification
  22571. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22572. return false;
  22573. }
  22574. initialized = true;
  22575. }
  22576. // Configure the SSL config
  22577. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22578. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22579. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22580. // Set minimum TLS version using mbedTLS native API
  22581. #if MBEDTLS_VERSION_MAJOR >= 3
  22582. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22583. #else
  22584. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22585. MBEDTLS_SSL_MINOR_VERSION_3);
  22586. #endif
  22587. return true;
  22588. };
  22589. SSLServer svr(setup_callback);
  22590. ASSERT_TRUE(svr.is_valid());
  22591. ASSERT_TRUE(callback_invoked);
  22592. svr.Get("/test", [&](const Request &req, Response &res) {
  22593. res.set_content("test", "text/plain");
  22594. auto cert = req.peer_cert();
  22595. ASSERT_TRUE(static_cast<bool>(cert));
  22596. auto common_name = cert.subject_cn();
  22597. EXPECT_EQ("Common Name", common_name);
  22598. });
  22599. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22600. auto se = detail::scope_exit([&] {
  22601. svr.stop();
  22602. t.join();
  22603. ASSERT_FALSE(svr.is_running());
  22604. });
  22605. svr.wait_until_ready();
  22606. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22607. cli.enable_server_certificate_verification(false);
  22608. cli.set_connection_timeout(30);
  22609. auto res = cli.Get("/test");
  22610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22611. ASSERT_EQ(StatusCode::OK_200, res->status);
  22612. }
  22613. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22614. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22615. // keep-alive SSL session, which reads through that config in
  22616. // mbedtls_ssl_close_notify.
  22617. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22618. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22619. ASSERT_TRUE(svr.is_valid());
  22620. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22621. res.set_content("test", "text/plain");
  22622. });
  22623. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22624. auto se = detail::scope_exit([&] {
  22625. svr.stop();
  22626. t.join();
  22627. ASSERT_FALSE(svr.is_running());
  22628. });
  22629. svr.wait_until_ready();
  22630. {
  22631. SSLClient cli(HOST, PORT);
  22632. cli.enable_server_certificate_verification(false);
  22633. cli.set_keep_alive(true);
  22634. auto res = cli.Get("/test");
  22635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22636. ASSERT_EQ(StatusCode::OK_200, res->status);
  22637. // cli is destructed here with the keep-alive SSL session still open.
  22638. }
  22639. }
  22640. #endif
  22641. // WebSocket Tests
  22642. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22643. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22644. // defining the meaning of these bits has been negotiated.
  22645. auto make_frame = [](uint8_t first_byte) {
  22646. std::string frame;
  22647. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22648. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22649. frame += "Hello";
  22650. return frame;
  22651. };
  22652. // RSV1 set (0x40)
  22653. {
  22654. detail::BufferStream strm;
  22655. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22656. ws::Opcode opcode;
  22657. std::string payload;
  22658. bool fin;
  22659. EXPECT_EQ(
  22660. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22661. ws::impl::FrameRead::Fail);
  22662. }
  22663. // RSV2 set (0x20)
  22664. {
  22665. detail::BufferStream strm;
  22666. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22667. ws::Opcode opcode;
  22668. std::string payload;
  22669. bool fin;
  22670. EXPECT_EQ(
  22671. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22672. ws::impl::FrameRead::Fail);
  22673. }
  22674. // RSV3 set (0x10)
  22675. {
  22676. detail::BufferStream strm;
  22677. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22678. ws::Opcode opcode;
  22679. std::string payload;
  22680. bool fin;
  22681. EXPECT_EQ(
  22682. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22683. ws::impl::FrameRead::Fail);
  22684. }
  22685. // No RSV bits set - should succeed
  22686. {
  22687. detail::BufferStream strm;
  22688. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22689. ws::Opcode opcode;
  22690. std::string payload;
  22691. bool fin;
  22692. EXPECT_EQ(
  22693. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22694. ws::impl::FrameRead::Ok);
  22695. EXPECT_EQ(ws::Opcode::Text, opcode);
  22696. EXPECT_EQ("Hello", payload);
  22697. EXPECT_TRUE(fin);
  22698. }
  22699. }
  22700. TEST(WebSocketTest, ControlFrameValidation) {
  22701. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22702. // payload length <= 125.
  22703. // Ping with FIN=0 - must be rejected
  22704. {
  22705. detail::BufferStream strm;
  22706. std::string frame;
  22707. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22708. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22709. strm.write(frame.data(), frame.size());
  22710. ws::Opcode opcode;
  22711. std::string payload;
  22712. bool fin;
  22713. EXPECT_EQ(
  22714. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22715. ws::impl::FrameRead::Fail);
  22716. }
  22717. // Close with FIN=0 - must be rejected
  22718. {
  22719. detail::BufferStream strm;
  22720. std::string frame;
  22721. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22722. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22723. strm.write(frame.data(), frame.size());
  22724. ws::Opcode opcode;
  22725. std::string payload;
  22726. bool fin;
  22727. EXPECT_EQ(
  22728. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22729. ws::impl::FrameRead::Fail);
  22730. }
  22731. // Ping with payload_len=126 (extended length) - must be rejected
  22732. {
  22733. detail::BufferStream strm;
  22734. std::string frame;
  22735. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22736. frame += static_cast<char>(126); // payload_len=126 (>125)
  22737. frame += static_cast<char>(0x00); // extended length high byte
  22738. frame += static_cast<char>(126); // extended length low byte
  22739. frame += std::string(126, 'x');
  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 FIN=1 and payload_len=125 - should succeed
  22749. {
  22750. detail::BufferStream strm;
  22751. std::string frame;
  22752. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22753. frame += static_cast<char>(125); // payload_len=125
  22754. frame += std::string(125, 'x');
  22755. strm.write(frame.data(), frame.size());
  22756. ws::Opcode opcode;
  22757. std::string payload;
  22758. bool fin;
  22759. EXPECT_EQ(
  22760. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22761. ws::impl::FrameRead::Ok);
  22762. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22763. EXPECT_EQ(125u, payload.size());
  22764. EXPECT_TRUE(fin);
  22765. }
  22766. }
  22767. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22768. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22769. // length MUST be 0.
  22770. // MSB set - must be rejected
  22771. {
  22772. detail::BufferStream strm;
  22773. std::string frame;
  22774. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22775. frame += static_cast<char>(127); // 64-bit extended length
  22776. frame += static_cast<char>(0x80); // MSB set (invalid)
  22777. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22778. strm.write(frame.data(), frame.size());
  22779. ws::Opcode opcode;
  22780. std::string payload;
  22781. bool fin;
  22782. EXPECT_EQ(
  22783. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22784. ws::impl::FrameRead::Fail);
  22785. }
  22786. // MSB clear - should pass length parsing (will be rejected by max_len,
  22787. // but that's a different check; use a small length to verify)
  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 += std::string(7, '\0'); // high bytes = 0
  22794. frame += static_cast<char>(0x03); // length = 3
  22795. frame += "abc";
  22796. strm.write(frame.data(), frame.size());
  22797. ws::Opcode opcode;
  22798. std::string payload;
  22799. bool fin;
  22800. EXPECT_EQ(
  22801. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22802. ws::impl::FrameRead::Ok);
  22803. EXPECT_EQ(ws::Opcode::Text, opcode);
  22804. EXPECT_EQ("abc", payload);
  22805. }
  22806. }
  22807. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22808. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22809. // Valid UTF-8
  22810. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22811. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22812. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22813. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22814. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22815. // Invalid UTF-8
  22816. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22817. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22818. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22819. EXPECT_FALSE(
  22820. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22821. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22822. }
  22823. TEST(WebSocketTest, ConnectAndDisconnect) {
  22824. Server svr;
  22825. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22826. std::string msg;
  22827. while (ws.read(msg)) {}
  22828. });
  22829. auto port = svr.bind_to_any_port(HOST);
  22830. std::thread t([&]() { svr.listen_after_bind(); });
  22831. svr.wait_until_ready();
  22832. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22833. auto res = client.connect();
  22834. ASSERT_TRUE(res);
  22835. EXPECT_EQ(Error::Success, res.error());
  22836. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22837. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22838. EXPECT_TRUE(client.is_open());
  22839. client.close();
  22840. EXPECT_FALSE(client.is_open());
  22841. svr.stop();
  22842. t.join();
  22843. }
  22844. TEST(WebSocketTest, ValidURL) {
  22845. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22846. EXPECT_TRUE(ws1.is_valid());
  22847. ws::WebSocketClient ws2("ws://example.com/path");
  22848. EXPECT_TRUE(ws2.is_valid());
  22849. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22850. EXPECT_TRUE(ws3.is_valid());
  22851. #ifdef CPPHTTPLIB_SSL_ENABLED
  22852. ws::WebSocketClient wss1("wss://example.com/path");
  22853. EXPECT_TRUE(wss1.is_valid());
  22854. ws::WebSocketClient wss2("wss://example.com:443/path");
  22855. EXPECT_TRUE(wss2.is_valid());
  22856. #endif
  22857. }
  22858. TEST(WebSocketTest, InvalidURL) {
  22859. // No scheme
  22860. ws::WebSocketClient ws1("localhost:8080/path");
  22861. EXPECT_FALSE(ws1.is_valid());
  22862. // No path
  22863. ws::WebSocketClient ws2("ws://localhost:8080");
  22864. EXPECT_FALSE(ws2.is_valid());
  22865. // Empty string
  22866. ws::WebSocketClient ws3("");
  22867. EXPECT_FALSE(ws3.is_valid());
  22868. // Missing host
  22869. ws::WebSocketClient ws4("ws://:8080/path");
  22870. EXPECT_FALSE(ws4.is_valid());
  22871. // Port number overflow — should not crash
  22872. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22873. EXPECT_FALSE(ws5.is_valid());
  22874. // Port out of range
  22875. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22876. EXPECT_FALSE(ws6.is_valid());
  22877. }
  22878. TEST(WebSocketTest, UnsupportedScheme) {
  22879. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22880. ws::WebSocketClient ws1("http://localhost:8080/path");
  22881. EXPECT_FALSE(ws1.is_valid());
  22882. ws::WebSocketClient ws2("https://localhost:8080/path");
  22883. EXPECT_FALSE(ws2.is_valid());
  22884. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22885. EXPECT_FALSE(ws3.is_valid());
  22886. #else
  22887. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22888. std::invalid_argument);
  22889. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22890. std::invalid_argument);
  22891. #endif
  22892. }
  22893. TEST(WebSocketTest, ConnectWhenInvalid) {
  22894. ws::WebSocketClient ws("not a valid url");
  22895. EXPECT_FALSE(ws.is_valid());
  22896. auto res = ws.connect();
  22897. EXPECT_FALSE(res);
  22898. EXPECT_EQ(Error::Connection, res.error());
  22899. EXPECT_EQ(-1, res.status());
  22900. }
  22901. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22902. // Grab a port that is free, then close it again so nothing listens there
  22903. Server svr;
  22904. auto port = svr.bind_to_any_port(HOST);
  22905. svr.stop();
  22906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22907. auto res = client.connect();
  22908. ASSERT_FALSE(res);
  22909. EXPECT_EQ(Error::Connection, res.error());
  22910. EXPECT_EQ(-1, res.status());
  22911. }
  22912. TEST(WebSocketTest, DefaultPort) {
  22913. ws::WebSocketClient ws1("ws://example.com/path");
  22914. EXPECT_TRUE(ws1.is_valid());
  22915. // ws:// defaults to port 80 (verified by successful parse)
  22916. #ifdef CPPHTTPLIB_SSL_ENABLED
  22917. ws::WebSocketClient ws2("wss://example.com/path");
  22918. EXPECT_TRUE(ws2.is_valid());
  22919. // wss:// defaults to port 443 (verified by successful parse)
  22920. #endif
  22921. }
  22922. TEST(WebSocketTest, IPv6LiteralAddress) {
  22923. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22924. EXPECT_TRUE(ws1.is_valid());
  22925. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22926. EXPECT_TRUE(ws2.is_valid());
  22927. }
  22928. TEST(WebSocketTest, ComplexPath) {
  22929. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22930. EXPECT_TRUE(ws1.is_valid());
  22931. ws::WebSocketClient ws2("ws://localhost:8080/");
  22932. EXPECT_TRUE(ws2.is_valid());
  22933. }
  22934. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22935. Server svr;
  22936. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22937. std::string msg;
  22938. while (ws.read(msg)) {}
  22939. });
  22940. auto port = svr.bind_to_any_port(HOST);
  22941. std::thread t([&]() { svr.listen_after_bind(); });
  22942. svr.wait_until_ready();
  22943. auto another_host = "example.com";
  22944. auto wrong_ip = "192.0.2.1";
  22945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22946. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22947. ASSERT_TRUE(client.connect());
  22948. EXPECT_TRUE(client.is_open());
  22949. client.close();
  22950. svr.stop();
  22951. t.join();
  22952. }
  22953. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22954. Server svr;
  22955. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22956. std::string msg;
  22957. while (ws.read(msg)) {}
  22958. });
  22959. auto port = svr.bind_to_any_port(HOST);
  22960. std::thread t([&]() { svr.listen_after_bind(); });
  22961. svr.wait_until_ready();
  22962. auto wrong_ip = "192.0.2.1";
  22963. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22964. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22965. client.set_connection_timeout(1);
  22966. client.set_read_timeout(1);
  22967. client.set_write_timeout(1);
  22968. EXPECT_FALSE(client.connect());
  22969. EXPECT_FALSE(client.is_open());
  22970. svr.stop();
  22971. t.join();
  22972. }
  22973. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22974. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22975. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22976. // (RFC 6761) is only a map key and the Host header value.
  22977. auto host = "target.invalid";
  22978. Server svr;
  22979. std::string received_host;
  22980. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22981. received_host = req.get_header_value("Host");
  22982. std::string msg;
  22983. while (ws.read(msg)) {}
  22984. });
  22985. auto port = svr.bind_to_any_port(HOST);
  22986. std::thread t([&]() { svr.listen_after_bind(); });
  22987. // ASSERT_* below returns from the test body, which would leave t joinable
  22988. // and make ~thread call std::terminate.
  22989. auto se = detail::scope_exit([&] {
  22990. svr.stop();
  22991. if (t.joinable()) { t.join(); }
  22992. });
  22993. svr.wait_until_ready();
  22994. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22995. std::to_string(port) + "/ws");
  22996. client.set_hostname_addr_map({{host, HOST}});
  22997. ASSERT_TRUE(client.connect());
  22998. EXPECT_TRUE(client.is_open());
  22999. client.close();
  23000. svr.stop();
  23001. t.join();
  23002. // The mapping only redirects the connection; the identity stays host_.
  23003. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23004. }
  23005. class WebSocketIntegrationTest : public ::testing::Test {
  23006. protected:
  23007. void SetUp() override {
  23008. server_ = httplib::detail::make_unique<Server>();
  23009. setup_server();
  23010. start_server();
  23011. }
  23012. void TearDown() override {
  23013. server_->stop();
  23014. if (server_thread_.joinable()) { server_thread_.join(); }
  23015. }
  23016. void setup_server() {
  23017. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23018. std::string msg;
  23019. ws::ReadResult ret;
  23020. while ((ret = ws.read(msg))) {
  23021. if (ret == ws::Binary) {
  23022. ws.send(msg.data(), msg.size());
  23023. } else {
  23024. ws.send(msg);
  23025. }
  23026. }
  23027. });
  23028. server_->WebSocket("/ws-echo-string",
  23029. [](const Request &, ws::WebSocket &ws) {
  23030. std::string msg;
  23031. while (ws.read(msg)) {
  23032. ws.send("echo: " + msg);
  23033. }
  23034. });
  23035. server_->WebSocket(
  23036. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23037. // Echo back request metadata
  23038. ws.send("path:" + req.path);
  23039. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23040. std::string msg;
  23041. while (ws.read(msg)) {}
  23042. });
  23043. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23044. std::string msg;
  23045. ws.read(msg); // wait for a message
  23046. ws.close();
  23047. });
  23048. server_->WebSocket("/ws-close-status",
  23049. [](const Request &, ws::WebSocket &ws) {
  23050. std::string msg;
  23051. ws.read(msg); // wait for a message
  23052. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23053. });
  23054. server_->WebSocket(
  23055. "/ws-subprotocol",
  23056. [](const Request &, ws::WebSocket &ws) {
  23057. std::string msg;
  23058. while (ws.read(msg)) {
  23059. ws.send(msg);
  23060. }
  23061. },
  23062. [](const std::vector<std::string> &protocols) -> std::string {
  23063. for (const auto &p : protocols) {
  23064. if (p == "graphql-ws") { return p; }
  23065. }
  23066. return "";
  23067. });
  23068. server_->WebSocket(
  23069. "/ws-subprotocol-unoffered",
  23070. [](const Request &, ws::WebSocket &ws) {
  23071. std::string msg;
  23072. while (ws.read(msg)) {
  23073. ws.send(msg);
  23074. }
  23075. },
  23076. [](const std::vector<std::string> &) -> std::string {
  23077. return "admin";
  23078. });
  23079. }
  23080. void start_server() {
  23081. port_ = server_->bind_to_any_port(HOST);
  23082. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23083. server_->wait_until_ready();
  23084. }
  23085. std::unique_ptr<Server> server_;
  23086. std::thread server_thread_;
  23087. int port_ = 0;
  23088. };
  23089. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23090. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23091. "/ws-echo");
  23092. ASSERT_TRUE(client.connect());
  23093. ASSERT_TRUE(client.is_open());
  23094. ASSERT_TRUE(client.send("Hello WebSocket"));
  23095. std::string msg;
  23096. EXPECT_EQ(ws::Text, client.read(msg));
  23097. EXPECT_EQ("Hello WebSocket", msg);
  23098. client.close();
  23099. }
  23100. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23101. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23102. "/ws-echo");
  23103. ASSERT_TRUE(client.connect());
  23104. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23105. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23106. std::string msg;
  23107. EXPECT_EQ(ws::Binary, client.read(msg));
  23108. EXPECT_EQ(binary_data, msg);
  23109. client.close();
  23110. }
  23111. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23112. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23113. "/ws-echo");
  23114. ASSERT_TRUE(client.connect());
  23115. for (int i = 0; i < 10; i++) {
  23116. auto text = "message " + std::to_string(i);
  23117. ASSERT_TRUE(client.send(text));
  23118. std::string msg;
  23119. ASSERT_TRUE(client.read(msg));
  23120. EXPECT_EQ(text, msg);
  23121. }
  23122. client.close();
  23123. }
  23124. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23125. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23126. "/ws-close");
  23127. ASSERT_TRUE(client.connect());
  23128. // Send a message to trigger the server to close
  23129. ASSERT_TRUE(client.send("trigger close"));
  23130. // The server will close, so read should return false
  23131. std::string msg;
  23132. EXPECT_FALSE(client.read(msg));
  23133. EXPECT_FALSE(client.is_open());
  23134. }
  23135. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23136. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23137. "/ws-echo");
  23138. ASSERT_TRUE(client.connect());
  23139. // 128KB message
  23140. std::string large_data(128 * 1024, 'X');
  23141. ASSERT_TRUE(client.send(large_data));
  23142. std::string msg;
  23143. ASSERT_TRUE(client.read(msg));
  23144. EXPECT_EQ(large_data, msg);
  23145. client.close();
  23146. }
  23147. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23148. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23149. "/ws-echo");
  23150. ASSERT_TRUE(client.connect());
  23151. const int num_threads = 4;
  23152. std::vector<std::thread> threads;
  23153. std::atomic<int> send_count{0};
  23154. for (int t = 0; t < num_threads; t++) {
  23155. threads.emplace_back([&client, &send_count, t]() {
  23156. for (int i = 0; i < 5; i++) {
  23157. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23158. if (client.send(text)) { send_count++; }
  23159. }
  23160. });
  23161. }
  23162. for (auto &th : threads) {
  23163. th.join();
  23164. }
  23165. int received = 0;
  23166. std::string msg;
  23167. while (received < send_count.load()) {
  23168. if (!client.read(msg)) { break; }
  23169. received++;
  23170. }
  23171. EXPECT_EQ(send_count.load(), received);
  23172. client.close();
  23173. }
  23174. TEST_F(WebSocketIntegrationTest, ReadString) {
  23175. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23176. "/ws-echo-string");
  23177. ASSERT_TRUE(client.connect());
  23178. ASSERT_TRUE(client.send("hello"));
  23179. std::string msg;
  23180. ASSERT_TRUE(client.read(msg));
  23181. EXPECT_EQ("echo: hello", msg);
  23182. ASSERT_TRUE(client.send("world"));
  23183. ASSERT_TRUE(client.read(msg));
  23184. EXPECT_EQ("echo: world", msg);
  23185. client.close();
  23186. }
  23187. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23188. Headers headers = {{"X-Test-Header", "test-value"}};
  23189. ws::WebSocketClient client(
  23190. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23191. ASSERT_TRUE(client.connect());
  23192. std::string msg;
  23193. ASSERT_TRUE(client.read(msg));
  23194. EXPECT_EQ("path:/ws-request-info", msg);
  23195. ASSERT_TRUE(client.read(msg));
  23196. EXPECT_EQ("header:test-value", msg);
  23197. client.close();
  23198. }
  23199. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23201. "/ws-echo");
  23202. client.set_read_timeout(1, 0); // 1 second
  23203. ASSERT_TRUE(client.connect());
  23204. // Don't send anything — server echo handler waits for a message, so read()
  23205. // should time out. The connection survives it: nothing was consumed.
  23206. std::string msg;
  23207. EXPECT_EQ(client.read(msg), ws::Timeout);
  23208. EXPECT_TRUE(client.is_open());
  23209. // And it is still usable afterwards.
  23210. EXPECT_TRUE(client.send("after timeout"));
  23211. EXPECT_EQ(client.read(msg), ws::Text);
  23212. EXPECT_EQ(msg, "after timeout");
  23213. }
  23214. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23215. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23216. "/ws-echo");
  23217. client.set_read_timeout(1, 0);
  23218. ASSERT_TRUE(client.connect());
  23219. ASSERT_TRUE(client.send("first"));
  23220. std::string msg;
  23221. ASSERT_EQ(client.read(msg), ws::Text);
  23222. ASSERT_EQ(msg, "first");
  23223. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23224. // not be used with a read timeout: it would reprocess the previous message.
  23225. EXPECT_EQ(client.read(msg), ws::Timeout);
  23226. EXPECT_EQ(msg, "first");
  23227. }
  23228. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23229. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23230. "/ws-echo");
  23231. ASSERT_TRUE(client.connect());
  23232. // Setting it once the connection is open reaches the live stream, not just
  23233. // the seed for the next connect().
  23234. client.set_read_timeout(1, 0);
  23235. std::string msg;
  23236. EXPECT_EQ(client.read(msg), ws::Timeout);
  23237. EXPECT_TRUE(client.is_open());
  23238. }
  23239. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23240. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23241. "/ws-echo");
  23242. client.set_read_timeout(5, 0);
  23243. ASSERT_TRUE(client.connect());
  23244. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23245. // The server should reject it and close the connection.
  23246. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23247. client.send(oversized);
  23248. // The server's read() should have failed due to payload limit,
  23249. // so our read() should return false (connection closed).
  23250. std::string msg;
  23251. EXPECT_FALSE(client.read(msg));
  23252. }
  23253. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23254. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23255. "/ws-echo");
  23256. client.set_read_timeout(10, 0);
  23257. ASSERT_TRUE(client.connect());
  23258. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23259. // This should succeed.
  23260. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23261. ASSERT_TRUE(client.send(at_limit));
  23262. std::string msg;
  23263. ASSERT_TRUE(client.read(msg));
  23264. EXPECT_EQ(at_limit.size(), msg.size());
  23265. client.close();
  23266. }
  23267. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23269. "/nonexistent");
  23270. auto res = client.connect();
  23271. EXPECT_FALSE(res);
  23272. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23273. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23274. EXPECT_FALSE(client.is_open());
  23275. }
  23276. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23277. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23278. "/ws-echo");
  23279. ASSERT_TRUE(client.connect());
  23280. ASSERT_TRUE(client.send(""));
  23281. std::string msg;
  23282. EXPECT_EQ(ws::Text, client.read(msg));
  23283. EXPECT_EQ("", msg);
  23284. client.close();
  23285. }
  23286. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23287. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23288. "/ws-echo");
  23289. // First connection
  23290. ASSERT_TRUE(client.connect());
  23291. ASSERT_TRUE(client.send("first"));
  23292. std::string msg;
  23293. ASSERT_TRUE(client.read(msg));
  23294. EXPECT_EQ("first", msg);
  23295. client.close();
  23296. EXPECT_FALSE(client.is_open());
  23297. // Reconnect using the same client object
  23298. ASSERT_TRUE(client.connect());
  23299. ASSERT_TRUE(client.is_open());
  23300. ASSERT_TRUE(client.send("second"));
  23301. ASSERT_TRUE(client.read(msg));
  23302. EXPECT_EQ("second", msg);
  23303. client.close();
  23304. }
  23305. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23307. "/ws-close-status");
  23308. ASSERT_TRUE(client.connect());
  23309. // Trigger the server to close with GoingAway status
  23310. ASSERT_TRUE(client.send("trigger"));
  23311. // read() should return false after receiving the close frame
  23312. std::string msg;
  23313. EXPECT_FALSE(client.read(msg));
  23314. EXPECT_FALSE(client.is_open());
  23315. }
  23316. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23317. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23318. "/ws-echo");
  23319. ASSERT_TRUE(client.connect());
  23320. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23321. EXPECT_FALSE(client.is_open());
  23322. }
  23323. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23324. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23325. ws::WebSocketClient client(
  23326. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23327. ASSERT_TRUE(client.connect());
  23328. // Server should have selected graphql-ws
  23329. EXPECT_EQ("graphql-ws", client.subprotocol());
  23330. client.close();
  23331. }
  23332. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23333. Headers headers;
  23334. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23335. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23336. ws::WebSocketClient client(
  23337. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23338. ASSERT_TRUE(client.connect());
  23339. // The offer on the second field line counts too, so graphql-ws is selected
  23340. EXPECT_EQ("graphql-ws", client.subprotocol());
  23341. client.close();
  23342. }
  23343. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23344. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23345. ws::WebSocketClient client(
  23346. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23347. ASSERT_TRUE(client.connect());
  23348. // Server should not have selected any subprotocol
  23349. EXPECT_TRUE(client.subprotocol().empty());
  23350. client.close();
  23351. }
  23352. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23353. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23354. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23355. "/ws-subprotocol-unoffered",
  23356. headers);
  23357. ASSERT_TRUE(client.connect());
  23358. EXPECT_TRUE(client.subprotocol().empty());
  23359. client.close();
  23360. }
  23361. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23362. // Connect without requesting any subprotocol
  23363. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23364. "/ws-subprotocol");
  23365. ASSERT_TRUE(client.connect());
  23366. EXPECT_TRUE(client.subprotocol().empty());
  23367. client.close();
  23368. }
  23369. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23371. "/ws-echo");
  23372. client.set_tcp_nodelay(true);
  23373. client.set_connection_timeout(3, 0);
  23374. bool socket_options_called = false;
  23375. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23376. ASSERT_TRUE(client.connect());
  23377. ASSERT_TRUE(client.is_open());
  23378. EXPECT_TRUE(socket_options_called);
  23379. ASSERT_TRUE(client.send("hello"));
  23380. std::string msg;
  23381. auto result = client.read(msg);
  23382. EXPECT_EQ(result, ws::ReadResult::Text);
  23383. EXPECT_EQ(msg, "hello");
  23384. client.close();
  23385. }
  23386. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23388. "/ws-echo");
  23389. client.set_connection_timeout(std::chrono::seconds(3));
  23390. client.set_write_timeout(std::chrono::seconds(3));
  23391. // A sub-second remainder exercises the seconds/microseconds split.
  23392. client.set_read_timeout(std::chrono::milliseconds(1500));
  23393. ASSERT_TRUE(client.connect());
  23394. auto start = std::chrono::steady_clock::now();
  23395. std::string msg;
  23396. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23397. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23398. std::chrono::steady_clock::now() - start)
  23399. .count();
  23400. // Above 1s so that dropping the microseconds half of the split fails here.
  23401. // Ignoring the setter altogether would not reach this line at all: a client
  23402. // waits forever by default.
  23403. EXPECT_GE(elapsed, 1400);
  23404. EXPECT_LT(elapsed, 30000);
  23405. }
  23406. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23407. Server svr;
  23408. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23409. if (!req.has_header("Authorization")) {
  23410. res.status = StatusCode::Unauthorized_401;
  23411. res.set_content("Unauthorized", "text/plain");
  23412. return Server::HandlerResponse::Handled;
  23413. }
  23414. return Server::HandlerResponse::Unhandled;
  23415. });
  23416. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23417. std::string msg;
  23418. while (ws.read(msg)) {
  23419. ws.send(msg);
  23420. }
  23421. });
  23422. auto port = svr.bind_to_any_port("localhost");
  23423. std::thread t([&]() { svr.listen_after_bind(); });
  23424. svr.wait_until_ready();
  23425. // Without Authorization header - should be rejected before upgrade
  23426. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23427. EXPECT_FALSE(client1.connect());
  23428. // The rejection is framed like any other HTTP response
  23429. {
  23430. Client cli("localhost", port);
  23431. Headers headers = {{"Upgrade", "websocket"},
  23432. {"Connection", "Upgrade"},
  23433. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23434. {"Sec-WebSocket-Version", "13"}};
  23435. auto res = cli.Get("/ws", headers);
  23436. ASSERT_TRUE(res);
  23437. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23438. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23439. EXPECT_EQ("Unauthorized", res->body);
  23440. }
  23441. // With Authorization header - should succeed
  23442. Headers headers = {{"Authorization", "Bearer token123"}};
  23443. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23444. headers);
  23445. ASSERT_TRUE(client2.connect());
  23446. ASSERT_TRUE(client2.send("hello"));
  23447. std::string msg;
  23448. ASSERT_TRUE(client2.read(msg));
  23449. EXPECT_EQ("hello", msg);
  23450. client2.close();
  23451. svr.stop();
  23452. t.join();
  23453. }
  23454. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23455. Server svr;
  23456. std::atomic<int> pre_routing_calls{0};
  23457. std::atomic<int> pre_request_calls{0};
  23458. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23459. pre_routing_calls++;
  23460. if (req.path == "/handled") {
  23461. res.set_content("handled", "text/plain");
  23462. return Server::HandlerResponse::Handled;
  23463. }
  23464. return Server::HandlerResponse::Unhandled;
  23465. });
  23466. svr.set_pre_request_handler([&](const Request &, Response &) {
  23467. pre_request_calls++;
  23468. return Server::HandlerResponse::Unhandled;
  23469. });
  23470. svr.Get("/http", [](const Request &, Response &res) {
  23471. res.set_content("http", "text/plain");
  23472. });
  23473. svr.WebSocket("/ws",
  23474. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23475. auto port = svr.bind_to_any_port("localhost");
  23476. std::thread t([&]() { svr.listen_after_bind(); });
  23477. auto se = detail::scope_exit([&] {
  23478. svr.stop();
  23479. t.join();
  23480. });
  23481. svr.wait_until_ready();
  23482. Headers upgrade = {{"Upgrade", "websocket"},
  23483. {"Connection", "Upgrade"},
  23484. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23485. {"Sec-WebSocket-Version", "13"}};
  23486. auto get = [&](const char *path) {
  23487. pre_routing_calls = 0;
  23488. return Client("localhost", port).Get(path, upgrade);
  23489. };
  23490. // No WebSocket route, but an HTTP one
  23491. auto res = get("/http");
  23492. ASSERT_TRUE(res);
  23493. EXPECT_EQ(StatusCode::OK_200, res->status);
  23494. EXPECT_EQ("http", res->body);
  23495. EXPECT_EQ(1, pre_routing_calls);
  23496. EXPECT_EQ(1, pre_request_calls);
  23497. // No route at all
  23498. res = get("/none");
  23499. ASSERT_TRUE(res);
  23500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23501. EXPECT_EQ(1, pre_routing_calls);
  23502. // Answered by the pre-routing handler
  23503. res = get("/handled");
  23504. ASSERT_TRUE(res);
  23505. EXPECT_EQ(StatusCode::OK_200, res->status);
  23506. EXPECT_EQ("handled", res->body);
  23507. EXPECT_EQ(1, pre_routing_calls);
  23508. // A WebSocket route
  23509. pre_routing_calls = 0;
  23510. pre_request_calls = 0;
  23511. {
  23512. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23513. "/ws");
  23514. ASSERT_TRUE(client.connect());
  23515. std::string msg;
  23516. ASSERT_TRUE(client.read(msg));
  23517. EXPECT_EQ("ws", msg);
  23518. client.close();
  23519. }
  23520. EXPECT_EQ(1, pre_routing_calls);
  23521. EXPECT_EQ(1, pre_request_calls);
  23522. }
  23523. // An upgrade request answered by a hook leaves its body unread, so that body
  23524. // must not be served as the next request on the connection.
  23525. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23526. Server svr;
  23527. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23528. if (req.path == "/pre-routing") {
  23529. res.set_content("pre-routing", "text/plain");
  23530. return Server::HandlerResponse::Handled;
  23531. }
  23532. return Server::HandlerResponse::Unhandled;
  23533. });
  23534. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23535. if (req.matched_route == "/pre-request") {
  23536. res.set_content("pre-request", "text/plain");
  23537. return Server::HandlerResponse::Handled;
  23538. }
  23539. return Server::HandlerResponse::Unhandled;
  23540. });
  23541. svr.Get("/smuggled", [](const Request &, Response &res) {
  23542. res.set_content("smuggled", "text/plain");
  23543. });
  23544. svr.WebSocket("/pre-request",
  23545. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23546. auto port = svr.bind_to_any_port(HOST);
  23547. std::thread t([&]() { svr.listen_after_bind(); });
  23548. auto se = detail::scope_exit([&] {
  23549. svr.stop();
  23550. t.join();
  23551. });
  23552. svr.wait_until_ready();
  23553. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23554. for (auto path : {"/pre-routing", "/pre-request"}) {
  23555. std::string req = std::string("GET ") + path +
  23556. " HTTP/1.1\r\n"
  23557. "Host: localhost\r\n"
  23558. "Upgrade: websocket\r\n"
  23559. "Connection: Upgrade\r\n"
  23560. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23561. "Sec-WebSocket-Version: 13\r\n"
  23562. "Content-Length: " +
  23563. std::to_string(body.size()) + "\r\n\r\n" + body;
  23564. std::string res;
  23565. ASSERT_TRUE(send_request(5, req, &res, port));
  23566. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23567. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23568. // Only one response, and the body was not served as a request
  23569. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23570. }
  23571. }
  23572. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23573. Server svr;
  23574. std::atomic<int> pre_request_calls{0};
  23575. std::atomic<bool> route_matched{false};
  23576. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23577. pre_request_calls++;
  23578. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23579. if (req.get_header_value("Authorization") != "Bearer token123") {
  23580. res.status = StatusCode::Unauthorized_401;
  23581. res.set_content("Unauthorized", "text/plain");
  23582. return Server::HandlerResponse::Handled;
  23583. }
  23584. return Server::HandlerResponse::Unhandled;
  23585. });
  23586. std::atomic<bool> handler_called{false};
  23587. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23588. handler_called = true;
  23589. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23590. });
  23591. auto port = svr.bind_to_any_port("localhost");
  23592. std::thread t([&]() { svr.listen_after_bind(); });
  23593. svr.wait_until_ready();
  23594. // Without Authorization header - should be rejected before upgrade
  23595. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23596. "/ws/1");
  23597. EXPECT_FALSE(client1.connect());
  23598. EXPECT_FALSE(handler_called);
  23599. EXPECT_EQ(1, pre_request_calls);
  23600. EXPECT_TRUE(route_matched);
  23601. // The rejection is an ordinary HTTP response, not a protocol switch
  23602. {
  23603. Client cli("localhost", port);
  23604. Headers headers = {{"Upgrade", "websocket"},
  23605. {"Connection", "Upgrade"},
  23606. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23607. {"Sec-WebSocket-Version", "13"}};
  23608. auto res = cli.Get("/ws/1", headers);
  23609. ASSERT_TRUE(res);
  23610. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23611. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23612. EXPECT_EQ("Unauthorized", res->body);
  23613. }
  23614. EXPECT_FALSE(handler_called);
  23615. // With Authorization header - should succeed
  23616. Headers headers = {{"Authorization", "Bearer token123"}};
  23617. ws::WebSocketClient client2(
  23618. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23619. ASSERT_TRUE(client2.connect());
  23620. std::string msg;
  23621. ASSERT_TRUE(client2.read(msg));
  23622. EXPECT_EQ("/ws/:id 2", msg);
  23623. EXPECT_TRUE(handler_called);
  23624. client2.close();
  23625. svr.stop();
  23626. t.join();
  23627. }
  23628. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23629. Server svr;
  23630. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23631. // A read timeout is how a handler gets control back. Without it, a handler
  23632. // parked in read() can never write on the connection it is reading.
  23633. ws.set_read_timeout(std::chrono::milliseconds(100));
  23634. std::string msg;
  23635. while (ws.is_open()) {
  23636. auto r = ws.read(msg);
  23637. if (r == httplib::ws::Timeout) {
  23638. ws.send("tick");
  23639. continue;
  23640. }
  23641. if (r == httplib::ws::Fail) { break; }
  23642. ws.send(msg);
  23643. }
  23644. });
  23645. auto port = svr.bind_to_any_port("localhost");
  23646. std::thread t([&]() { svr.listen_after_bind(); });
  23647. svr.wait_until_ready();
  23648. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23649. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23650. ASSERT_TRUE(client.connect());
  23651. // The client sends nothing, so anything it receives came out of the
  23652. // handler's timeout path.
  23653. std::string msg;
  23654. ASSERT_EQ(client.read(msg), ws::Text);
  23655. EXPECT_EQ("tick", msg);
  23656. client.close();
  23657. svr.stop();
  23658. t.join();
  23659. }
  23660. // Stream::read may return fewer bytes than asked for. This is that contract at
  23661. // its worst -- one byte per call -- which is what a frame header straddling a
  23662. // read buffer's boundary looks like to the frame parser.
  23663. class WsByteAtATimeStream : public Stream {
  23664. public:
  23665. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23666. bool is_readable() const override { return true; }
  23667. bool wait_readable() const override { return true; }
  23668. bool wait_writable() const override { return true; }
  23669. ssize_t read(char *ptr, size_t size) override {
  23670. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23671. *ptr = data_[pos_++];
  23672. return 1;
  23673. }
  23674. ssize_t write(const char *, size_t size) override {
  23675. return static_cast<ssize_t>(size);
  23676. }
  23677. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23678. ip = "127.0.0.1";
  23679. port = 0;
  23680. }
  23681. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23682. ip = "127.0.0.1";
  23683. port = 0;
  23684. }
  23685. socket_t socket() const override { return INVALID_SOCKET; }
  23686. time_t duration() const override { return 0; }
  23687. private:
  23688. std::string data_;
  23689. size_t pos_ = 0;
  23690. };
  23691. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23692. // The payload uses the 16-bit extended length, so the header, the length
  23693. // and the mask key are all multi-byte fields here. Each used to be read
  23694. // with a single read() call, which fails as soon as one is split. The
  23695. // payload is also a little over one read chunk, so it is read in two.
  23696. std::string body;
  23697. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23698. body += static_cast<char>(i % 251);
  23699. }
  23700. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23701. std::string frame;
  23702. frame += static_cast<char>(0x81); // FIN + Text
  23703. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23704. frame += static_cast<char>(body.size() >> 8);
  23705. frame += static_cast<char>(body.size() & 0xff);
  23706. for (size_t i = 0; i < 4; i++) {
  23707. frame += static_cast<char>(mask[i]);
  23708. }
  23709. for (size_t i = 0; i < body.size(); i++) {
  23710. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23711. }
  23712. WsByteAtATimeStream strm(frame);
  23713. ws::Opcode opcode;
  23714. std::string payload;
  23715. bool fin = false;
  23716. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23717. /*expect_masked=*/true, body.size()),
  23718. ws::impl::FrameRead::Ok);
  23719. EXPECT_TRUE(fin);
  23720. EXPECT_EQ(opcode, ws::Opcode::Text);
  23721. EXPECT_EQ(payload, body);
  23722. }
  23723. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23724. std::string body(2000, 'x');
  23725. std::string frame;
  23726. frame += static_cast<char>(0x82); // FIN + Binary
  23727. frame += static_cast<char>(126); // 16-bit length follows
  23728. frame += static_cast<char>(body.size() >> 8);
  23729. frame += static_cast<char>(body.size() & 0xff);
  23730. frame += body;
  23731. detail::BufferStream strm;
  23732. strm.write(frame.data(), frame.size());
  23733. ws::Opcode opcode;
  23734. std::string payload;
  23735. bool fin;
  23736. EXPECT_EQ(
  23737. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23738. ws::impl::FrameRead::Ok);
  23739. EXPECT_EQ(body, payload);
  23740. }
  23741. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23742. // The header announces the largest payload allowed, and only 3 bytes of it
  23743. // ever arrive.
  23744. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23745. std::string frame;
  23746. frame += static_cast<char>(0x82); // FIN + Binary
  23747. frame += static_cast<char>(127); // 64-bit length follows
  23748. for (int shift = 56; shift >= 0; shift -= 8) {
  23749. frame += static_cast<char>((len >> shift) & 0xff);
  23750. }
  23751. frame += "abc";
  23752. detail::BufferStream strm;
  23753. strm.write(frame.data(), frame.size());
  23754. ws::Opcode opcode;
  23755. std::string payload;
  23756. bool fin;
  23757. EXPECT_EQ(
  23758. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23759. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23760. ws::impl::FrameRead::Fail);
  23761. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23762. }
  23763. TEST(WebSocketTest, QueryStringInHandshake) {
  23764. Server svr;
  23765. std::mutex mtx;
  23766. std::string received_target;
  23767. std::string received_token;
  23768. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23769. {
  23770. std::lock_guard<std::mutex> lock(mtx);
  23771. received_target = req.target;
  23772. if (req.has_param("token")) {
  23773. received_token = req.get_param_value("token");
  23774. }
  23775. }
  23776. std::string msg;
  23777. while (ws.read(msg)) {
  23778. ws.send(msg);
  23779. }
  23780. });
  23781. auto port = svr.bind_to_any_port("localhost");
  23782. std::thread t([&]() { svr.listen_after_bind(); });
  23783. svr.wait_until_ready();
  23784. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23785. "/ws?token=ABC&session=123");
  23786. ASSERT_TRUE(client.connect());
  23787. // Round-trip ensures the handler has run and captured the request.
  23788. ASSERT_TRUE(client.send("hello"));
  23789. std::string msg;
  23790. ASSERT_TRUE(client.read(msg));
  23791. EXPECT_EQ("hello", msg);
  23792. client.close();
  23793. {
  23794. std::lock_guard<std::mutex> lock(mtx);
  23795. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23796. EXPECT_EQ("ABC", received_token);
  23797. }
  23798. svr.stop();
  23799. t.join();
  23800. }
  23801. // Run a handshake against a throwaway server and hand the request the server
  23802. // received back to the caller, so tests can assert on the headers the client
  23803. // actually put on the wire.
  23804. static void capture_websocket_handshake_request(
  23805. const Headers &client_headers,
  23806. std::function<void(const Request &, int port)> verify) {
  23807. Server svr;
  23808. std::mutex mtx;
  23809. Request received;
  23810. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23811. {
  23812. std::lock_guard<std::mutex> lock(mtx);
  23813. received = req;
  23814. }
  23815. std::string msg;
  23816. while (ws.read(msg)) {
  23817. ws.send(msg);
  23818. }
  23819. });
  23820. auto port = svr.bind_to_any_port("localhost");
  23821. std::thread t([&]() { svr.listen_after_bind(); });
  23822. auto se = detail::scope_exit([&] {
  23823. svr.stop();
  23824. t.join();
  23825. });
  23826. svr.wait_until_ready();
  23827. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23828. client_headers);
  23829. ASSERT_TRUE(client.connect());
  23830. ASSERT_TRUE(client.send("hello"));
  23831. std::string msg;
  23832. ASSERT_TRUE(client.read(msg));
  23833. client.close();
  23834. {
  23835. std::lock_guard<std::mutex> lock(mtx);
  23836. verify(received, port);
  23837. }
  23838. }
  23839. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23840. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23841. // Non-default port must be present in the Host header. Default ports
  23842. // (80/443) are omitted; that logic is covered by
  23843. // MakeHostAndPortStringTest.
  23844. EXPECT_EQ("localhost:" + std::to_string(port),
  23845. req.get_header_value("Host"));
  23846. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23847. req.get_header_value("User-Agent"));
  23848. EXPECT_FALSE(req.has_header("Accept"));
  23849. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23850. EXPECT_FALSE(req.has_header("Content-Length"));
  23851. });
  23852. }
  23853. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23854. capture_websocket_handshake_request(
  23855. {{"Host", "example.com"},
  23856. {"User-Agent", "custom-agent"},
  23857. {"X-Custom", "value"}},
  23858. [](const Request &req, int) {
  23859. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23860. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23861. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23862. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23863. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23864. });
  23865. }
  23866. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23867. capture_websocket_handshake_request(
  23868. {{"Upgrade", "bogus"},
  23869. {"Connection", "close"},
  23870. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23871. {"Sec-WebSocket-Version", "8"}},
  23872. [](const Request &req, int) {
  23873. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23874. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23875. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23876. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23877. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23878. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23879. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23880. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23881. req.get_header_value("Sec-WebSocket-Key"));
  23882. });
  23883. }
  23884. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23885. // A header the client refuses to send must abort the handshake before any
  23886. // part of it reaches the wire; a lone request line would otherwise sit in
  23887. // the peer's buffer as a truncated request.
  23888. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23889. ASSERT_NE(INVALID_SOCKET, srv);
  23890. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23891. sockaddr_in addr{};
  23892. addr.sin_family = AF_INET;
  23893. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23894. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23895. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23896. ASSERT_EQ(0, ::listen(srv, 1));
  23897. sockaddr_in bound{};
  23898. socklen_t bound_len = sizeof(bound);
  23899. ASSERT_EQ(
  23900. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23901. auto port = ntohs(bound.sin_port);
  23902. ssize_t received = -1;
  23903. std::thread t([&] {
  23904. // Bound every blocking call so a regression fails the test with a bad
  23905. // value instead of hanging the suite.
  23906. fd_set rfds;
  23907. FD_ZERO(&rfds);
  23908. FD_SET(srv, &rfds);
  23909. timeval tv{5, 0};
  23910. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23911. 0) {
  23912. return;
  23913. }
  23914. sockaddr_in cli_addr{};
  23915. socklen_t cli_len = sizeof(cli_addr);
  23916. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23917. if (cli == INVALID_SOCKET) { return; }
  23918. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23919. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23920. char buf[4096];
  23921. received = ::recv(cli, buf, sizeof(buf), 0);
  23922. });
  23923. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23924. // connect() has already shut the socket down by the time it returns false,
  23925. // so the peer sees EOF without waiting for the client to be destroyed.
  23926. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23927. {{"X-Bad", "a\r\nInjected: 1"}});
  23928. EXPECT_FALSE(client.connect());
  23929. t.join();
  23930. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23931. EXPECT_EQ(0, received);
  23932. }
  23933. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23934. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23935. // contains "upgrade" as a substring is a different token and must not
  23936. // start a WebSocket handshake.
  23937. auto make_request = [](const std::vector<std::string> &connection_values) {
  23938. Request req;
  23939. req.method = "GET";
  23940. req.headers.emplace("Upgrade", "websocket");
  23941. for (const auto &value : connection_values) {
  23942. req.headers.emplace("Connection", value);
  23943. }
  23944. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23945. req.headers.emplace("Sec-WebSocket-Version", "13");
  23946. return req;
  23947. };
  23948. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23949. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23950. EXPECT_TRUE(
  23951. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23952. EXPECT_TRUE(
  23953. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23954. EXPECT_TRUE(
  23955. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23956. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23957. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23958. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23959. EXPECT_FALSE(
  23960. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23961. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23962. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23963. }
  23964. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23965. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23966. // asks recipients to match each protocol-name case-insensitively, and RFC
  23967. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23968. // client naming websocket alongside another protocol, or on a second field
  23969. // line, is offering websocket; a value that merely contains "websocket" as a
  23970. // substring is a different protocol name and is not.
  23971. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23972. Request req;
  23973. req.method = "GET";
  23974. for (const auto &value : upgrade_values) {
  23975. req.headers.emplace("Upgrade", value);
  23976. }
  23977. req.headers.emplace("Connection", "Upgrade");
  23978. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23979. req.headers.emplace("Sec-WebSocket-Version", "13");
  23980. return req;
  23981. };
  23982. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23983. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23984. EXPECT_TRUE(
  23985. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23986. EXPECT_TRUE(
  23987. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23988. EXPECT_TRUE(
  23989. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23990. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23991. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23992. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23993. EXPECT_FALSE(
  23994. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23995. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23996. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23997. }
  23998. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23999. Server svr;
  24000. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24001. auto port = svr.bind_to_any_port("localhost");
  24002. std::thread t([&]() { svr.listen_after_bind(); });
  24003. auto se = detail::scope_exit([&] {
  24004. svr.stop();
  24005. t.join();
  24006. });
  24007. svr.wait_until_ready();
  24008. Headers headers = {{"Upgrade", "websocket"},
  24009. {"Connection", "notupgrade"},
  24010. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24011. {"Sec-WebSocket-Version", "13"}};
  24012. Client cli("localhost", port);
  24013. auto res = cli.Get("/ws", headers);
  24014. // The route exists only as a WebSocket route, so a request that fails the
  24015. // handshake check falls through to ordinary routing.
  24016. ASSERT_TRUE(res);
  24017. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24018. }
  24019. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24020. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24021. // Connection value is the only thing left for the client to reject.
  24022. Server svr;
  24023. svr.Get("/ws", [](const Request &req, Response &res) {
  24024. res.status = StatusCode::SwitchingProtocol_101;
  24025. res.set_header("Upgrade", "websocket");
  24026. res.set_header("Connection", "notupgrade");
  24027. res.set_header("Sec-WebSocket-Accept",
  24028. detail::websocket_accept_key(
  24029. req.get_header_value("Sec-WebSocket-Key")));
  24030. });
  24031. auto port = svr.bind_to_any_port("localhost");
  24032. std::thread t([&]() { svr.listen_after_bind(); });
  24033. auto se = detail::scope_exit([&] {
  24034. svr.stop();
  24035. t.join();
  24036. });
  24037. svr.wait_until_ready();
  24038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24039. auto res = client.connect();
  24040. EXPECT_FALSE(res);
  24041. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24042. EXPECT_FALSE(client.is_open());
  24043. }
  24044. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24045. Server svr;
  24046. svr.Get("/ws", [](const Request &req, Response &res) {
  24047. res.status = StatusCode::SwitchingProtocol_101;
  24048. res.set_header("Upgrade", "websocket");
  24049. res.set_header("Connection", "Upgrade");
  24050. res.set_header("Sec-WebSocket-Accept",
  24051. detail::websocket_accept_key(
  24052. req.get_header_value("Sec-WebSocket-Key")));
  24053. res.set_header("Sec-WebSocket-Protocol", "admin");
  24054. });
  24055. auto port = svr.bind_to_any_port("localhost");
  24056. std::thread t([&]() { svr.listen_after_bind(); });
  24057. auto se = detail::scope_exit([&] {
  24058. svr.stop();
  24059. t.join();
  24060. });
  24061. svr.wait_until_ready();
  24062. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24063. // Server selects a subprotocol the client never offered
  24064. {
  24065. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24066. ws::WebSocketClient client(url, headers);
  24067. auto res = client.connect();
  24068. EXPECT_FALSE(res);
  24069. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24070. EXPECT_FALSE(client.is_open());
  24071. EXPECT_TRUE(client.subprotocol().empty());
  24072. }
  24073. // Client offered none but the server named one anyway
  24074. {
  24075. ws::WebSocketClient client(url);
  24076. auto res = client.connect();
  24077. EXPECT_FALSE(res);
  24078. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24079. EXPECT_FALSE(client.is_open());
  24080. EXPECT_TRUE(client.subprotocol().empty());
  24081. }
  24082. }
  24083. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24084. // The socket path doubles as the URL host, so it must not contain '/'.
  24085. const char *shard = getenv("GTEST_SHARD_INDEX");
  24086. const std::string sock_path =
  24087. shard ? std::string("httplib-ws-") + shard + ".sock"
  24088. : std::string("httplib-ws.sock");
  24089. std::remove(sock_path.c_str());
  24090. Server svr;
  24091. std::mutex mtx;
  24092. std::string received_host;
  24093. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24094. {
  24095. std::lock_guard<std::mutex> lock(mtx);
  24096. received_host = req.get_header_value("Host");
  24097. }
  24098. std::string msg;
  24099. while (ws.read(msg)) {
  24100. ws.send(msg);
  24101. }
  24102. });
  24103. svr.set_address_family(AF_UNIX);
  24104. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24105. auto se = detail::scope_exit([&] {
  24106. svr.stop();
  24107. t.join();
  24108. std::remove(sock_path.c_str());
  24109. });
  24110. svr.wait_until_ready();
  24111. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24112. client.set_address_family(AF_UNIX);
  24113. ASSERT_TRUE(client.connect());
  24114. ASSERT_TRUE(client.send("hello"));
  24115. std::string msg;
  24116. ASSERT_TRUE(client.read(msg));
  24117. client.close();
  24118. {
  24119. std::lock_guard<std::mutex> lock(mtx);
  24120. // There is no host:port for a Unix socket, so the same "localhost"
  24121. // placeholder the HTTP client uses is expected.
  24122. EXPECT_EQ("localhost", received_host);
  24123. }
  24124. }
  24125. // Two threads must never parse WebSocket frames from the same stream.
  24126. // close() used to read the peer's Close reply with its own frame read, so it
  24127. // raced a reader thread that was in the middle of a payload: the payload loop
  24128. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24129. // so bytes taken by close() were replaced with bytes from further along the
  24130. // stream. The message kept its length and silently changed content.
  24131. //
  24132. // The raw peer below sends a frame header plus part of the payload, waits for
  24133. // the handler to call close(), and only then sends the rest. Whichever thread
  24134. // would win the race for those bytes, the message must arrive intact, because
  24135. // close() must not touch the stream while read() owns it.
  24136. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24137. #ifndef _WIN32
  24138. signal(SIGPIPE, SIG_IGN);
  24139. #endif
  24140. const size_t payload_len = 120; // fits the 7-bit length field
  24141. const size_t prefix_len = 8;
  24142. const int attempts = 8;
  24143. std::string expected(payload_len, '\0');
  24144. for (size_t i = 0; i < payload_len; i++) {
  24145. expected[i] = static_cast<char>('a' + i % 26);
  24146. }
  24147. std::atomic<bool> peer_stalled{false};
  24148. std::atomic<bool> handler_done{false};
  24149. std::mutex received_mutex;
  24150. std::vector<std::string> received;
  24151. // Bound every wait, so a regression fails the test instead of hanging the
  24152. // suite.
  24153. auto wait_for = [](const std::atomic<bool> &flag) {
  24154. for (int i = 0; i < 500 && !flag; i++) {
  24155. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24156. }
  24157. };
  24158. Server svr;
  24159. svr.set_websocket_ping_interval(0);
  24160. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24161. std::thread reader([&]() {
  24162. std::string msg;
  24163. while (ws.read(msg)) {
  24164. std::lock_guard<std::mutex> guard(received_mutex);
  24165. received.push_back(msg);
  24166. }
  24167. });
  24168. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24169. // inside read_websocket_frame() when close() runs.
  24170. wait_for(peer_stalled);
  24171. ws.close();
  24172. reader.join();
  24173. handler_done = true;
  24174. });
  24175. auto port = svr.bind_to_any_port("127.0.0.1");
  24176. std::thread t([&]() { svr.listen_after_bind(); });
  24177. auto se = detail::scope_exit([&] {
  24178. svr.stop();
  24179. t.join();
  24180. });
  24181. svr.wait_until_ready();
  24182. auto send_bytes = [](socket_t s, const std::string &data) {
  24183. #ifdef _WIN32
  24184. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24185. #else
  24186. auto n = ::send(s, data.data(), data.size(), 0);
  24187. #endif
  24188. return n == static_cast<decltype(n)>(data.size());
  24189. };
  24190. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24191. // Every length used here fits the 7-bit length field.
  24192. auto masked_header = [](uint8_t first_byte, size_t len) {
  24193. std::string h;
  24194. h += static_cast<char>(first_byte);
  24195. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24196. h.append(4, '\0'); // mask key
  24197. return h;
  24198. };
  24199. for (int attempt = 0; attempt < attempts; attempt++) {
  24200. peer_stalled = false;
  24201. handler_done = false;
  24202. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24203. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24204. auto se_sock = detail::scope_exit([&] {
  24205. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24206. });
  24207. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24208. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24209. sockaddr_in addr{};
  24210. addr.sin_family = AF_INET;
  24211. addr.sin_port = htons(static_cast<uint16_t>(port));
  24212. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24213. ASSERT_EQ(
  24214. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24215. << "attempt " << attempt;
  24216. ASSERT_TRUE(send_bytes(sock,
  24217. "GET /ws HTTP/1.1\r\n"
  24218. "Host: 127.0.0.1\r\n"
  24219. "Upgrade: websocket\r\n"
  24220. "Connection: Upgrade\r\n"
  24221. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24222. "Sec-WebSocket-Version: 13\r\n"
  24223. "\r\n"))
  24224. << "attempt " << attempt;
  24225. std::string response;
  24226. while (response.find("\r\n\r\n") == std::string::npos) {
  24227. char buf[512];
  24228. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24229. if (n <= 0) { break; }
  24230. response.append(buf, static_cast<size_t>(n));
  24231. }
  24232. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24233. << "attempt " << attempt;
  24234. // Send the header of a Binary message but only the first prefix_len bytes
  24235. // of its payload, leaving the reader thread stalled inside the payload.
  24236. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24237. expected.substr(0, prefix_len)))
  24238. << "attempt " << attempt;
  24239. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24240. peer_stalled = true;
  24241. // Let close() send its Close frame and park in its own read before the
  24242. // rest of the payload arrives, so both threads are waiting for it.
  24243. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24244. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24245. close_frame += static_cast<char>(0x03); // status 1000
  24246. close_frame += static_cast<char>(0xE8);
  24247. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24248. << "attempt " << attempt;
  24249. // Closing the peer releases the reader thread even on the buggy path,
  24250. // where it waits for bytes another thread already consumed.
  24251. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24252. detail::close_socket(sock);
  24253. sock = INVALID_SOCKET;
  24254. wait_for(handler_done);
  24255. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24256. }
  24257. std::lock_guard<std::mutex> guard(received_mutex);
  24258. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24259. << "a message in flight when close() ran was dropped";
  24260. for (size_t i = 0; i < received.size(); i++) {
  24261. EXPECT_EQ(expected, received[i]) << "message " << i;
  24262. }
  24263. }
  24264. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24265. // returning the socket, or INVALID_SOCKET.
  24266. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24267. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24268. if (sock == INVALID_SOCKET) { return sock; }
  24269. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24270. sockaddr_in addr{};
  24271. addr.sin_family = AF_INET;
  24272. addr.sin_port = htons(static_cast<uint16_t>(port));
  24273. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24274. std::string req = "GET " + path +
  24275. " HTTP/1.1\r\n"
  24276. "Host: 127.0.0.1\r\n"
  24277. "Upgrade: websocket\r\n"
  24278. "Connection: Upgrade\r\n"
  24279. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24280. "Sec-WebSocket-Version: 13\r\n"
  24281. "\r\n";
  24282. std::string res;
  24283. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24284. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24285. static_cast<ssize_t>(req.size())) {
  24286. char c;
  24287. while (res.find("\r\n\r\n") == std::string::npos &&
  24288. ::recv(sock, &c, 1, 0) == 1) {
  24289. res += c;
  24290. }
  24291. }
  24292. if (res.find(" 101 ") == std::string::npos) {
  24293. detail::close_socket(sock);
  24294. return INVALID_SOCKET;
  24295. }
  24296. return sock;
  24297. }
  24298. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24299. // The payload must fit the 7-bit length field.
  24300. static std::string masked_frame(uint8_t first_byte,
  24301. const std::string &payload) {
  24302. std::string f;
  24303. f += static_cast<char>(first_byte);
  24304. f += static_cast<char>(0x80 | payload.size());
  24305. f.append(4, '\0');
  24306. return f + payload;
  24307. }
  24308. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24309. std::atomic<bool> done{false};
  24310. std::string received;
  24311. Server svr;
  24312. svr.set_websocket_ping_interval(0);
  24313. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24314. std::string msg;
  24315. if (ws.read(msg) == ws::Binary) { received = msg; }
  24316. done = true;
  24317. });
  24318. auto port = svr.bind_to_any_port("127.0.0.1");
  24319. std::thread t([&]() { svr.listen_after_bind(); });
  24320. auto se = detail::scope_exit([&] {
  24321. svr.stop();
  24322. t.join();
  24323. });
  24324. svr.wait_until_ready();
  24325. auto sock = connect_raw_websocket(port, "/ws");
  24326. ASSERT_NE(INVALID_SOCKET, sock);
  24327. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24328. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24329. masked_frame(0x89, "p") + // FIN + Ping
  24330. masked_frame(0x80, "lo"); // FIN + Continuation
  24331. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24332. for (int i = 0; i < 500 && !done; i++) {
  24333. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24334. }
  24335. ASSERT_TRUE(done);
  24336. EXPECT_EQ("Hello", received);
  24337. // The Ping between the fragments is answered with a Pong.
  24338. char pong[3];
  24339. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24340. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24341. }
  24342. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24343. Server svr;
  24344. svr.set_websocket_ping_interval(-1);
  24345. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24346. std::string msg;
  24347. while (ws.read(msg)) {}
  24348. });
  24349. auto port = svr.bind_to_any_port("127.0.0.1");
  24350. std::thread t([&]() { svr.listen_after_bind(); });
  24351. auto se = detail::scope_exit([&] {
  24352. svr.stop();
  24353. t.join();
  24354. });
  24355. svr.wait_until_ready();
  24356. auto sock = connect_raw_websocket(port, "/ws");
  24357. ASSERT_NE(INVALID_SOCKET, sock);
  24358. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24359. // Nothing comes while the client stays quiet.
  24360. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24361. char c;
  24362. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24363. }
  24364. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24365. // and that has to end a read() already waiting on the peer, on every platform.
  24366. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24367. // The peer sends no pings, and its handler never calls read(), which is
  24368. // where pongs are written.
  24369. std::mutex mutex;
  24370. std::condition_variable cv;
  24371. auto release = false;
  24372. svr.set_websocket_ping_interval(0);
  24373. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24374. std::unique_lock<std::mutex> lock(mutex);
  24375. cv.wait(lock, [&] { return release; });
  24376. });
  24377. auto port = svr.bind_to_any_port(HOST);
  24378. std::thread t([&]() { svr.listen_after_bind(); });
  24379. auto se = detail::scope_exit([&] {
  24380. {
  24381. std::lock_guard<std::mutex> lock(mutex);
  24382. release = true;
  24383. }
  24384. cv.notify_all();
  24385. svr.stop();
  24386. t.join();
  24387. });
  24388. svr.wait_until_ready();
  24389. ws::WebSocketClient client(std::string(scheme) +
  24390. "://localhost:" + std::to_string(port) + "/ws");
  24391. #ifdef CPPHTTPLIB_SSL_ENABLED
  24392. client.enable_server_certificate_verification(false);
  24393. #endif
  24394. // A ping a second, given up on after two go unanswered: about 3s
  24395. client.set_websocket_ping_interval(1);
  24396. client.set_websocket_max_missed_pongs(2);
  24397. // Well past that, so that a read the timeout ends instead stands out
  24398. client.set_read_timeout(10);
  24399. ASSERT_TRUE(client.connect());
  24400. auto start = std::chrono::steady_clock::now();
  24401. std::string msg;
  24402. EXPECT_EQ(ws::Fail, client.read(msg));
  24403. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24404. std::chrono::steady_clock::now() - start)
  24405. .count(),
  24406. 6000);
  24407. EXPECT_FALSE(client.is_open());
  24408. }
  24409. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24410. Server svr;
  24411. check_pong_timeout_ends_read(svr, "ws");
  24412. }
  24413. #ifdef CPPHTTPLIB_SSL_ENABLED
  24414. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24416. ASSERT_TRUE(svr.is_valid());
  24417. check_pong_timeout_ends_read(svr, "wss");
  24418. }
  24419. #endif
  24420. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24421. Server svr;
  24422. svr.set_websocket_ping_interval(0);
  24423. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24424. std::string msg;
  24425. while (ws.read(msg)) {}
  24426. });
  24427. auto port = svr.bind_to_any_port("127.0.0.1");
  24428. std::thread t([&]() { svr.listen_after_bind(); });
  24429. auto se = detail::scope_exit([&] {
  24430. svr.stop();
  24431. t.join();
  24432. });
  24433. svr.wait_until_ready();
  24434. // Each Close payload and the reply it should get: an echo when valid, 1002
  24435. // otherwise.
  24436. std::vector<std::pair<std::string, std::string>> cases = {
  24437. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24438. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24439. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24440. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24441. };
  24442. // Also between the fragments of a message.
  24443. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24444. for (const auto &c : cases) {
  24445. auto sock = connect_raw_websocket(port, "/ws");
  24446. ASSERT_NE(INVALID_SOCKET, sock);
  24447. auto frames = prefix + masked_frame(0x88, c.first);
  24448. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24449. std::string reply;
  24450. char buf[256];
  24451. while (reply.size() < 2 + c.second.size()) {
  24452. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24453. if (n <= 0) { break; }
  24454. reply.append(buf, static_cast<size_t>(n));
  24455. }
  24456. detail::close_socket(sock);
  24457. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24458. c.second,
  24459. reply);
  24460. }
  24461. }
  24462. }
  24463. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24464. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24465. protected:
  24466. void SetUp() override {
  24467. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24468. SERVER_PRIVATE_KEY_FILE);
  24469. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24470. std::string msg;
  24471. ws::ReadResult ret;
  24472. while ((ret = ws.read(msg))) {
  24473. if (ret == ws::Binary) {
  24474. ws.send(msg.data(), msg.size());
  24475. } else {
  24476. ws.send(msg);
  24477. }
  24478. }
  24479. });
  24480. port_ = server_->bind_to_any_port(HOST);
  24481. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24482. server_->wait_until_ready();
  24483. }
  24484. void TearDown() override {
  24485. server_->stop();
  24486. if (server_thread_.joinable()) { server_thread_.join(); }
  24487. }
  24488. std::unique_ptr<SSLServer> server_;
  24489. std::thread server_thread_;
  24490. int port_ = 0;
  24491. };
  24492. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24493. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24494. {
  24495. ws::WebSocketClient client(url);
  24496. client.enable_server_certificate_verification(false);
  24497. auto calls = 0;
  24498. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24499. calls++;
  24500. return false;
  24501. });
  24502. EXPECT_FALSE(client.connect());
  24503. EXPECT_GT(calls, 0);
  24504. }
  24505. {
  24506. ws::WebSocketClient client(url);
  24507. client.enable_server_certificate_verification(false);
  24508. client.set_session_verifier([](tls::session_t) {
  24509. return SSLVerifierResponse::CertificateRejected;
  24510. });
  24511. EXPECT_FALSE(client.connect());
  24512. }
  24513. {
  24514. ws::WebSocketClient client(url);
  24515. client.enable_server_certificate_verification(false);
  24516. client.set_session_verifier([](tls::session_t) {
  24517. return SSLVerifierResponse::CertificateAccepted;
  24518. });
  24519. EXPECT_TRUE(client.connect());
  24520. }
  24521. }
  24522. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24523. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24524. "/ws-echo");
  24525. client.enable_server_certificate_verification(false);
  24526. ASSERT_TRUE(client.connect());
  24527. ASSERT_TRUE(client.is_open());
  24528. ASSERT_TRUE(client.send("Hello WSS"));
  24529. std::string msg;
  24530. EXPECT_EQ(ws::Text, client.read(msg));
  24531. EXPECT_EQ("Hello WSS", msg);
  24532. client.close();
  24533. }
  24534. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24535. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24536. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24537. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24538. // client (without calling close() first) is the only path that runs
  24539. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24540. // bug exactly.
  24541. //
  24542. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24543. // when linked against an instrumented libssl; run under Valgrind to catch it
  24544. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24545. // suite (the freed session otherwise stalls on the close handshake) — this test
  24546. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24547. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24548. {
  24549. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24550. "/ws-echo");
  24551. client.enable_server_certificate_verification(false);
  24552. client.set_read_timeout(2, 0);
  24553. client.set_write_timeout(2, 0);
  24554. ASSERT_TRUE(client.connect());
  24555. ASSERT_TRUE(client.is_open());
  24556. ASSERT_TRUE(client.send("still open"));
  24557. // Intentionally do NOT call client.close(): leaving scope runs
  24558. // shutdown_and_close() with the WebSocket still open, which must send the
  24559. // close frame while the TLS session is still alive.
  24560. }
  24561. }
  24562. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24563. // shutdown_and_close() at the start of connect(), reproducing the same
  24564. // use-after-free within the test body rather than at scope exit. The second
  24565. // connect must succeed and echo, proving the close handshake ran over a live
  24566. // session. See the note above about memory-tool requirements.
  24567. TEST_F(WebSocketSSLIntegrationTest,
  24568. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24569. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24570. "/ws-echo");
  24571. client.enable_server_certificate_verification(false);
  24572. client.set_read_timeout(2, 0);
  24573. client.set_write_timeout(2, 0);
  24574. ASSERT_TRUE(client.connect());
  24575. ASSERT_TRUE(client.is_open());
  24576. ASSERT_TRUE(client.send("still open"));
  24577. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24578. // the still-open connection, which must not touch a freed TLS session.
  24579. ASSERT_TRUE(client.connect());
  24580. ASSERT_TRUE(client.is_open());
  24581. ASSERT_TRUE(client.send("after reconnect"));
  24582. std::string msg;
  24583. EXPECT_EQ(ws::Text, client.read(msg));
  24584. EXPECT_EQ("after reconnect", msg);
  24585. client.close();
  24586. }
  24587. #endif
  24588. #ifdef CPPHTTPLIB_SSL_ENABLED
  24589. class WebSocketSSLCATest : public ::testing::Test {
  24590. protected:
  24591. void SetUp() override {
  24592. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24593. SERVER_PRIVATE_KEY_FILE);
  24594. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24595. std::string msg;
  24596. while (ws.read(msg)) {
  24597. ws.send(msg);
  24598. }
  24599. });
  24600. port_ = server_->bind_to_any_port("127.0.0.1");
  24601. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24602. server_->wait_until_ready();
  24603. }
  24604. void TearDown() override {
  24605. server_->stop();
  24606. if (server_thread_.joinable()) { server_thread_.join(); }
  24607. }
  24608. std::string url() const {
  24609. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24610. }
  24611. std::unique_ptr<SSLServer> server_;
  24612. std::thread server_thread_;
  24613. int port_ = 0;
  24614. };
  24615. // A custom CA loaded as PEM verifies the server with full certificate
  24616. // verification enabled
  24617. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24618. ws::WebSocketClient client(url());
  24619. std::string cert;
  24620. read_file(SERVER_CERT2_FILE, cert);
  24621. client.load_ca_cert_store(cert.c_str(), cert.size());
  24622. ASSERT_TRUE(client.connect());
  24623. ASSERT_TRUE(client.send("hello"));
  24624. std::string msg;
  24625. EXPECT_EQ(ws::Text, client.read(msg));
  24626. EXPECT_EQ("hello", msg);
  24627. client.close();
  24628. }
  24629. // A custom CA that does not cover the server must fail verification (the
  24630. // custom CA is exclusive; system certs are not loaded alongside it)
  24631. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24632. ws::WebSocketClient client(url());
  24633. std::string cert;
  24634. read_file(CLIENT_CA_CERT_FILE, cert);
  24635. client.load_ca_cert_store(cert.c_str(), cert.size());
  24636. auto res = client.connect();
  24637. ASSERT_FALSE(res);
  24638. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24639. EXPECT_EQ(-1, res.status());
  24640. EXPECT_NE(0u, res.ssl_backend_error());
  24641. }
  24642. // The same CA as a file path rather than PEM in memory
  24643. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24644. ws::WebSocketClient client(url());
  24645. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24646. ASSERT_TRUE(client.connect());
  24647. ASSERT_TRUE(client.send("hello"));
  24648. std::string msg;
  24649. EXPECT_EQ(ws::Text, client.read(msg));
  24650. EXPECT_EQ("hello", msg);
  24651. client.close();
  24652. }
  24653. // ...and a CA file that does not cover the server still fails, so it is the
  24654. // path above that decides the outcome
  24655. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24656. ws::WebSocketClient client(url());
  24657. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24658. ASSERT_FALSE(client.connect());
  24659. }
  24660. // Regression test: reconnecting with a native custom CA store used to reuse
  24661. // a store handle the previous TLS context had already freed (use-after-free
  24662. // under the OpenSSL backend). The context now lives as long as the client.
  24663. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24664. ws::WebSocketClient client(url());
  24665. std::string cert;
  24666. read_file(SERVER_CERT2_FILE, cert);
  24667. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24668. ASSERT_TRUE(client.connect());
  24669. client.close();
  24670. ASSERT_TRUE(client.connect());
  24671. ASSERT_TRUE(client.send("again"));
  24672. std::string msg;
  24673. EXPECT_EQ(ws::Text, client.read(msg));
  24674. EXPECT_EQ("again", msg);
  24675. client.close();
  24676. }
  24677. // Regression test: a certificate with a trusted chain but no identity match
  24678. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24679. // verification entirely for IP hosts, so this connection succeeded there.
  24680. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24681. // chain verification while the identity check must still fail.
  24682. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24684. ASSERT_TRUE(svr.is_valid());
  24685. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24686. std::string msg;
  24687. while (ws.read(msg)) {
  24688. ws.send(msg);
  24689. }
  24690. });
  24691. auto port = svr.bind_to_any_port("127.0.0.1");
  24692. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24693. auto se = detail::scope_exit([&] {
  24694. svr.stop();
  24695. t.join();
  24696. });
  24697. svr.wait_until_ready();
  24698. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24699. "/echo");
  24700. std::string cert;
  24701. read_file(SERVER_CERT_FILE, cert);
  24702. client.load_ca_cert_store(cert.c_str(), cert.size());
  24703. ASSERT_FALSE(client.connect());
  24704. }
  24705. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24706. // SNI, so nothing binds the host name to the TLS session. These bind the
  24707. // server to "localhost" instead, the only shape that exercises the SNI and
  24708. // hostname-verification path with certificate verification left enabled.
  24709. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24710. protected:
  24711. void Start(const char *cert_file) {
  24712. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24713. SERVER_PRIVATE_KEY_FILE);
  24714. ASSERT_TRUE(server_->is_valid());
  24715. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24716. std::string msg;
  24717. while (ws.read(msg)) {
  24718. ws.send(msg);
  24719. }
  24720. });
  24721. port_ = server_->bind_to_any_port("localhost");
  24722. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24723. server_->wait_until_ready();
  24724. }
  24725. void TearDown() override {
  24726. if (server_) { server_->stop(); }
  24727. if (server_thread_.joinable()) { server_thread_.join(); }
  24728. }
  24729. std::string url() const {
  24730. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24731. }
  24732. std::unique_ptr<SSLServer> server_;
  24733. std::thread server_thread_;
  24734. int port_ = 0;
  24735. };
  24736. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24737. // out and the connection is usable
  24738. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24739. Start(SERVER_CERT2_FILE);
  24740. ws::WebSocketClient client(url());
  24741. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24742. ASSERT_TRUE(client.connect());
  24743. ASSERT_TRUE(client.send("hello"));
  24744. std::string msg;
  24745. EXPECT_EQ(ws::Text, client.read(msg));
  24746. EXPECT_EQ("hello", msg);
  24747. client.close();
  24748. }
  24749. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24750. // while the identity check must still reject "localhost"
  24751. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24752. Start(SERVER_CERT_FILE);
  24753. ws::WebSocketClient client(url());
  24754. client.set_ca_cert_path(SERVER_CERT_FILE);
  24755. auto res = client.connect();
  24756. ASSERT_FALSE(res);
  24757. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24758. EXPECT_EQ(-1, res.status());
  24759. }
  24760. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24761. // disabled: the chain is still checked, only the identity check is skipped
  24762. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24763. Start(SERVER_CERT_FILE);
  24764. ws::WebSocketClient client(url());
  24765. client.set_ca_cert_path(SERVER_CERT_FILE);
  24766. client.enable_server_hostname_verification(false);
  24767. ASSERT_TRUE(client.connect());
  24768. ASSERT_TRUE(client.send("hello"));
  24769. std::string msg;
  24770. EXPECT_EQ(ws::Text, client.read(msg));
  24771. EXPECT_EQ("hello", msg);
  24772. client.close();
  24773. }
  24774. // A CA that did not sign the server certificate fails the chain, even though
  24775. // the name would match
  24776. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24777. Start(SERVER_CERT2_FILE);
  24778. ws::WebSocketClient client(url());
  24779. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24780. ASSERT_FALSE(client.connect());
  24781. }
  24782. // With verification disabled, neither the chain nor the name is checked
  24783. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24784. Start(SERVER_CERT_FILE);
  24785. ws::WebSocketClient client(url());
  24786. client.enable_server_certificate_verification(false);
  24787. ASSERT_TRUE(client.connect());
  24788. ASSERT_TRUE(client.send("hello"));
  24789. std::string msg;
  24790. EXPECT_EQ(ws::Text, client.read(msg));
  24791. EXPECT_EQ("hello", msg);
  24792. client.close();
  24793. }
  24794. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24795. protected:
  24796. void SetUp() override {
  24797. server_ = httplib::detail::make_unique<SSLServer>(
  24798. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24799. ASSERT_TRUE(server_->is_valid());
  24800. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24801. std::string msg;
  24802. while (ws.read(msg)) {
  24803. ws.send(msg);
  24804. }
  24805. });
  24806. port_ = server_->bind_to_any_port("localhost");
  24807. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24808. server_->wait_until_ready();
  24809. }
  24810. void TearDown() override {
  24811. server_->stop();
  24812. if (server_thread_.joinable()) { server_thread_.join(); }
  24813. }
  24814. std::string url() const {
  24815. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24816. }
  24817. void ConnectWithClientCert(const std::string &client_cert_file,
  24818. const std::string &client_private_key_file,
  24819. const char *private_key_password) {
  24820. std::string cert_pem, key_pem;
  24821. read_file(client_cert_file, cert_pem);
  24822. read_file(client_private_key_file, key_pem);
  24823. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24824. key_pem.c_str(), key_pem.size(),
  24825. private_key_password};
  24826. ConnectWithPem(pem);
  24827. }
  24828. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24829. ws::WebSocketClient client(url(), pem);
  24830. ASSERT_TRUE(client.is_valid());
  24831. client.enable_server_certificate_verification(false);
  24832. ASSERT_TRUE(client.connect());
  24833. ASSERT_TRUE(client.send("hello"));
  24834. std::string msg;
  24835. EXPECT_EQ(ws::Text, client.read(msg));
  24836. EXPECT_EQ("hello", msg);
  24837. client.close();
  24838. }
  24839. std::unique_ptr<SSLServer> server_;
  24840. std::thread server_thread_;
  24841. int port_ = 0;
  24842. };
  24843. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24844. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24845. }
  24846. // Control for the tests above: the fixture's server really does require a
  24847. // client certificate, so it is the PEM the constructor installed that decides
  24848. // the outcome.
  24849. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24850. ws::WebSocketClient client(url());
  24851. ASSERT_TRUE(client.is_valid());
  24852. client.enable_server_certificate_verification(false);
  24853. EXPECT_FALSE(client.connect());
  24854. }
  24855. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24856. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24857. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24858. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24859. }
  24860. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24861. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24862. std::string cert_pem, key_pem;
  24863. read_file(CLIENT_CERT_FILE, cert_pem);
  24864. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24865. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24866. std::vector<char> key(key_pem.begin(), key_pem.end());
  24867. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24868. key.size(), nullptr};
  24869. ConnectWithPem(pem);
  24870. }
  24871. #endif
  24872. #if !defined(_WIN32)
  24873. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24874. auto secret_dir = std::string("./symlink_test_secret");
  24875. auto served_dir = std::string("./symlink_test_served");
  24876. auto secret_file = secret_dir + "/secret.txt";
  24877. auto symlink_path = served_dir + "/escape";
  24878. // Setup: create directories and files
  24879. mkdir(secret_dir.c_str(), 0755);
  24880. mkdir(served_dir.c_str(), 0755);
  24881. {
  24882. std::ofstream ofs(secret_file);
  24883. ofs << "SECRET_DATA";
  24884. }
  24885. // Create symlink using absolute path so it resolves correctly
  24886. #ifdef PATH_MAX
  24887. char abs_secret[PATH_MAX];
  24888. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24889. #else
  24890. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24891. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24892. ASSERT_NE(nullptr, abs_secret);
  24893. #endif
  24894. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24895. auto se = detail::scope_exit([&] {
  24896. unlink(symlink_path.c_str());
  24897. unlink(secret_file.c_str());
  24898. rmdir(served_dir.c_str());
  24899. rmdir(secret_dir.c_str());
  24900. });
  24901. Server svr;
  24902. svr.set_mount_point("/", served_dir);
  24903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24904. auto se2 = detail::scope_exit([&] {
  24905. svr.stop();
  24906. listen_thread.join();
  24907. });
  24908. svr.wait_until_ready();
  24909. Client cli("localhost", PORT);
  24910. // Symlink pointing outside base dir should be blocked
  24911. auto res = cli.Get("/escape/secret.txt");
  24912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24913. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24914. }
  24915. #endif
  24916. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24917. // "GET /smuggled" request), reads the first response, and only then sends the
  24918. // embedded request as the body. Returns how many times /smuggled ran.
  24919. //
  24920. // The body is sent AFTER receiving the first response (as in the original
  24921. // PoC) so that the stream_line_reader cannot buffer it together with the
  24922. // headers of the first request.
  24923. static int count_smuggled_requests(const std::string &outer_head,
  24924. std::string &first_response) {
  24925. Server svr;
  24926. svr.set_mount_point("/", "./www");
  24927. std::atomic<int> smuggled_count(0);
  24928. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24929. smuggled_count++;
  24930. res.set_content("oops", "text/plain");
  24931. });
  24932. svr.Post("/post", [&](const Request &req, Response &res) {
  24933. res.set_content(req.body, "text/plain");
  24934. });
  24935. auto port = svr.bind_to_any_port("localhost");
  24936. thread t = thread([&] { svr.listen_after_bind(); });
  24937. auto se = detail::scope_exit([&] {
  24938. svr.stop();
  24939. t.join();
  24940. });
  24941. svr.wait_until_ready();
  24942. auto error = Error::Success;
  24943. auto sock = detail::create_client_socket(
  24944. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24945. /*connection_timeout_sec=*/2, 0,
  24946. /*read_timeout_sec=*/2, 0,
  24947. /*write_timeout_sec=*/2, 0, std::string(), error);
  24948. EXPECT_NE(INVALID_SOCKET, sock);
  24949. if (sock == INVALID_SOCKET) { return -1; }
  24950. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24951. // The "smuggled" request will be sent as the body of the outer request
  24952. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24953. "Host: localhost\r\n"
  24954. "Connection: close\r\n"
  24955. "\r\n";
  24956. auto head = outer_head;
  24957. auto len = std::to_string(smuggled.size());
  24958. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24959. pos = head.find("{len}", pos + len.size())) {
  24960. head.replace(pos, 5, len);
  24961. }
  24962. // Step 1: Send only the outer request headers (no body yet)
  24963. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24964. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24965. // Step 2: Read the first response
  24966. char buf[4096];
  24967. for (;;) {
  24968. auto n = recv(sock, buf, sizeof(buf), 0);
  24969. if (n <= 0) break;
  24970. first_response.append(buf, static_cast<size_t>(n));
  24971. // Stop once we have a complete response (headers + body)
  24972. auto hdr_end = first_response.find("\r\n\r\n");
  24973. if (hdr_end != std::string::npos) {
  24974. // Check for Content-Length to know when the body is complete
  24975. auto cl_pos = first_response.find("Content-Length:");
  24976. if (cl_pos != std::string::npos) {
  24977. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24978. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24979. auto cl = std::stoul(
  24980. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24981. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24982. } else {
  24983. break; // No Content-Length, assume headers-only response
  24984. }
  24985. }
  24986. }
  24987. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24988. // vulnerable server the keep-alive loop reads this as a second request. The
  24989. // server may already have closed the connection, so the result is ignored.
  24990. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  24991. // Half-close so that a server which drained the body sees EOF and closes,
  24992. // instead of the read below waiting for the read timeout.
  24993. #ifdef _WIN32
  24994. ::shutdown(sock, SD_SEND);
  24995. #else
  24996. ::shutdown(sock, SHUT_WR);
  24997. #endif
  24998. // Step 4: Read until the server closes the connection
  24999. for (;;) {
  25000. auto n = recv(sock, buf, sizeof(buf), 0);
  25001. if (n <= 0) break;
  25002. }
  25003. return smuggled_count.load();
  25004. }
  25005. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25006. // A GET request with Content-Length to a static file handler must have its
  25007. // body drained before the keep-alive connection is reused. Otherwise the
  25008. // unread body bytes are interpreted as the next HTTP request.
  25009. std::string first_response;
  25010. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25011. "Host: localhost\r\n"
  25012. "Content-Length: {len}\r\n"
  25013. "\r\n",
  25014. first_response));
  25015. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25016. }
  25017. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25018. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25019. // be answered with 400 and the connection closed. Treating it as "no body"
  25020. // leaves the body to be parsed as the next request.
  25021. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25022. const char *targets[] = {
  25023. "GET /file", // handler that never reads the body
  25024. "GET /not-found", // no handler matches (404)
  25025. "POST /post", // handler that reads the body
  25026. };
  25027. for (auto target : targets) {
  25028. for (auto value : values) {
  25029. std::string first_response;
  25030. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25031. " HTTP/1.1\r\n"
  25032. "Host: localhost\r\n"
  25033. "Content-Length: " +
  25034. value + "\r\n\r\n",
  25035. first_response))
  25036. << target << " with Content-Length: " << value;
  25037. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25038. << target << " with Content-Length: " << value;
  25039. }
  25040. }
  25041. }
  25042. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25043. // A 400 for an unparseable request line leaves the rest of the message
  25044. // unread, so the connection must be closed rather than reused.
  25045. std::string first_response;
  25046. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25047. "Host: localhost\r\n"
  25048. "Content-Length: {len}\r\n"
  25049. "\r\n",
  25050. first_response));
  25051. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25052. }
  25053. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25054. // Same as above for a header block that fails to parse.
  25055. std::string first_response;
  25056. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25057. "Host: localhost\r\n"
  25058. "Bad Header\r\n"
  25059. "Content-Length: {len}\r\n"
  25060. "\r\n",
  25061. first_response));
  25062. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25063. }
  25064. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25065. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25066. // server must not read another request on that connection, even when the
  25067. // request had no body to drain.
  25068. std::string first_response;
  25069. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25070. "Host: localhost\r\n"
  25071. "\r\n",
  25072. first_response));
  25073. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25074. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25075. }
  25076. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25077. // A content reader that stops early leaves the stream inside the body.
  25078. // Draining the whole Content-Length from there, or reading the body again,
  25079. // reads into the next request, and whatever follows is parsed as a request
  25080. // of its own.
  25081. Server svr;
  25082. std::atomic<int> smuggled_count(0);
  25083. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25084. svr.Post("/upload", [](const Request &req, Response &res,
  25085. const ContentReader &content_reader) {
  25086. // Stop at the last chunk, so the whole body has been read however it
  25087. // arrives.
  25088. auto length = req.get_header_value_u64("Content-Length");
  25089. size_t total = 0;
  25090. auto consumed = content_reader([&](const char *, size_t n) {
  25091. total += n;
  25092. return total < length;
  25093. });
  25094. EXPECT_FALSE(consumed);
  25095. if (req.has_param("retry")) {
  25096. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25097. }
  25098. // Replace the 400 the aborted read set, which would close the connection.
  25099. res.set_redirect("/done");
  25100. });
  25101. auto port = svr.bind_to_any_port(HOST);
  25102. thread t = thread([&] { svr.listen_after_bind(); });
  25103. auto se = detail::scope_exit([&] {
  25104. svr.stop();
  25105. t.join();
  25106. });
  25107. svr.wait_until_ready();
  25108. // A front end sees the second request as a POST whose body is the GET. The
  25109. // first body is as long as the POST's headers, so draining it again reads
  25110. // exactly those and leaves the GET to be parsed next.
  25111. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25112. "Host: localhost\r\n"
  25113. "\r\n";
  25114. std::string second_head = "POST /post HTTP/1.1\r\n"
  25115. "Host: localhost\r\n"
  25116. "Content-Length: " +
  25117. std::to_string(inner.size()) +
  25118. "\r\n"
  25119. "\r\n";
  25120. for (auto target : {"/upload", "/upload?retry"}) {
  25121. smuggled_count = 0;
  25122. std::string request = "POST " + std::string(target) +
  25123. " HTTP/1.1\r\n"
  25124. "Host: localhost\r\n"
  25125. "Content-Length: " +
  25126. std::to_string(second_head.size()) +
  25127. "\r\n"
  25128. "\r\n" +
  25129. std::string(second_head.size(), 'A') + second_head +
  25130. inner;
  25131. std::string response;
  25132. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25133. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25134. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25135. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25136. EXPECT_EQ(0, smuggled_count.load()) << target;
  25137. }
  25138. }
  25139. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25140. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25141. // must be rejected with 400 Bad Request.
  25142. Server svr;
  25143. svr.Post("/test", [&](const Request &, Response &res) {
  25144. res.set_content("ok", "text/plain");
  25145. });
  25146. thread t = thread([&] { svr.listen(HOST, PORT); });
  25147. auto se = detail::scope_exit([&] {
  25148. svr.stop();
  25149. t.join();
  25150. ASSERT_FALSE(svr.is_running());
  25151. });
  25152. svr.wait_until_ready();
  25153. // Exact "chunked"
  25154. {
  25155. auto req = "POST /test HTTP/1.1\r\n"
  25156. "Host: localhost\r\n"
  25157. "Content-Length: 5\r\n"
  25158. "Transfer-Encoding: chunked\r\n"
  25159. "Connection: close\r\n"
  25160. "\r\n"
  25161. "hello";
  25162. std::string response;
  25163. ASSERT_TRUE(send_request(1, req, &response));
  25164. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25165. response.substr(0, response.find("\r\n")));
  25166. }
  25167. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25168. {
  25169. auto req = "POST /test HTTP/1.1\r\n"
  25170. "Host: localhost\r\n"
  25171. "Content-Length: 5\r\n"
  25172. "Transfer-Encoding: gzip, chunked\r\n"
  25173. "Connection: close\r\n"
  25174. "\r\n"
  25175. "hello";
  25176. std::string response;
  25177. ASSERT_TRUE(send_request(1, req, &response));
  25178. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25179. response.substr(0, response.find("\r\n")));
  25180. }
  25181. }
  25182. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25183. Server svr;
  25184. svr.Post("/test", [&](const Request &, Response &res) {
  25185. res.set_content("ok", "text/plain");
  25186. });
  25187. thread t = thread([&] { svr.listen(HOST, PORT); });
  25188. auto se = detail::scope_exit([&] {
  25189. svr.stop();
  25190. t.join();
  25191. ASSERT_FALSE(svr.is_running());
  25192. });
  25193. svr.wait_until_ready();
  25194. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25195. // length cannot be determined, so the server must answer 400 and close
  25196. // rather than treat the request as bodyless and leave the body in the
  25197. // socket for the next request to pick up.
  25198. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25199. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25200. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25201. std::string response;
  25202. ASSERT_TRUE(send_request(1, req, &response));
  25203. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25204. response.substr(0, response.find("\r\n")))
  25205. << transfer_encoding;
  25206. }
  25207. // RFC 9110 5.3: the codings may also be split across several
  25208. // Transfer-Encoding lines, which combine in the order they were received.
  25209. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25210. // just like the single-line "chunked, gzip" above.
  25211. {
  25212. auto req = "POST /test HTTP/1.1\r\n"
  25213. "Host: localhost\r\n"
  25214. "Transfer-Encoding: chunked\r\n"
  25215. "Transfer-Encoding: gzip\r\n"
  25216. "\r\n"
  25217. "0\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. }
  25223. // A sequence ending in chunked stays valid.
  25224. auto req = "POST /test HTTP/1.1\r\n"
  25225. "Host: localhost\r\n"
  25226. "Transfer-Encoding: gzip, chunked\r\n"
  25227. "Connection: close\r\n"
  25228. "\r\n"
  25229. "0\r\n\r\n";
  25230. std::string response;
  25231. ASSERT_TRUE(send_request(1, req, &response));
  25232. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25233. // ...including when it is spread over several lines.
  25234. auto split_req = "POST /test HTTP/1.1\r\n"
  25235. "Host: localhost\r\n"
  25236. "Transfer-Encoding: gzip\r\n"
  25237. "Transfer-Encoding: chunked\r\n"
  25238. "Connection: close\r\n"
  25239. "\r\n"
  25240. "0\r\n\r\n";
  25241. std::string split_response;
  25242. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25243. EXPECT_EQ("HTTP/1.1 200 OK",
  25244. split_response.substr(0, split_response.find("\r\n")));
  25245. }
  25246. // Regression for issue #2450: a DELETE without Content-Length on a
  25247. // keep-alive connection must not let the post-response drain consume the
  25248. // next request's bytes.
  25249. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25250. Server svr;
  25251. std::atomic<int> delete_count(0);
  25252. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25253. delete_count++;
  25254. res.status = StatusCode::NoContent_204;
  25255. });
  25256. auto port = svr.bind_to_any_port(HOST);
  25257. thread t = thread([&] { svr.listen_after_bind(); });
  25258. auto se = detail::scope_exit([&] {
  25259. svr.stop();
  25260. t.join();
  25261. });
  25262. svr.wait_until_ready();
  25263. auto error = Error::Success;
  25264. auto sock = detail::create_client_socket(
  25265. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25266. /*connection_timeout_sec=*/2, 0,
  25267. /*read_timeout_sec=*/2, 0,
  25268. /*write_timeout_sec=*/2, 0, std::string(), error);
  25269. ASSERT_NE(INVALID_SOCKET, sock);
  25270. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25271. auto send_request_and_read_response = [&](const std::string &req,
  25272. std::string &out) -> bool {
  25273. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25274. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25275. char buf[4096];
  25276. for (;;) {
  25277. auto n = recv(sock, buf, sizeof(buf), 0);
  25278. if (n <= 0) { return !out.empty(); }
  25279. out.append(buf, static_cast<size_t>(n));
  25280. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25281. }
  25282. };
  25283. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25284. "Host: localhost\r\n"
  25285. "\r\n";
  25286. std::string resp1;
  25287. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25288. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25289. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25290. "Host: localhost\r\n"
  25291. "Connection: close\r\n"
  25292. "\r\n";
  25293. std::string resp2;
  25294. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25295. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25296. EXPECT_EQ(2, delete_count.load());
  25297. }
  25298. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25299. Server svr;
  25300. svr.Post("/ingest", [&](const Request &, Response &res,
  25301. const ContentReader &content_reader) {
  25302. auto consumed = content_reader([](const char *, size_t) { return false; });
  25303. EXPECT_FALSE(consumed);
  25304. res.status = StatusCode::Conflict_409;
  25305. res.set_header("Connection", "close");
  25306. });
  25307. auto port = svr.bind_to_any_port(HOST);
  25308. thread t = thread([&] { svr.listen_after_bind(); });
  25309. auto se = detail::scope_exit([&] {
  25310. svr.stop();
  25311. t.join();
  25312. });
  25313. svr.wait_until_ready();
  25314. auto error = Error::Success;
  25315. auto sock = detail::create_client_socket(
  25316. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25317. /*connection_timeout_sec=*/2, 0,
  25318. /*read_timeout_sec=*/1, 0,
  25319. /*write_timeout_sec=*/2, 0, std::string(), error);
  25320. ASSERT_NE(INVALID_SOCKET, sock);
  25321. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25322. std::string request = "POST /ingest HTTP/1.1\r\n"
  25323. "Host: localhost\r\n"
  25324. "Transfer-Encoding: chunked\r\n"
  25325. "\r\n"
  25326. "4\r\n"
  25327. "data\r\n";
  25328. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25329. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25330. std::string response;
  25331. ssize_t received = 0;
  25332. do {
  25333. char buf[4096];
  25334. received = recv(sock, buf, sizeof(buf), 0);
  25335. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25336. } while (received > 0);
  25337. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25338. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25339. EXPECT_EQ(0, received);
  25340. }
  25341. namespace no_proxy_test {
  25342. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25343. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25344. // calling listen().
  25345. class ScopedServer {
  25346. public:
  25347. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25348. ~ScopedServer() {
  25349. svr_.stop();
  25350. if (th_.joinable()) { th_.join(); }
  25351. }
  25352. Server &svr() { return svr_; }
  25353. int port() const { return port_; }
  25354. void listen() {
  25355. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25356. svr_.wait_until_ready();
  25357. }
  25358. private:
  25359. Server svr_;
  25360. std::thread th_;
  25361. int port_ = 0;
  25362. };
  25363. class ProxyAndTargetServers {
  25364. public:
  25365. ProxyAndTargetServers() {
  25366. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25367. proxy_hits_++;
  25368. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25369. res.set_content("via-proxy", "text/plain");
  25370. });
  25371. target_.Get(".*", [this](const Request &req, Response &res) {
  25372. target_hits_++;
  25373. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25374. res.set_content("direct", "text/plain");
  25375. });
  25376. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25377. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25378. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25379. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25380. proxy_mock_.wait_until_ready();
  25381. target_.wait_until_ready();
  25382. }
  25383. ~ProxyAndTargetServers() {
  25384. proxy_mock_.stop();
  25385. target_.stop();
  25386. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25387. if (target_thread_.joinable()) { target_thread_.join(); }
  25388. }
  25389. Server &proxy_mock() { return proxy_mock_; }
  25390. Server &target() { return target_; }
  25391. int proxy_port() const { return proxy_port_; }
  25392. int target_port() const { return target_port_; }
  25393. int proxy_hits() const { return proxy_hits_.load(); }
  25394. int target_hits() const { return target_hits_.load(); }
  25395. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25396. void reset_counters() {
  25397. proxy_hits_ = 0;
  25398. target_hits_ = 0;
  25399. last_had_proxy_authz_ = false;
  25400. }
  25401. private:
  25402. Server proxy_mock_;
  25403. Server target_;
  25404. std::thread proxy_thread_;
  25405. std::thread target_thread_;
  25406. int proxy_port_ = 0;
  25407. int target_port_ = 0;
  25408. std::atomic<int> proxy_hits_{0};
  25409. std::atomic<int> target_hits_{0};
  25410. std::atomic<bool> last_had_proxy_authz_{false};
  25411. };
  25412. inline std::unique_ptr<Client> make_client(const std::string &host,
  25413. ProxyAndTargetServers &s) {
  25414. auto cli = detail::make_unique<Client>(host, s.target_port());
  25415. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25416. cli->set_proxy("127.0.0.1", s.proxy_port());
  25417. return cli;
  25418. }
  25419. } // namespace no_proxy_test
  25420. using no_proxy_test::make_client;
  25421. using no_proxy_test::ProxyAndTargetServers;
  25422. // A stream request carries the credentials a buffered request does
  25423. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25424. no_proxy_test::ScopedServer origin;
  25425. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25426. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25427. });
  25428. origin.listen();
  25429. Client cli("127.0.0.1", origin.port());
  25430. cli.set_basic_auth("user", "pass");
  25431. auto handle = cli.open_stream("GET", "/x");
  25432. ASSERT_TRUE(handle.is_valid());
  25433. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25434. Client bearer("127.0.0.1", origin.port());
  25435. bearer.set_bearer_token_auth("tok");
  25436. auto handle2 = bearer.open_stream("GET", "/x");
  25437. ASSERT_TRUE(handle2.is_valid());
  25438. EXPECT_EQ("Bearer tok", read_all(handle2));
  25439. }
  25440. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25441. // takes its own credentials, as for a buffered request
  25442. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25443. std::string target, authz, proxy_authz;
  25444. no_proxy_test::ScopedServer proxy;
  25445. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25446. target = req.target;
  25447. authz = req.get_header_value("Authorization");
  25448. proxy_authz = req.get_header_value("Proxy-Authorization");
  25449. res.set_content("ok", "text/plain");
  25450. });
  25451. proxy.listen();
  25452. Client cli("origin.example", 8080);
  25453. cli.set_proxy("127.0.0.1", proxy.port());
  25454. cli.set_proxy_basic_auth("puser", "ppass");
  25455. cli.set_basic_auth("user", "pass");
  25456. auto handle = cli.open_stream("GET", "/x");
  25457. ASSERT_TRUE(handle.is_valid());
  25458. EXPECT_EQ("ok", read_all(handle));
  25459. EXPECT_EQ("http://origin.example:8080/x", target);
  25460. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25461. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25462. }
  25463. TEST(NoProxyTest, ExactHostnameBypasses) {
  25464. ProxyAndTargetServers s;
  25465. auto cli = make_client("example.com", s);
  25466. cli->set_no_proxy({"example.com"});
  25467. auto res = cli->Get("/");
  25468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25469. EXPECT_EQ(0, s.proxy_hits());
  25470. EXPECT_EQ(1, s.target_hits());
  25471. }
  25472. TEST(NoProxyTest, SubdomainBypasses) {
  25473. ProxyAndTargetServers s;
  25474. auto cli = make_client("foo.example.com", s);
  25475. cli->set_no_proxy({"example.com"});
  25476. auto res = cli->Get("/");
  25477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25478. EXPECT_EQ(0, s.proxy_hits());
  25479. EXPECT_EQ(1, s.target_hits());
  25480. }
  25481. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25482. // Regression guard: "evilexample.com" must not be considered a subdomain
  25483. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25484. // check would let traffic bypass the proxy and leak credentials direct
  25485. // to the attacker host.
  25486. ProxyAndTargetServers s;
  25487. auto cli = make_client("evilexample.com", s);
  25488. cli->set_no_proxy({"example.com"});
  25489. auto res = cli->Get("/");
  25490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25491. EXPECT_GE(s.proxy_hits(), 1);
  25492. EXPECT_EQ(0, s.target_hits());
  25493. }
  25494. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25495. ProxyAndTargetServers s;
  25496. auto cli = make_client("example.com.evil.com", s);
  25497. cli->set_no_proxy({"example.com"});
  25498. auto res = cli->Get("/");
  25499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25500. EXPECT_GE(s.proxy_hits(), 1);
  25501. EXPECT_EQ(0, s.target_hits());
  25502. }
  25503. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25504. ProxyAndTargetServers s;
  25505. auto cli = make_client("example.com", s);
  25506. cli->set_no_proxy({".example.com"});
  25507. auto res = cli->Get("/");
  25508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25509. EXPECT_EQ(0, s.proxy_hits());
  25510. EXPECT_EQ(1, s.target_hits());
  25511. }
  25512. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25513. ProxyAndTargetServers s;
  25514. auto cli = make_client("Example.COM", s);
  25515. cli->set_no_proxy({"EXAMPLE.com"});
  25516. auto res = cli->Get("/");
  25517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25518. EXPECT_EQ(0, s.proxy_hits());
  25519. EXPECT_EQ(1, s.target_hits());
  25520. }
  25521. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25522. ProxyAndTargetServers s;
  25523. auto cli = make_client("example.com.", s);
  25524. cli->set_no_proxy({"example.com"});
  25525. auto res = cli->Get("/");
  25526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25527. EXPECT_EQ(0, s.proxy_hits());
  25528. EXPECT_EQ(1, s.target_hits());
  25529. }
  25530. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25531. // Trailing dots must be normalized on BOTH sides — host and entry.
  25532. // An implementation that only strips the host-side trailing dot would
  25533. // fail to match host "example.com" against entry "example.com." because
  25534. // a literal substring search would compare 11 chars against 12.
  25535. ProxyAndTargetServers s;
  25536. auto cli = make_client("example.com", s);
  25537. cli->set_no_proxy({"example.com."});
  25538. auto res = cli->Get("/");
  25539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25540. EXPECT_EQ(0, s.proxy_hits());
  25541. EXPECT_EQ(1, s.target_hits());
  25542. }
  25543. TEST(NoProxyTest, WildcardBypassesEverything) {
  25544. ProxyAndTargetServers s;
  25545. auto cli = make_client("anything.invalid.test", s);
  25546. cli->set_no_proxy({"*"});
  25547. auto res = cli->Get("/");
  25548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25549. EXPECT_EQ(0, s.proxy_hits());
  25550. EXPECT_EQ(1, s.target_hits());
  25551. }
  25552. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25553. ProxyAndTargetServers s;
  25554. Client cli("127.0.0.1", s.target_port());
  25555. cli.set_proxy("127.0.0.1", s.proxy_port());
  25556. cli.set_no_proxy({"127.0.0.1"});
  25557. auto res = cli.Get("/");
  25558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25559. EXPECT_EQ(0, s.proxy_hits());
  25560. EXPECT_EQ(1, s.target_hits());
  25561. }
  25562. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25563. ProxyAndTargetServers s;
  25564. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25565. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25566. cli.set_proxy("127.0.0.1", s.proxy_port());
  25567. cli.set_no_proxy({"::1"});
  25568. auto res = cli.Get("/");
  25569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25570. EXPECT_EQ(0, s.proxy_hits());
  25571. EXPECT_EQ(1, s.target_hits());
  25572. }
  25573. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25574. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25575. // must still be recognized as IPv6 for CIDR matching. Implementations
  25576. // that detect IPv6 only when the host begins with '[' would parse the
  25577. // host as a hostname and miss the match.
  25578. ProxyAndTargetServers s;
  25579. Client cli("fe80::1", s.target_port());
  25580. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25581. cli.set_proxy("127.0.0.1", s.proxy_port());
  25582. cli.set_no_proxy({"fe80::/10"});
  25583. auto res = cli.Get("/");
  25584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25585. EXPECT_EQ(0, s.proxy_hits());
  25586. EXPECT_EQ(1, s.target_hits());
  25587. }
  25588. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25589. ProxyAndTargetServers s;
  25590. Client cli("::1", s.target_port());
  25591. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25592. cli.set_proxy("127.0.0.1", s.proxy_port());
  25593. cli.set_no_proxy({"[::1]"});
  25594. auto res = cli.Get("/");
  25595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25596. EXPECT_EQ(0, s.proxy_hits());
  25597. EXPECT_EQ(1, s.target_hits());
  25598. }
  25599. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25600. ProxyAndTargetServers s;
  25601. Client cli("fe80::1", s.target_port());
  25602. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25603. cli.set_proxy("127.0.0.1", s.proxy_port());
  25604. cli.set_no_proxy({"[fe80::]/10"});
  25605. auto res = cli.Get("/");
  25606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25607. EXPECT_EQ(0, s.proxy_hits());
  25608. EXPECT_EQ(1, s.target_hits());
  25609. }
  25610. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25611. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25612. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25613. // tricks via address-family conversion.
  25614. ProxyAndTargetServers s;
  25615. Client cli("::ffff:127.0.0.1", s.target_port());
  25616. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25617. cli.set_proxy("127.0.0.1", s.proxy_port());
  25618. cli.set_no_proxy({"127.0.0.1"});
  25619. auto res = cli.Get("/");
  25620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25621. EXPECT_GE(s.proxy_hits(), 1);
  25622. EXPECT_EQ(0, s.target_hits());
  25623. }
  25624. TEST(NoProxyTest, IPv4CidrMatch) {
  25625. ProxyAndTargetServers s;
  25626. Client cli("127.0.0.1", s.target_port());
  25627. cli.set_proxy("127.0.0.1", s.proxy_port());
  25628. cli.set_no_proxy({"127.0.0.0/8"});
  25629. auto res = cli.Get("/");
  25630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25631. EXPECT_EQ(0, s.proxy_hits());
  25632. EXPECT_EQ(1, s.target_hits());
  25633. }
  25634. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25635. ProxyAndTargetServers s;
  25636. Client cli("127.0.0.1", s.target_port());
  25637. cli.set_proxy("127.0.0.1", s.proxy_port());
  25638. cli.set_no_proxy({"10.0.0.0/8"});
  25639. auto res = cli.Get("/");
  25640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25641. EXPECT_GE(s.proxy_hits(), 1);
  25642. EXPECT_EQ(0, s.target_hits());
  25643. }
  25644. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25645. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25646. // IPv4 target matches.
  25647. ProxyAndTargetServers s;
  25648. Client cli("127.0.0.1", s.target_port());
  25649. cli.set_proxy("127.0.0.1", s.proxy_port());
  25650. cli.set_no_proxy({"0.0.0.0/0"});
  25651. auto res = cli.Get("/");
  25652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25653. EXPECT_EQ(0, s.proxy_hits());
  25654. EXPECT_EQ(1, s.target_hits());
  25655. }
  25656. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25657. ProxyAndTargetServers s;
  25658. Client cli("127.0.0.1", s.target_port());
  25659. cli.set_proxy("127.0.0.1", s.proxy_port());
  25660. cli.set_no_proxy({"127.0.0.1"});
  25661. auto res = cli.Get("/");
  25662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25663. EXPECT_EQ(0, s.proxy_hits());
  25664. EXPECT_EQ(1, s.target_hits());
  25665. }
  25666. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25667. ProxyAndTargetServers s;
  25668. Client cli("127.0.0.1", s.target_port());
  25669. cli.set_proxy("127.0.0.1", s.proxy_port());
  25670. cli.set_no_proxy({"127.0.0.0/33"});
  25671. auto res = cli.Get("/");
  25672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25673. EXPECT_GE(s.proxy_hits(), 1);
  25674. EXPECT_EQ(0, s.target_hits());
  25675. }
  25676. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25677. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25678. ProxyAndTargetServers s;
  25679. Client cli("127.0.0.1", s.target_port());
  25680. cli.set_proxy("127.0.0.1", s.proxy_port());
  25681. cli.set_no_proxy({"127.0.0.1/"});
  25682. auto res = cli.Get("/");
  25683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25684. EXPECT_GE(s.proxy_hits(), 1);
  25685. EXPECT_EQ(0, s.target_hits());
  25686. }
  25687. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25688. ProxyAndTargetServers s;
  25689. auto cli = make_client("internal.corp", s);
  25690. cli->set_proxy_basic_auth("u", "p");
  25691. cli->set_no_proxy({"internal.corp"});
  25692. auto res = cli->Get("/");
  25693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25694. EXPECT_EQ(1, s.target_hits());
  25695. EXPECT_EQ(0, s.proxy_hits());
  25696. EXPECT_FALSE(s.last_had_proxy_authz())
  25697. << "Proxy-Authorization must not be sent direct to the target";
  25698. }
  25699. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25700. ProxyAndTargetServers s;
  25701. auto cli = make_client("public.example", s);
  25702. cli->set_proxy_basic_auth("u", "p");
  25703. cli->set_no_proxy({"internal.corp"}); // does not match
  25704. auto res = cli->Get("/");
  25705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25706. EXPECT_GE(s.proxy_hits(), 1);
  25707. EXPECT_TRUE(s.last_had_proxy_authz());
  25708. }
  25709. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25710. std::atomic<int> hits{0};
  25711. std::atomic<int> hits_with_authz{0};
  25712. no_proxy_test::ScopedServer proxy_mock;
  25713. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25714. hits++;
  25715. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25716. if (req.target.find("/redir") != std::string::npos) {
  25717. res.set_redirect("http://other.example/landed");
  25718. } else {
  25719. res.set_content("via-proxy", "text/plain");
  25720. }
  25721. });
  25722. proxy_mock.listen();
  25723. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25724. hits = 0;
  25725. hits_with_authz = 0;
  25726. Client cli("public.example", 80);
  25727. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25728. cli.set_proxy_basic_auth(c.first, c.second);
  25729. cli.set_follow_location(true);
  25730. // The redirect to another host goes through the proxy as well
  25731. auto res = cli.Get("/redir");
  25732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25733. EXPECT_EQ(2, hits.load());
  25734. EXPECT_EQ(2, hits_with_authz.load());
  25735. }
  25736. }
  25737. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25738. ProxyAndTargetServers s;
  25739. auto cli = make_client("anything.test", s);
  25740. auto res = cli->Get("/");
  25741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25742. EXPECT_GE(s.proxy_hits(), 1);
  25743. EXPECT_EQ(0, s.target_hits());
  25744. }
  25745. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25746. ProxyAndTargetServers s;
  25747. auto cli = make_client("example.com", s);
  25748. cli->set_no_proxy({"example.com:8080"});
  25749. auto res = cli->Get("/");
  25750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25751. EXPECT_GE(s.proxy_hits(), 1);
  25752. EXPECT_EQ(0, s.target_hits());
  25753. }
  25754. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25755. ProxyAndTargetServers s;
  25756. auto cli = make_client("anything.test", s);
  25757. cli->set_no_proxy({"", " ", "\t"});
  25758. auto res = cli->Get("/");
  25759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25760. EXPECT_GE(s.proxy_hits(), 1);
  25761. EXPECT_EQ(0, s.target_hits());
  25762. }
  25763. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25764. // An entry with leading/trailing whitespace must still match — env-style
  25765. // values are commonly pasted with stray spaces and an implementation
  25766. // that feeds the raw token directly to inet_pton would fail to match
  25767. // valid CIDRs because of the spaces.
  25768. ProxyAndTargetServers s;
  25769. Client cli("127.0.0.1", s.target_port());
  25770. cli.set_proxy("127.0.0.1", s.proxy_port());
  25771. cli.set_no_proxy({" 127.0.0.0/8 "});
  25772. auto res = cli.Get("/");
  25773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25774. EXPECT_EQ(0, s.proxy_hits());
  25775. EXPECT_EQ(1, s.target_hits());
  25776. }
  25777. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25778. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25779. // go direct and must NOT carry Proxy-Authorization.
  25780. std::atomic<int> proxy_hits{0};
  25781. std::atomic<int> target_hits{0};
  25782. std::atomic<bool> target_saw_authz{false};
  25783. no_proxy_test::ScopedServer proxy_mock, target;
  25784. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25785. proxy_hits++;
  25786. res.status = 302;
  25787. res.set_header("Location", "http://127.0.0.1:" +
  25788. std::to_string(target.port()) + "/landed");
  25789. });
  25790. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25791. target_hits++;
  25792. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25793. res.set_content("direct", "text/plain");
  25794. });
  25795. proxy_mock.listen();
  25796. target.listen();
  25797. Client cli("public.example", target.port());
  25798. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25799. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25800. cli.set_proxy_basic_auth("u", "p");
  25801. cli.set_no_proxy({"127.0.0.1"});
  25802. cli.set_follow_location(true);
  25803. auto res = cli.Get("/redir");
  25804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25805. EXPECT_GE(proxy_hits.load(), 1);
  25806. EXPECT_GE(target_hits.load(), 1);
  25807. EXPECT_FALSE(target_saw_authz.load());
  25808. }
  25809. #ifdef CPPHTTPLIB_SSL_ENABLED
  25810. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25811. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25812. // proxy creds would be sent to the (possibly hostile) origin.
  25813. std::atomic<int> target_hits{0};
  25814. std::atomic<bool> target_saw_proxy_authz{false};
  25815. no_proxy_test::ScopedServer target;
  25816. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25817. target_hits++;
  25818. if (req.has_header("Proxy-Authorization")) {
  25819. target_saw_proxy_authz = true;
  25820. }
  25821. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25822. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25823. "nonce=\"abc\", algorithm=MD5");
  25824. });
  25825. target.listen();
  25826. // The proxy address is set to the target's port: the bypass MUST kick in;
  25827. // if it doesn't, the test still routes "via proxy" to the same server and
  25828. // the Proxy-Authorization assertion below catches the leak.
  25829. Client cli("evil.example", target.port());
  25830. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25831. cli.set_proxy("127.0.0.1", target.port());
  25832. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25833. cli.set_no_proxy({"evil.example"});
  25834. auto res = cli.Get("/x");
  25835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25836. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25837. EXPECT_EQ(1, target_hits.load());
  25838. EXPECT_FALSE(target_saw_proxy_authz.load());
  25839. }
  25840. #endif
  25841. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25842. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25843. std::atomic<int> proxy_hits{0};
  25844. std::atomic<int> bypass_hits{0};
  25845. std::atomic<bool> proxy_saw_c_url{false};
  25846. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25847. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25848. proxy_hits++;
  25849. if (req.path.find("/start") != std::string::npos) {
  25850. res.status = 302;
  25851. res.set_header("Location", "http://127.0.0.1:" +
  25852. std::to_string(bypass_server.port()) +
  25853. "/middle");
  25854. return;
  25855. }
  25856. if (req.path.find("/end") != std::string::npos) {
  25857. proxy_saw_c_url = true;
  25858. res.set_content("c-via-proxy", "text/plain");
  25859. return;
  25860. }
  25861. res.set_content("unexpected", "text/plain");
  25862. });
  25863. // public.example's "advertised" port is arbitrary (the request never lands
  25864. // there — it goes through the proxy), but use a dynamic value to stay
  25865. // friendly with sharded parallel runs.
  25866. int public_port = bypass_server.port();
  25867. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25868. bypass_hits++;
  25869. res.status = 302;
  25870. res.set_header("Location", "http://public.example:" +
  25871. std::to_string(public_port) + "/end");
  25872. });
  25873. proxy_mock.listen();
  25874. bypass_server.listen();
  25875. Client cli("public.example", public_port);
  25876. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25877. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25878. cli.set_no_proxy({"127.0.0.1"});
  25879. cli.set_follow_location(true);
  25880. auto res = cli.Get("/start");
  25881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25882. EXPECT_EQ(StatusCode::OK_200, res->status);
  25883. EXPECT_EQ("c-via-proxy", res->body);
  25884. EXPECT_GE(proxy_hits.load(), 2);
  25885. EXPECT_GE(bypass_hits.load(), 1);
  25886. EXPECT_TRUE(proxy_saw_c_url.load());
  25887. }
  25888. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25889. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25890. // request reconnects to the correct endpoint.
  25891. std::atomic<int> proxy_hits{0};
  25892. std::atomic<int> target_hits{0};
  25893. no_proxy_test::ScopedServer proxy_mock, target;
  25894. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25895. proxy_hits++;
  25896. res.set_content("via-proxy", "text/plain");
  25897. });
  25898. target.svr().Get(".*", [&](const Request &, Response &res) {
  25899. target_hits++;
  25900. res.set_content("direct", "text/plain");
  25901. });
  25902. proxy_mock.listen();
  25903. target.listen();
  25904. Client cli("public.example", target.port());
  25905. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25906. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25907. cli.set_keep_alive(true);
  25908. auto res1 = cli.Get("/a");
  25909. ASSERT_TRUE(res1);
  25910. EXPECT_EQ("via-proxy", res1->body);
  25911. EXPECT_EQ(1, proxy_hits.load());
  25912. EXPECT_EQ(0, target_hits.load());
  25913. cli.set_no_proxy({"public.example"});
  25914. auto res2 = cli.Get("/b");
  25915. ASSERT_TRUE(res2);
  25916. EXPECT_EQ("direct", res2->body);
  25917. EXPECT_EQ(1, proxy_hits.load());
  25918. EXPECT_EQ(1, target_hits.load());
  25919. }
  25920. // Forward declarations (see the base64_encode note).
  25921. namespace httplib {
  25922. namespace detail {
  25923. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25924. int shutdown_socket(socket_t sock) noexcept;
  25925. } // namespace detail
  25926. } // namespace httplib
  25927. namespace proxy_tunnel_test {
  25928. const char *const kTunnelEstablished =
  25929. "HTTP/1.1 200 Connection established\r\n\r\n";
  25930. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25931. using ConnectReply = std::function<std::string(const std::string &head)>;
  25932. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25933. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25934. class ScopedConnectProxy {
  25935. public:
  25936. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25937. : forward_port_(forward_port), reply_(std::move(reply)) {
  25938. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25939. if (listen_sock_ == INVALID_SOCKET) { return; }
  25940. auto a = loopback(0);
  25941. auto addr = reinterpret_cast<sockaddr *>(&a);
  25942. socklen_t alen = sizeof(a);
  25943. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25944. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25945. ::listen(listen_sock_, 4) != 0) {
  25946. return;
  25947. }
  25948. port_ = ntohs(a.sin_port);
  25949. th_ = std::thread([this] { run(); });
  25950. }
  25951. ~ScopedConnectProxy() {
  25952. if (th_.joinable()) {
  25953. stop_ = true;
  25954. auto wake = connect_to(port_);
  25955. th_.join();
  25956. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25957. }
  25958. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25959. }
  25960. int port() const { return port_; }
  25961. int connect_hits() const { return connect_hits_.load(); }
  25962. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25963. std::string connect_request() const {
  25964. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25965. return connect_request_;
  25966. }
  25967. private:
  25968. static sockaddr_in loopback(int port) {
  25969. sockaddr_in a{};
  25970. a.sin_family = AF_INET;
  25971. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25972. a.sin_port = htons(static_cast<unsigned short>(port));
  25973. return a;
  25974. }
  25975. static socket_t connect_to(int port) {
  25976. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25977. if (sock == INVALID_SOCKET) { return sock; }
  25978. auto a = loopback(port);
  25979. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25980. detail::close_socket(sock);
  25981. return INVALID_SOCKET;
  25982. }
  25983. return sock;
  25984. }
  25985. static bool send_all(socket_t sock, const char *data, size_t size) {
  25986. while (size > 0) {
  25987. auto n = detail::send_socket(sock, data, size, 0);
  25988. if (n <= 0) { return false; }
  25989. data += n;
  25990. size -= static_cast<size_t>(n);
  25991. }
  25992. return true;
  25993. }
  25994. void run() {
  25995. for (;;) {
  25996. auto client = ::accept(listen_sock_, nullptr, nullptr);
  25997. if (stop_) {
  25998. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  25999. return;
  26000. }
  26001. if (client == INVALID_SOCKET) { continue; }
  26002. serve(client);
  26003. detail::close_socket(client);
  26004. }
  26005. }
  26006. void serve(socket_t client) {
  26007. std::string head;
  26008. char buf[2048];
  26009. while (head.find("\r\n\r\n") == std::string::npos) {
  26010. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26011. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26012. if (n <= 0) { return; }
  26013. head.append(buf, static_cast<size_t>(n));
  26014. }
  26015. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26016. connect_hits_++;
  26017. {
  26018. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26019. connect_request_ = head;
  26020. }
  26021. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26022. if (!send_all(client, res.data(), res.size()) ||
  26023. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26024. return;
  26025. }
  26026. auto origin = connect_to(forward_port_);
  26027. if (origin == INVALID_SOCKET) { return; }
  26028. // When either side stops, shut both down so the other pump returns too.
  26029. auto pump = [&](socket_t from, socket_t to) {
  26030. char b[8192];
  26031. for (;;) {
  26032. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26033. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26034. }
  26035. detail::shutdown_socket(client);
  26036. detail::shutdown_socket(origin);
  26037. };
  26038. std::thread up([&] { pump(client, origin); });
  26039. pump(origin, client);
  26040. up.join();
  26041. detail::close_socket(origin);
  26042. }
  26043. int forward_port_;
  26044. ConnectReply reply_;
  26045. socket_t listen_sock_ = INVALID_SOCKET;
  26046. int port_ = 0;
  26047. std::thread th_;
  26048. std::atomic<bool> stop_{false};
  26049. std::atomic<int> connect_hits_{0};
  26050. mutable std::mutex connect_request_mutex_;
  26051. std::string connect_request_;
  26052. };
  26053. } // namespace proxy_tunnel_test
  26054. #ifdef CPPHTTPLIB_SSL_ENABLED
  26055. namespace proxy_tunnel_test {
  26056. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26057. class ScopedSSLServer {
  26058. public:
  26059. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26060. port_ = svr_.bind_to_any_port("127.0.0.1");
  26061. }
  26062. ~ScopedSSLServer() {
  26063. svr_.stop();
  26064. if (th_.joinable()) { th_.join(); }
  26065. }
  26066. SSLServer &svr() { return svr_; }
  26067. int port() const { return port_; }
  26068. void listen() {
  26069. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26070. svr_.wait_until_ready();
  26071. }
  26072. private:
  26073. SSLServer svr_;
  26074. std::thread th_;
  26075. int port_ = 0;
  26076. };
  26077. // Sends one request through the CONNECT proxy to the TLS origin with a
  26078. // credential configured for each hop, and checks that each credential reaches
  26079. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26080. // origin's (every header in origin_headers) on the tunnelled request.
  26081. void CredentialsStayWithTheirHop(
  26082. const std::function<void(SSLClient &)> &set_credentials,
  26083. const std::string &scheme,
  26084. const std::vector<std::string> &origin_headers = {"Authorization"},
  26085. bool stream = false) {
  26086. std::atomic<int> origin_hits{0};
  26087. std::atomic<bool> origin_saw_proxy_authz{false};
  26088. std::atomic<bool> origin_saw_headers{false};
  26089. ScopedSSLServer origin;
  26090. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26091. origin_hits++;
  26092. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26093. origin_saw_headers =
  26094. std::all_of(origin_headers.begin(), origin_headers.end(),
  26095. [&](const std::string &h) { return req.has_header(h); });
  26096. res.set_content("ok", "text/plain");
  26097. });
  26098. origin.listen();
  26099. ScopedConnectProxy proxy(origin.port());
  26100. ASSERT_NE(0, proxy.port());
  26101. // Pinned to 127.0.0.1 for the same reason as the test below.
  26102. SSLClient cli("127.0.0.1", origin.port());
  26103. cli.enable_server_certificate_verification(false);
  26104. cli.set_proxy("127.0.0.1", proxy.port());
  26105. set_credentials(cli);
  26106. if (stream) {
  26107. auto handle = cli.open_stream("GET", "/x");
  26108. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26109. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26110. } else {
  26111. auto res = cli.Get("/x");
  26112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26113. EXPECT_EQ(StatusCode::OK_200, res->status);
  26114. }
  26115. EXPECT_EQ(1, origin_hits.load());
  26116. EXPECT_EQ(1, proxy.connect_hits());
  26117. EXPECT_TRUE(origin_saw_headers.load());
  26118. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26119. << "Proxy-Authorization must not be sent inside the tunnel";
  26120. auto connect_req = proxy.connect_request();
  26121. EXPECT_NE(std::string::npos,
  26122. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26123. for (const auto &h : origin_headers) {
  26124. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26125. << h << " must not be sent to the proxy on CONNECT";
  26126. }
  26127. }
  26128. } // namespace proxy_tunnel_test
  26129. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26130. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26131. [](SSLClient &cli) {
  26132. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26133. cli.set_basic_auth("origin-user", "origin-pass");
  26134. },
  26135. "Basic");
  26136. }
  26137. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26138. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26139. [](SSLClient &cli) {
  26140. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26141. cli.set_basic_auth("origin-user", "origin-pass");
  26142. },
  26143. "Basic", {"Authorization"}, true);
  26144. }
  26145. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26146. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26147. [](SSLClient &cli) {
  26148. cli.set_proxy_bearer_token_auth("proxy-token");
  26149. cli.set_bearer_token_auth("origin-token");
  26150. },
  26151. "Bearer");
  26152. }
  26153. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26154. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26155. [](SSLClient &cli) {
  26156. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26157. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26158. {"Cookie", "sid=origin-session"},
  26159. {"X-Api-Key", "origin-key"}});
  26160. },
  26161. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26162. }
  26163. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26164. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26165. // retry; otherwise proxy creds would be sent to the origin.
  26166. std::atomic<int> origin_hits{0};
  26167. std::atomic<bool> origin_saw_proxy_authz{false};
  26168. proxy_tunnel_test::ScopedSSLServer origin;
  26169. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26170. origin_hits++;
  26171. if (req.has_header("Proxy-Authorization")) {
  26172. origin_saw_proxy_authz = true;
  26173. }
  26174. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26175. res.set_header("Proxy-Authenticate",
  26176. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26177. "algorithm=MD5");
  26178. });
  26179. origin.listen();
  26180. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26181. ASSERT_NE(0, proxy.port());
  26182. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26183. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26184. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26185. // and answer with its own status, making this test flaky.
  26186. SSLClient cli("127.0.0.1", origin.port());
  26187. cli.enable_server_certificate_verification(false);
  26188. cli.set_proxy("127.0.0.1", proxy.port());
  26189. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26190. auto res = cli.Get("/x");
  26191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26192. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26193. EXPECT_EQ(1, origin_hits.load());
  26194. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26195. EXPECT_EQ(1, proxy.connect_hits());
  26196. }
  26197. #endif
  26198. namespace proxy_tunnel_test {
  26199. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26200. // anything else gets a 407 with `challenge`.
  26201. ConnectReply require_proxy_auth(const std::string &expected,
  26202. const std::string &challenge) {
  26203. return [=](const std::string &head) -> std::string {
  26204. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26205. std::string::npos) {
  26206. return kTunnelEstablished;
  26207. }
  26208. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26209. "Proxy-Authenticate: " +
  26210. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26211. };
  26212. }
  26213. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26214. // request, then echoes.
  26215. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26216. ws.send(
  26217. "authorization:" + req.get_header_value("Authorization") +
  26218. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26219. std::string msg;
  26220. while (ws.read(msg)) {
  26221. ws.send(msg);
  26222. }
  26223. }
  26224. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26225. class ScopedWebSocketOrigin {
  26226. public:
  26227. ScopedWebSocketOrigin() {
  26228. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26229. server_.listen();
  26230. }
  26231. int port() const { return server_.port(); }
  26232. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26233. std::string url() const {
  26234. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26235. }
  26236. private:
  26237. no_proxy_test::ScopedServer server_;
  26238. };
  26239. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26240. // passed as a constructor header, and checks that each reaches only its hop.
  26241. void WebSocketCredentialsStayWithTheirHop(
  26242. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26243. const std::string &proxy_authz, const std::string &origin_authz) {
  26244. ScopedWebSocketOrigin origin;
  26245. ScopedConnectProxy proxy(
  26246. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26247. ASSERT_NE(0, proxy.port());
  26248. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26249. client.set_proxy("127.0.0.1", proxy.port());
  26250. set_proxy_credentials(client);
  26251. auto res = client.connect();
  26252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26253. std::string msg;
  26254. ASSERT_TRUE(client.read(msg));
  26255. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26256. client.close();
  26257. EXPECT_EQ(1, proxy.connect_hits());
  26258. EXPECT_EQ(std::string::npos,
  26259. proxy.connect_request().find("\r\nAuthorization: "))
  26260. << "origin credentials must not be sent to the proxy";
  26261. }
  26262. } // namespace proxy_tunnel_test
  26263. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26264. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26265. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26266. ASSERT_NE(0, proxy.port());
  26267. ws::WebSocketClient client(origin.url());
  26268. client.set_proxy("127.0.0.1", proxy.port());
  26269. auto res = client.connect();
  26270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26271. std::string msg;
  26272. ASSERT_TRUE(client.read(msg));
  26273. ASSERT_TRUE(client.send("hello"));
  26274. ASSERT_TRUE(client.read(msg));
  26275. EXPECT_EQ("hello", msg);
  26276. client.close();
  26277. EXPECT_EQ(1, proxy.connect_hits());
  26278. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26279. auto connect_req = proxy.connect_request();
  26280. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26281. EXPECT_NE(std::string::npos,
  26282. connect_req.find("\r\nHost: " + target + "\r\n"));
  26283. }
  26284. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26285. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26286. [](ws::WebSocketClient &cli) {
  26287. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26288. },
  26289. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26290. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26291. }
  26292. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26293. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26294. [](ws::WebSocketClient &cli) {
  26295. cli.set_proxy_bearer_token_auth("proxy-token");
  26296. },
  26297. "Bearer proxy-token", "Bearer origin-token");
  26298. }
  26299. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26300. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26301. proxy_tunnel_test::ScopedConnectProxy proxy(
  26302. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26303. "Basic " + detail::base64_encode("proxy-user:"),
  26304. "Basic realm=\"proxy\""));
  26305. ASSERT_NE(0, proxy.port());
  26306. ws::WebSocketClient client(origin.url());
  26307. client.set_proxy("127.0.0.1", proxy.port());
  26308. client.set_proxy_basic_auth("proxy-user", "");
  26309. auto res = client.connect();
  26310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26311. client.close();
  26312. EXPECT_EQ(1, proxy.connect_hits());
  26313. }
  26314. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26315. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26316. proxy_tunnel_test::ScopedConnectProxy proxy(
  26317. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26318. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26319. ASSERT_NE(0, proxy.port());
  26320. ws::WebSocketClient client(origin.url());
  26321. client.set_proxy("127.0.0.1", proxy.port());
  26322. auto res = client.connect();
  26323. EXPECT_FALSE(res);
  26324. EXPECT_EQ(Error::ProxyConnection, res.error());
  26325. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26326. EXPECT_EQ("Basic realm=\"proxy\"",
  26327. res.get_header_value("Proxy-Authenticate"));
  26328. EXPECT_FALSE(client.is_open());
  26329. }
  26330. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26331. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26332. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26333. ASSERT_NE(0, proxy.port());
  26334. ws::WebSocketClient client(origin.url());
  26335. client.set_proxy("127.0.0.1", proxy.port());
  26336. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26337. client.set_no_proxy({"127.0.0.1"});
  26338. auto res = client.connect();
  26339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26340. std::string msg;
  26341. ASSERT_TRUE(client.read(msg));
  26342. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26343. << "proxy credentials must not reach a bypassed origin";
  26344. client.close();
  26345. EXPECT_EQ(0, proxy.connect_hits());
  26346. }
  26347. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  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. ASSERT_TRUE(client.connect());
  26354. ASSERT_TRUE(client.connect());
  26355. client.close();
  26356. EXPECT_EQ(2, proxy.connect_hits());
  26357. }
  26358. #ifdef CPPHTTPLIB_SSL_ENABLED
  26359. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26360. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26361. proxy_tunnel_test::ScopedConnectProxy proxy(
  26362. origin.port(), [](const std::string &head) -> std::string {
  26363. if (head.find(
  26364. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26365. std::string::npos) {
  26366. return proxy_tunnel_test::kTunnelEstablished;
  26367. }
  26368. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26369. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26370. "nonce=\"abc\", algorithm=MD5\r\n"
  26371. "Content-Length: 0\r\n\r\n";
  26372. });
  26373. ASSERT_NE(0, proxy.port());
  26374. ws::WebSocketClient client(origin.url());
  26375. client.set_proxy("127.0.0.1", proxy.port());
  26376. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26377. auto res = client.connect();
  26378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26379. std::string msg;
  26380. ASSERT_TRUE(client.read(msg));
  26381. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26382. client.close();
  26383. EXPECT_EQ(2, proxy.connect_hits());
  26384. }
  26385. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26386. proxy_tunnel_test::ScopedSSLServer origin;
  26387. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26388. origin.listen();
  26389. proxy_tunnel_test::ScopedConnectProxy proxy(
  26390. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26391. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26392. ASSERT_NE(0, proxy.port());
  26393. ws::WebSocketClient client(
  26394. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26395. client.enable_server_certificate_verification(false);
  26396. client.set_proxy("127.0.0.1", proxy.port());
  26397. client.set_proxy_bearer_token_auth("proxy-token");
  26398. auto res = client.connect();
  26399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26400. std::string msg;
  26401. ASSERT_TRUE(client.read(msg));
  26402. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26403. << "Proxy-Authorization must not be sent inside the tunnel";
  26404. client.close();
  26405. EXPECT_EQ(1, proxy.connect_hits());
  26406. }
  26407. #endif